lingo/lingo/invoicing/management/commands/generate_invoices.py

67 lines
2.7 KiB
Python

# lingo - payment and billing system
# Copyright (C) 2022 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero 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 distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import datetime
from django.core.management.base import BaseCommand, CommandError
from lingo.invoicing.models import Campaign
from lingo.invoicing.utils import generate_invoices
class Command(BaseCommand):
help = 'Generate invoicing for a period'
def add_arguments(self, parser):
parser.add_argument('date_start')
parser.add_argument('date_end')
parser.add_argument('--date-issue')
parser.add_argument('--draft', action='store_true')
def handle(self, *args, **options):
try:
date_start = datetime.datetime.fromisoformat(options['date_start']).date()
except ValueError:
raise CommandError('Bad value "%s" for date_start' % options['date_start'])
try:
date_end = datetime.datetime.fromisoformat(options['date_end']).date()
except ValueError:
raise CommandError('Bad value "%s" for date_end' % options['date_end'])
if options.get('date_issue'):
try:
date_issue = datetime.datetime.fromisoformat(options['date_issue']).date()
except ValueError:
raise CommandError('Bad value "%s" for date_issue' % options['date_issue'])
else:
date_issue = date_end
try:
campaign = Campaign.objects.get(date_start=date_start, date_end=date_end)
except Campaign.DoesNotExist:
campaigns = Campaign.objects.extra(
where=["(date_start, date_end) OVERLAPS (%s, %s)"], params=[date_start, date_end]
)
if campaigns.exists():
raise CommandError('Overlapping campaigns already exist')
campaign = Campaign.objects.create(
date_start=date_start, date_end=date_end, date_issue=date_issue
)
generate_invoices(campaign=campaign, draft=options['draft'])
self.stdout.write(
self.style.SUCCESS('Invoicing generation OK (start: %s, end: %s)' % (date_start, date_end))
)