<commit_before>import logging
import datetime

from madmin_server import InternalServerError, add_handler
from madmin_db import Query, DatabaseError, commit, rollback, start_transaction
from madmin_user import hasPermission
from madmin_voorraad import add_voorraad, use_voorraad, ammount_voorraad
from madmin_products import query_product
from madmin_vereniging import query_vereniging
from madmin_budget import budget_query, budget_update
import policy.madmin_factuur as policy

class MalformedDataException(Exception):
	pass

class NonExistingProductException(Exception):
	def __init__(self, product_id, product_name):
		Exception.__init__(self, "Product does not exist")
		self.product_id = product_id
		self.product_name = product_name

class NonExistingVerenigingException(Exception):
	def __init__(self, vereniging):
		Exception.__init__(self, "Vereniging does not exist")
		self.vereniging = vereniging

class NonExistingBudgetException(Exception):
	def __init__(self, budget):
		Exception.__init__(self, "Budget does not exist")
		self.budget = budget

class IncompatibleBudgetException(Exception):
	def __init__(self, budget, vereniging):
		Exception.__init__(self, "Budget does not belong to vereniging")
		self.budget = budget;
		self.vereniging = vereniging

class NoVoorraadException(Exception):
	def __init__(self, product_id):
		Exception.__init__(self, "Not enough suplies")
		self.product_id = product_id

log = logging.getLogger(__name__)

def handle_factuur_create(params, json_data):
	log.debug('Start factuur_create')
	log.debug('Input data:%s', json_data)
	
	if not hasPermission(params,'factuur_create',None):
		return {'error': 'insufficient permissions'}
	
	facturen = []
	
	#Start transaction
	
	try:
		facturen.append(parse_factuur(json_data))
	except MalformedDataException:
		return {'error': 'incorrectly structured data'}
	
	try:
		for factuur in facturen:
			start_transaction()
			verify_factuur(factuur)
			fac_id = process_factuur(factuur)
			policy.process_factuur(factuur, fac_id)
			commit()
	except NonExistingProductException, e:
		rollback()
		return {'error': 'No such product {0}: {1}'.format(e.product_id, e.product_name), 'product_id': e.product_id, 'product_name': e.product_name}
	except NonExistingVerenigingException, e:
		
		return {'error': 'No such vereniging {0}'.format(e.vereniging), 'vereniging_id': e.vereniging}
	except NonExistingBudgetException, e:
		rollback()
		return {'error': 'No such budget {0}'.format(e.budget), 'budget_id': e.budget}
	except IncompatibleBudgetException, e:
		rollback()
		return {'error': 'Budget {0} is not compatible with vereniging {1}'.format(e.budget, e.vereniging),
		        'budget_id': e.budget, 'vereniging_id': e.vereniging}
	except NoVoorraadException, e:
		rollback()
		return {'error': 'Not enough supplies of {0}'.format(e.product_id), 'product_id': e.product_id}
	
	return {'succes': len(facturen)}

# ------------------------------------------------------------------------------
# Process factuur
#  Do all processing of the factuur, ie:
#   - changes in voorraad
#   - creation of permanent representation of factuur
#
#  This should not do validation, the only errors this should throw are
#  database errors
# ------------------------------------------------------------------------------

