cznic/public/: django-pain-3.1.0 metadata and description
Django application for managing bank payments and invoices
author | Jan Musílek |
author_email | jan.musilek@nic.cz |
classifiers |
|
license | GPLv3+ |
provides_extras | types |
requires_dist |
|
requires_python | ~=3.8 |
Because this project isn't in the mirror_whitelist
,
no releases from root/pypi are included.
File | Tox results | History |
---|---|---|
django_pain-3.1.0-py3-none-any.whl
|
|
|
django_pain-3.1.0.tar.gz
|
|
Django application for processing bank payments and invoices.
Bank statements are passed through a parser and imported to a database. So far, there is only one parser available, TransprocXMLParser, used to process bank statements collected and transformed by fred-transproc. Parsers may also be implemented as django-pain plugins.
Imported payments are regularly processed by payment processors. The processors are usually implemented as django-pain plugins, implementing payment processor interface.
Bank accounts and payments may be managed through a Django admin site.
Installation
You need to add django_pain.apps.DjangoPainConfig and django_lang_switch.apps.DjangoLangSwitchConfig to your INSTALLED_APPS. In order for user interface to work, you also need to add the Django admin site. See Django docs for detailed description.
You also need to include django_pain, admin and django_lang_switch urls into your project urls.py:
urlpatterns = [
...
path('pain/', include('django_pain.urls')),
path('admin/', admin.site.urls),
path('django_lang_switch/', include('django_lang_switch.urls')),
...
]
After installing the django-pain package and configuring your Django project, you need to generate migrations. Call django-admin makemigrations. These migrations depend on LANGUAGES and CURRENCIES settings, so think carefully how you set them. If you decide to change these settings in the future, you need to generate the migrations again.
Also, JavaScript files use the new ECMAScript 2017 notation and need to be transpiled in order to work in most of current browsers. Assuming you have Node.js and npm installed, you need to install necessary packages first by calling npm install from the command line. After that, you can transpile the JavaScript code by calling npm run build.
Requirements
All requirements are resolved during package installation, see install_requires in setup.cfg.
If you wish to use LDAP authentication, you can use django-python3-ldap.
Plugins
auctions-pain
https://gitlab.office.nic.cz/others/auctions-pain
Provides payment processor for domain auctions.
donations-pain
https://gitlab.office.nic.cz/django-apps/donations-pain
Provides payment processor for donations to CZ.NIC projects and other activities.
fred-pain
https://gitlab.office.nic.cz/fred/pain
Provides payment processor for FRED.
payments-pain
https://gitlab.office.nic.cz/ginger/payments-pain
Provides payment processor for Ginger Payments (and therefore the Academy).
Settings
In order for django-pain to work, you need to define some settings in your settings.py.
PAIN_PROCESSORS
A required setting containing a dictionary of payment processor names and dotted paths to payment processors classes. The payments are offered to the payment processors in that order.
Example configuration:
PAIN_PROCESSORS = {
'fred': 'fred_pain.processors.FredPaymentProcessor',
'payments': 'payments_pain.processors.PaymentsPaymentProcessor',
'ignore': 'django_pain.processors.IgnorePaymentProcessor',
}
You should not change processor names unless you have a very good reason. In that case, you also need to take care of changing processor names saved in the database.
When you change this setting (including the initial setup), you have to run django-admin migrate. Permissions for manual assignment to individual payment processors are created in this step.
PAIN_PROCESS_PAYMENTS_LOCK_FILE
Path to the lock file for the process_payments command. The default value is /tmp/pain_process_payments.lock.
PAIN_TRIM_VARSYM
Boolean setting. If True, bank statement parser removes leading zeros from the variable symbol. Default is False.
PAIN_DOWNLOADERS
A setting containing dotted paths to payment downloader and parser classes and downloader parameters. There should be a separate entry in the dictionary for each bank from which payments should be downloaded. The downloaders and parsers are provided in teller library.
Example configuration:
PAIN_DOWNLOADERS = {
'test_bank': {'DOWNLOADER': 'teller.downloaders.TestStatementDownloader',
'PARSER': 'teller.downloaders.TestStatementParser',
'DOWNLOADER_PARAMS': {'base_url': 'https://bank.test', 'password': 'letmein'}}
}
PAIN_IMPORT_CALLBACKS
List setting containing dotted paths to callables.
Each value of the list should be dotted path refering to callable that takes BankPayment object as its argument and returns (possibly) changed BankPayment. This callable is called right before the payment is saved during the import. Especially, this callable can throw ValidationError in order to avoid saving payment to the database. Default value is empty list.
PAIN_CARD_PAYMENT_HANDLERS
A setting that assigns names to card payment handlers.
Handlers implement bank and payment method specific functionality of card payment operations. Keys in a dictionary stand for handler names, values consist of handler dotted path (HANDLER) and gateway name (GATEWAY). CSOB handlers read additional gateway parameters from related section in PAIN_CSOB_GATEWAYS. Card payment operations are started with an appropriate handler name as a required parameter.
Example configuration:
PAIN_CARD_PAYMENT_HANDLERS = {
'csob': {'HANDLER': 'django_pain.card_payment_handlers.csob.CSOBCardPaymentHandler', 'GATEWAY': 'default'},
'csob_custom': {'HANDLER': 'django_pain.card_payment_handlers.csob.CSOBCustomPaymentHandler', 'GATEWAY': 'default'},
'csob_auctions': {'HANDLER': 'django_pain.card_payment_handlers.csob.CSOBCustomPaymentHandler', 'GATEWAY': 'auctions'},
}
PAIN_CSOB_GATEWAYS
Settings for CSOB payment gateways as a dictionary with parameters for each gateway.
API_URL, API_PUBLIC_KEY, MERCHANT_ID and MERCHANT_PRIVATE_KEY contain parameters provided by CSOB bank. ACCOUNT_NUMBERS is a mapping assigning accounts to curency codes. CSOB payment gateway may accept payments in different currencies. For each currency there has to be an account held in that currency associated with the gateway. The associated accounts have to be specified in ACCOUNT_NUMBERS setting so we are able to choose the correct account when recording the payments in the application. The values of the mapping are account numbers as recorded in the database. Optional ACCOUNT_LIMITS mapping allows to handle a payment exceeding limit appropriately in advance (instead of generic transaction failure).
Example configuration:
PAIN_CSOB_GATEWAYS = {
'default': {
'API_URL': 'https://api.platebnibrana.csob.cz/api/v1.9/',
'API_PUBLIC_KEY': 'path/to/public_key.txt',
'MERCHANT_ID': 'abc123',
'MERCHANT_PRIVATE_KEY': 'path/to/private_key1.txt',
'ACCOUNT_NUMBERS': {'CZK': '123456', 'EUR': '234567'},
},
'auctions': {
'API_URL': 'https://api.platebnibrana.csob.cz/api/v1.9/',
'API_PUBLIC_KEY': 'path/to/public_key.txt',
'MERCHANT_ID': 'def456',
'MERCHANT_PRIVATE_KEY': 'path/to/private_key2.txt',
'ACCOUNT_NUMBERS': {'CZK': '987654'},
'ACCOUNT_LIMITS': {'CZK': 500000},
},
}
PAIN_CSOB_CUSTOM_HANDLER
Settings specific for CSOB custom payment handler. MIN_VALIDITY and MAX_VALIDITY define boundaries of validity of custom payment (provided in custom_expiry parameter to init_payment method call). These are integer values in seconds with defaults of 1 day for the minimum and slightly less than 59 days for the maximum (because of limit defined by CSOB). Optional URL parameter CUSTOM_PAYMENT_URL is used together with payment customer code to form the CSOB gateway link and defaults to https://platebnibrana.csob.cz/zaplat/. Agent for dispatching e-mails is initialized with network location (i.e. host and port) in MESSENGER_NETLOC (localhost:50051 by default) and security credentials (i.e. path to TLS certificate) in MESSENGER_SSL_CERT (empty, i.e. insecure connection by default). Re-sending emails (disabled by default) can be configured with RESEND_EMAIL dictionary: list TIME_DELTAS contains integers defining times to send remainder (in days, positive values are relative to payment creation, negative values relative to payment expiry, defaults to empty list), MIN_DELTA is the minimum interval between two emails (in days, defaults to 3 days) and PROCESSORS is a list of payment processors with remainders active (defaults to None, i.e. enabled regardless of processor).
Example of full configuration:
PAIN_CSOB_CUSTOM_HANDLER = {
'MIN_VALIDITY': 14400,
'MAX_VALIDITY': 864000,
'CUSTOM_PAYMENT_URL': 'https://platebnibrana.csob.cz/zaplat/',
'MESSENGER_NETLOC': 'localhost:50051',
'MESSENGER_SSL_CERT': 'path/to/certificate.pem',
'RESEND_EMAIL': {
'TIME_DELTAS': [-3],
'MIN_DELTA': 2,
'PROCESSORS': ['auctions'],
},
}
Please note that CSOB custom payment handler uses settings in PAIN_CSOB_CARD section as well.
PAIN_EU_MEMBERS
List of countries that are members of the EU. Items are two-letter strings with ISO-3166 country codes. The default is a list of 27 countries as of EU members in December 2023.
PAIN_VIES_REQUESTER
VIES system is used for validation of VAT numbers of customers. Its REST API requires a valid VAT number of requester (this is a required setting).
PAIN_PAYMENT_REQUESTS
Setting for payment requests consists of dictionary of application (by its app_id) and related values provided again as dictionary with keys: CARD_HANDLER (value is name of card payment handler configured in PAIN_CARD_PAYMENT_HANDLERS) and PROCESSOR (value is name of processor configured in PAIN_PROCESSORS).
Example:
PAIN_PAYMENT_REQUESTS = {
'auctions': {'CARD_HANDLER': 'csob_auctions', 'PROCESSOR': 'auctions'},
}
PAIN_FILEMAN_NETLOC
Network location in form host:port of the gRPC server with fileman service.
PAIN_FILEMAN_SSL_CERT
Path to file with TLS certificate. Default value is None, which means insecure connection.
PAIN_SECRETARY_URL
URL of django-secretary service (including the path to the API and trailing slash).
PAIN_SECRETARY_TIMEOUT
A timeout for connection to django-secretary service. For possible values see documentation of requests library, default value is 3.05 (in seconds).
PAIN_SECRETARY_TOKEN
Token for authentication to django-secretary service. Default value is None, which means no authentication.
Commands
import_payments
import_payments --parser PARSER [input file [input file ...]]
Import payments from the bank. A bank statement should be provided on the standard input or in a file as a positional parameter.
The mandatory argument PARSER must be a dotted path to a payment-parser class such as django_pain.parsers.transproc.TransprocXMLParser.
download_payments
download_payments [--start START] [--end END] [--downloader DOWNLOADER]
Download payments from the banks.
There are two optional arguments --start and --end which set the download interval for which the banks will be queried. Both parameters should be entered as date and time in ISO format. Default value for END is today. Default value for START is seven days before END.
Example download_payments --start 2020-09-01T00:00 --end 2020-10-31T23:59
Optional repeatable parameter --downloader selects which downloaders defined in the PAIN_DOWNLOADERS settings will be used. If the parameter is omitted all defined downloaders will be used.
Example download_payments --downloader somebank --downloader someotherbank
list_payments
list_payments [--exclude-accounts ACCOUNTS]
[--include-accounts ACCOUNTS]
[--limit LIMIT] [--state STATE]
List bank payments.
The options --exclude-accounts and --include-accounts are mutually exclusive and expect a comma-separated list of bank account numbers.
Option --state can be either initialized, ready_to_process, processed, deferred, exported, canceled, to_refund or refunded.
If --limit LIMIT is set, the command will list at most LIMIT payments. If there are any non-listed payments, the command will announce their count.
process_payments
process_payments [--from TIME_FROM] [--to TIME_TO]
Process unprocessed payments with predefined payment processors.
The command takes all payments in the states ready_to_process or deferred and offers them to the individual payment processors. If any processor accepts the payment, then payment’s state is switched to processed. Otherwise, its state is switched to deferred.
The options --from and --to limit payments to be processed by their creation date. They expect an ISO-formatted datetime value.
get_card_payments_states
get_card_payments_states [--from TIME_FROM] [--to TIME_TO]
Check and update states of card payments.
The command takes all card payments in the initialized state and checks their current state with the bank payment gateway. Payment states are updated accordingly. Each bank/payment method uses a dedicated handler of its own for communication with the bank.
The options --from and --to limit payments to be processed by their creation date. They expect an ISO-formatted datetime value.
check_vat_number
check_vat_number [--interval DAYS] [--timeout TIMEOUT]
Check customers in a database for valid VAT numbers with external system. It checks new (i.e. not processed yet) customers as well as regularly re-checks other customers (interval defaults to 14 days). Timeout value (integer or float in seconds) is used for calls to a VAT number validation service (default is 10.0 s).
create_invoice
create_invoice
Create invoice for newly realized payment requests where applicable. Evaluate proper VAT rate for each item, time supply point and calculate total base price, VAT and price including VAT. Invoice numbers for each application should form a uninterrupted sequence within a year.
create_pdf
create_pdf [--type=payment_request] [--type=invoice]
Create a PDF document for objects of given types (i.e. payment requests, invoices or both) and store them in the file repository. File identifier is stored with the object (is available via REST API), such objects are skipped from processing during subsequent runs.
export_invoice
export_invoice --from TIME_FROM --to TIME_TO
Export invoices created within provided time interval into XML format suitable for further processing by Helios accounting software.
Resulted data are directed to standard output which makes it easy to process them further by the calling process.
The required parameters --from and --to are expected as ISO-formatted datetime values.
Changes
See CHANGELOG.
Changelog
3.1.0 (2024-04-07)
New features
Add support for invoices (summary in #27)
Maintenace and fixes
Add logging to REST endpoints (#90)
Drop support for Django 3.2 (#100)
Use timestamps with time zone in tests (#101)
Replace pytz with timezone info from standard library
Fix CSS in admin interface (#103)
Update typist dependency
Allow EU customers with VAT number from other EU country (#105)
Fix VAT number prefix for Greek subjects (#118)
Handle exceeding daily limit on card payment gateway (#111)
Fix cart item price for card payments (#122)
3.0.3 (2024-04-05)
Maintenance and fixes
Fix due date in context for payment request PDF (#110)
3.0.2 (2024-04-03)
Maintenance and fixes
Fix admin interface for bank payments (#103)
Support localization of payment requst items in PDF (#115)
Change contents in payment QR code (#107)
3.0.1 (2024-03-21)
Maintenance and fixes
Fix transaction date in card payment processing (#102)
3.0.0 (2024-03-18)
New features
Add support for payment requests (summary in #27)
Add payment states for refunding (#47)
Breaking changes
Support multiple gateways (configuration - #24)
Rename data models Client (#28) and Invoice (#26)
Change payments processing result (#57) and its location (#58)
Maintenance and fixes
Drop support for Python 3.7 (#61)
Replace ordered dict with dict (#25)
Check payment parameter in card handler methods (#52)
Refactor payment processor result handling (consistent logging) (#58)
Replace custom StrEnum with implementation from backports
Fix handling processor exception (#59)
Fix requirement for django-rest-framework
Fix list and detail with “initialized” bank payments in admin interface (#87, #91)
Check card payment amount with limit in settings (#92)
2.5.0 (2023-09-22)
New features
Add support for CSOB custom payments with CSOBCustomPaymentHandler (summary in #9)
Allow filtering by initialized state in list_payments command (#18)
Maintenance and fixes
Add support for Python 3.11
Upgrade Django from 4.0 to 4.2
Fill missing documentation in README - get_card_payments_states command
Fill missing documentation in README - CSOBCardPaymentHandler settings (#14)
Fix project settings - add missing pytz dependency, drop requirements.txt (#8)
Avoid some deprecation warnings (#5)
Fix typos in exception messages and docstrings
Improve settings validation for CSOB key files and web links (CSOB API) (#21)
Improve tests - fix unclosed file (#6), silence logger output (#7)
Fix transaction date for card payments (#23)
2.4.0 (2023-01-11)
Upgrade to CSOB eAPI 1.9
Upgrade to Node.js 18
2.3.0 (2022-01-26)
Add help text to enforce currency field
Use account number instead of name in csob handler
Select account by currency in csob handler
2.2.1 (2021-10-12)
Skip to next processor after one fails
Use teller 0.4
Evaluate processor result inside try blok
2.2.0 (2021-08-13)
Upgrade django-money
Add type stubs
Skip bank fees callback
Fix requirements and tests for Django 3.0
Test with Django up to version 3.2
Fix default auto field warnings
Convert amount to type Money and handle it correctly
Convert currency to str for csob client
Update test settings and fix licence check
Do not run in parallel
Allow empty counter account
2.1.1 (2021-05-20)
Allow callback to cancel saving of a payment
2.1.0 (2021-04-29)
Raise exception on invalid datetime
Set default currency and allowed currencies
Round money amounts to two decimal places
Add README entry on currency formatting
Add select for update to admin
Fix thread synchronisation
Use teller to download statements
Allow to select subset of downloaders
Add downloader cli param to README
Add mixin for commands which save payments
Do not check downloaders when not required and raw is missing
Skip empty account with callback
Pin teller version
Add PaymentImportHistory
Wrap admin views in a transaction
Catch the OSError during import
Use datetime as download_payments parameters
Do not raise invalid account number for empty statements
Lock the DB only when request is POST
2.0.0 (2020-10-06)
Add support for Python 3.8
Drop support for Django 2.1
Add models for card payments
Add Card payment handler and REST API
Add get_card_payments_states mangagemend command
Command process_payments now process also card payments.
Add payment filtering by realized paymnets
Add processing newly paid payments after status update by REST API
Fix coverage of generators from payments processors
Add transaction to retrieve() in REST API
Allow only needed methods in BankPayment REST API
Update state of only initialized card payments
Return 503 while connection error during creating new card payment on gateway
Fix FileSettings for Python 3.5
Make PROCESSORS OrderedDict for tests to pass in Python 3.5
1.3.0 (2019-11-22)
Update setup.py and requirements
Return accidentally removed language switch
Use constraints in tox
Replace concurrent process_payments command info with warning
1.2.0 (2019-08-29)
Including accounts in payment processing
Add check for non-existing accounts
Generate migration for django-money 0.15
Update settings to allow multiple import callbacks
Add skip_credit_card_transaction_summary import callback
Move ignore_negative_payments callback to import_callbacks module
Add favicon
1.1.0 (2019-04-29)
Add separate permissions for manual assignment to individual payment processors
Expand payment processors API to allow sending processing error codes. * Admissible processing error codes are defined in django_pain.constants.PaymentProcessingError enum. * This change is backward compatible.
Add tax date to manual assignment of payment processor * If processor accepts a tax date, it has to have manual_tax_date set to True.
1.0.1 (2019-01-22)
Added PAIN_TRIM_VARSYM setting.
Fix czech translation of account invoice
0.3.0 (2018-07-24)
0.2.0 (2018-06-25)
Change payment processors API to allow bulk processing [#19]
0.1.1 (2018-06-12)
Add uuid field to BankPayment
0.1.0 (2018-06-11)
Add bank statement parsers
Add command import_payments
Add bank payment processors
Add command process_payments
Add simple list view for payments
0.0.2 (2018-04-26)
Add models BankAccount and BankPayment
Update setup.py for PyPI release
0.0.1 (2018-04-17)
Initial version