def process_factuur(factuur):
	# Gen. nones for possible non-existent values
	leverancier = None
	if 'leverancier' in factuur:
		leverancier = factuur['leverancier']
	vereniging = None
	saldo_basis = None
	if 'vereniging' in factuur:
		vereniging = factuur['vereniging']
		saldo_basis=query_vereniging(vereniging)[0]['basis_budget']
	saldo_speciaal = None
	if 'saldo_speciaal' in factuur:
		saldo_speciaal = factuur['saldo_speciaal']
	verantwoordelijke = None
	if 'verantwoordelijke' in factuur:
		verantwoordelijke = factuur['verantwoordelijke']
	
	# Generate next number for factuur
	try:
		q = Query("""SELECT MAX(fac_volgnummer)
		             FROM tblfactuur
		             WHERE fac_ver_id <=> %s AND fac_leverancier <=> %s""")
		q.run((vereniging, leverancier))
		rows = q.rows()
	except DatabaseError:
		raise InternalServerError
	if rows[0][0] is None:
		number = 1
	else:
		number = rows[0][0] + 1
	
	factuur['volgnummer'] = number
	
	# Create factuur entry
	try:
		q = Query("""INSERT INTO tblfactuur (fac_ver_id, 
		                                     fac_leverancier,
		                                     fac_type,
		                                     fac_volgnummer,
		                                     fac_factuurdatum,
		                                     fac_leverdatum,
		                                     fac_verantwoordelijke,
		                                     fac_saldo_speciaal,
		                                     fac_saldo_basis,
		                                     fac_bkjr_id) 
		             VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s,
		                    (SELECT bkjr_id FROM tblboekjaar
		                     WHERE bkjr_is_huidig = -1))""")
		q.run((vereniging,
		       leverancier,
		       factuur['type'],
		       number,<commit_msg>Fixed bug where numbering continued over boundaries of years.<commit_after>import logging
import datetime

from madmin_server import InternalServerError, add_handler
from madmin_db import Query, DatabaseError, commit, rollback, start_transaction
from madmin_user import hasPermission
from madmin_voorraad import add_voorraad, use_voorraad, ammount_voorraad
from madmin_products import query_product
from madmin_vereniging import query_vereniging
from madmin_budget import budget_query, budget_update
import policy.madmin_factuur as policy

class MalformedDataException(Exception):
	pass

class NonExistingProductException(Exception):
	def __init__(self, product_id, product_name):
		Exception.__init__(self, "Product does not exist")
		self.product_id = product_id
		self.product_name = product_name

class NonExistingVerenigingException(Exception):
	def __init__(self, vereniging):
		Exception.__init__(self, "Vereniging does not exist")
		self.vereniging = vereniging

class NonExistingBudgetException(Exception):
	def __init__(self, budget):
		Exception.__init__(self, "Budget does not exist")
		self.budget = budget

class IncompatibleBudgetException(Exception):
	def __init__(self, budget, vereniging):
		Exception.__init__(self, "Budget does not belong to vereniging")
		self.budget = budget;
		self.vereniging = vereniging

class NoVoorraadException(Exception):
	def __init__(self, product_id):
		Exception.__init__(self, "Not enough suplies")
		self.product_id = product_id

log = logging.getLogger(__name__)

def handle_factuur_create(params, json_data):
	log.debug('Start factuur_create')
	log.debug('Input data:%s', json_data)
	
	if not hasPermission(params,'factuur_create',None):
		return {'error': 'insufficient permissions'}
	
	facturen = []
	
	#Start transaction
	
	try:
		facturen.append(parse_factuur(json_data))
	except MalformedDataException:
		return {'error': 'incorrectly structured data'}
	
	try:
		for factuur in facturen:
			start_transaction()
			verify_factuur(factuur)
			fac_id = process_factuur(factuur)
			policy.process_factuur(factuur, fac_id)
			commit()
	except NonExistingProductException, e:
		rollback()
		return {'error': 'No such product {0}: {1}'.format(e.product_id, e.product_name), 'product_id': e.product_id, 'product_name': e.product_name}
	except NonExistingVerenigingException, e:
		
		return {'error': 'No such vereniging {0}'.format(e.vereniging), 'vereniging_id': e.vereniging}
	except NonExistingBudgetException, e:
		rollback()
		return {'error': 'No such budget {0}'.format(e.budget), 'budget_id': e.budget}
	except IncompatibleBudgetException, e:
		rollback()
		return {'error': 'Budget {0} is not compatible with vereniging {1}'.format(e.budget, e.vereniging),
		        'budget_id': e.budget, 'vereniging_id': e.vereniging}
	except NoVoorraadException, e:
		rollback()
		return {'error': 'Not enough supplies of {0}'.format(e.product_id), 'product_id': e.product_id}
	
	return {'succes': len(facturen)}

# ------------------------------------------------------------------------------
# Process factuur
#  Do all processing of the factuur, ie:
#   - changes in voorraad
#   - creation of permanent representation of factuur
#
#  This should not do validation, the only errors this should throw are
#  database errors
# ------------------------------------------------------------------------------

def process_factuur(factuur):
	# Gen. nones for possible non-existent values
	leverancier = None
	if 'leverancier' in factuur:
		leverancier = factuur['leverancier']
	vereniging = None
	saldo_basis = None
	if 'vereniging' in factuur:
		vereniging = factuur['vereniging']
		saldo_basis=query_vereniging(vereniging)[0]['basis_budget']
	saldo_speciaal = None
	if 'saldo_speciaal' in factuur:
		saldo_speciaal = factuur['saldo_speciaal']
	verantwoordelijke = None
	if 'verantwoordelijke' in factuur:
		verantwoordelijke = factuur['verantwoordelijke']
	
	# Generate next number for factuur
	try:
		q = Query("""SELECT MAX(fac_volgnummer)
		             FROM tblfactuur, tblboekjaar
		             WHERE fac_ver_id <=> %s AND fac_leverancier <=> %s 
		             AND fac_bkjr_id=bkjr_id AND bkjr_is_huidig = -1""")
		q.run((vereniging, leverancier))
		rows = q.rows()
	except DatabaseError:
		raise InternalServerError
	if rows[0][0] is None:
		number = 1
	else:
		number = rows[0][0] + 1
	
	factuur['volgnummer'] = number
	
	# Create factuur entry
	try:
		q = Query("""INSERT INTO tblfactuur (fac_ver_id, 
		                                     fac_leverancier,
		                                     fac_type,
		                                     fac_volgnummer,
		                                     fac_factuurdatum,
		                                     fac_leverdatum,
		                                     fac_verantwoordelijke,
		                                     fac_saldo_speciaal,
		                                     fac_saldo_basis,
		                                     fac_bkjr_id) 
		             VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s,
		                    (SELECT bkjr_id FROM tblboekjaar
		                     WHERE bkjr_is_huidig = -1))""")
		q.run((vereniging,
		       leverancier,
		       factuur['type'],
		       number,
{'fraction_non_alphanumeric': 0.12234403803240516, 'fraction_numerical': 0.003007664693897351, 'mean_word_length': 2.9922540666150272, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4705667', 'n_tokens_mistral': 3504, 'n_tokens_neox': 3301, 'n_words': 773}