def testContractCreation(self): student, teacher = self.createStudentTeacher() ''' Test creation of contract between student and teacher ''' contract = Contract(teacher=teacher, student=student) contract.save() self.assertIsInstance(contract, Contract)
def testSearch(self): student, teacher = self.createStudentTeacher() contract = Contract(teacher=teacher, student=student) contract.save() foundContract = Contract.objects.filter(student=student, teacher=teacher) assert (contract == foundContract[0])
def __init__(self): Contract.objects.all().delete() for contract in CONTRACTS: new_contract = Contract( contract_number=contract['contract_number'], sign_date=contract['sign_date'], contract_type=contract['contract_type'], tax=contract['tax'], cancel_date=contract['cancel_date'], broadcast=contract['broadcast'], unit_price=contract['unit_price'], ) new_contract.save()
def contract(request): '''Creates a view to save the contract details.''' contracts = Contract.objects.all() if request.method == 'POST': form = ContractForm(request.POST) if form.is_valid(): from_date = form.cleaned_data['from_date'] to_date = form.cleaned_data['to_date'] list_size = form.cleaned_data['list_size'] total_email = form.cleaned_data['total_email'] try: contract = Contract() contract.from_date = from_date contract.to_date = to_date contract.list_size = list_size contract.total_email = total_email contract.save() except: pass return HttpResponseRedirect(reverse('index')) else: form = ContractForm() context = {'contracts': contracts, 'form': form} return render(request, 'contracts/contract.html', context)
def test_create_contract_same_tenant_within_date_range(self): """ Should raise ValidationError when trying to create a contract for a tenant that is already in another contract and which data range includes the given range """ # checks db does not contain contracts self.assertEqual(Contract.objects.count(), 0) # creates a contracts contract_one = ContractFactory() contract_two = ContractFactory() self.assertEqual(Contract.objects.count(), 2) invalid_contract_data = { 'start_date': '2017-10-27', 'end_date': '2018-10-27', 'property': contract_two.property, 'tenant': contract_one.tenant, 'rent': 1000.00 } expected = ('There is already another contract for this property or ' 'for this tenant and the given dates.') with self.assertRaises(ValidationError) as raised: Contract(**invalid_contract_data).save() self.assertIn(expected, raised.exception.message_dict['__all__'])
def get_queryset(self): return Contract.objects.filter( education_level=Contract.get_education_code( self.EDU_LEVEL, raise_exception=True), min_years_experience__lt=self.EXPERIENCE_CAP, current_price__gt=self.MIN_PRICE, )
def to_internal_value(self, data): edu_code = Contract.get_education_code(data) if not edu_code: raise serializers.ValidationError( f'Invalid education level: {data}') return edu_code
def contract(request): """Creates a view to save the contract details.""" contracts = Contract.objects.all() if request.method == "POST": form = ContractForm(request.POST) if form.is_valid(): from_date = form.cleaned_data["from_date"] to_date = form.cleaned_data["to_date"] list_size = form.cleaned_data["list_size"] total_email = form.cleaned_data["total_email"] try: contract = Contract() contract.from_date = from_date contract.to_date = to_date contract.list_size = list_size contract.total_email = total_email contract.save() except: pass return HttpResponseRedirect(reverse("index")) else: form = ContractForm() context = {"contracts": contracts, "form": form} return render(request, "contracts/contract.html", context)
def to_internal_value(self, data): edu_code = Contract.get_education_code(data) if not edu_code: raise serializers.ValidationError( f'Invalid education level: {data}' ) return edu_code
def set_contract_address(multisig_address, contract_address, sender_address, tx_info): op_return_hex, tx_hash = _get_op_return_hex_and_hash(tx_info) sender_evm_address = wallet_address_to_evm(sender_address) c = Contract.objects.filter( multisig_address__address=multisig_address, sender_evm_address=sender_evm_address, hash_op_return=Contract.make_hash_op_return(op_return_hex), is_deployed=False )[0] c.contract_address = contract_address c.tx_hash_init = tx_hash c.is_deployed = True c.save()
def test_create_contract_missing_property(self): """ Should raise ObjectDoesNotExist when trying to create contract with missing property """ self.assertEqual(Contract.objects.count(), 0) contract_data = factory.build(dict, FACTORY_CLASS=ContractFactory) contract_data['property'].landlord.save() contract_data['tenant'].save() del(contract_data['property']) with self.assertRaises(ObjectDoesNotExist) as raised: Contract(**contract_data).save() expected = 'Contract has no property.' self.assertEqual(Contract.objects.count(), 0) self.assertEqual(raised.exception.message, expected)
def test_create_contract_missing_rent(self): """ Should raise ValidationError when trying to create contract with missing rent """ self.assertEqual(Contract.objects.count(), 0) contract_data = factory.build(dict, FACTORY_CLASS=ContractFactory) contract_data['property'].landlord.save() contract_data['property'].save() contract_data['tenant'].save() del(contract_data['rent']) with self.assertRaises(ValidationError) as raised: Contract(**contract_data).save() expected = {'rent': [u'This field cannot be null.']} self.assertEqual(Contract.objects.count(), 0) self.assertEqual(raised.exception.message_dict, expected)
def test_create_contract_same_tenant_not_matching_dates(self): """ Should successfully create a contract for a tenant that is already in another contract and which data range does not include given dates """ # checks db does not contain contracts self.assertEqual(Contract.objects.count(), 0) # creates contracts contract_one = ContractFactory() contract_two = ContractFactory() self.assertEqual(Contract.objects.count(), 2) contract_data = { 'start_date': '2018-11-01', 'end_date': '2019-11-01', 'property': contract_two.property, 'tenant': contract_one.tenant, 'rent': 1000.00 } Contract(**contract_data) self.assertEqual(Contract.objects.count(), 2)
def test_create_contract_with_given_invalid_id(self): """ Should raise ValidationError when creating Contract and given id is invalid """ self.assertEqual(Contract.objects.count(), 0) contract_data = factory.build(dict, FACTORY_CLASS=ContractFactory) contract_data['id'] = 'aaaabbbbccccddd#' contract_data['property'].landlord.save() contract_data['property'].save() contract_data['tenant'].save() expected = { 'id': [('ID must be a string containing 16 alphanumeric ' 'lowercase characters')]} with self.assertRaises(ValidationError) as raised: Contract(**contract_data).save() self.assertEqual(raised.exception.message_dict, expected) self.assertEqual(Contract.objects.count(), 0)
def test_create_contract_invalid_dates(self): """ Should raise ValidationError when trying to create a contract for a with ending date smaller than starting date """ # checks db does not contain contracts contract_one = ContractFactory() contract_two = ContractFactory() self.assertEqual(Contract.objects.count(), 2) invalid_contract_data = { 'start_date': '2017-10-27', 'end_date': '2017-01-27', 'property': contract_one.property, 'tenant': contract_two.tenant, 'rent': 1000.00 } expected = (u'Invalid dates for contract. Ending date should come ' 'after starting date.') with self.assertRaises(ValidationError) as raised: Contract(**invalid_contract_data).save() self.assertIn(expected, raised.exception.message_dict['__all__'])
def handle(self, *args, **options): data_file = csv.reader(open(os.path.join(settings.BASE_DIR, 'contracts/docs/hourly_prices.csv'), 'r')) #skip header row next(data_file) for line in data_file: try: if line[0]: #create contract record, unique to vendor, labor cat idv_piid = line[0] vendor_name = line[3] labor_category = line[4].strip().replace('\n', ' ') try: contract = Contract.objects.get(idv_piid=idv_piid, labor_category=labor_category, vendor_name=vendor_name) except Contract.DoesNotExist: contract = Contract() contract.idv_piid = idv_piid contract.labor_category = labor_category contract.vendor_name = vendor_name contract.education_level = contract.get_education_code(line[5]) if line[1] != '': contract.contract_start = datetime.strptime(line[1], '%m/%d/%Y').date() if line[2] != '': contract.contract_end = datetime.strptime(line[2], '%m/%d/%Y').date() if line[6].strip() != '': contract.min_years_experience = line[6] else: contract.min_years_experience = 0 if line[7] and line[7] != '': contract.hourly_rate_year1 = contract.normalize_rate(line[7]) else: #there's no pricing info continue for count, rate in enumerate(line[8:12]): if rate and rate.strip() != '': setattr(contract, 'hourly_rate_year' + str(count+2), contract.normalize_rate(rate)) contract.contractor_site = line[12] contract.save() except Exception as e: print(e) print(line) break
def make_contract(cls, line, upload_source=None): if line[0]: # create contract record, unique to vendor, labor cat idv_piid = line[11] vendor_name = line[10] labor_category = line[0].strip().replace('\n', ' ') contract = Contract() contract.idv_piid = idv_piid contract.labor_category = labor_category contract.vendor_name = vendor_name contract.education_level = contract.get_education_code( line[6] ) contract.schedule = line[12] contract.business_size = line[8] current_contract_year = int(float(line[14])) contract.contract_year = current_contract_year contract.sin = line[13] if line[15] != '': contract.contract_start = datetime.strptime( line[15], '%m/%d/%Y').date() if line[16] != '': contract.contract_end = datetime.strptime( line[16], '%m/%d/%Y').date() if line[7].strip() != '': contract.min_years_experience = int(float(line[7])) else: contract.min_years_experience = 0 if line[1] and line[1] != '': contract.hourly_rate_year1 = contract.normalize_rate( line[1] ) else: # there's no pricing info raise ValueError('missing price') for count, rate in enumerate(line[2:6]): if rate and rate.strip() != '': setattr(contract, 'hourly_rate_year' + str(count + 2), contract.normalize_rate(rate)) if line[14] and line[14] != '': price_fields = { 'current_price': getattr(contract, 'hourly_rate_year' + str(current_contract_year), 0) } # we have up to five years of rate data if current_contract_year < 5: price_fields['next_year_price'] = getattr( contract, 'hourly_rate_year' + str(current_contract_year + 1), 0 ) if current_contract_year < 4: price_fields['second_year_price'] = getattr( contract, 'hourly_rate_year' + str(current_contract_year + 2), 0 ) # don't create display prices for records where the # rate is under the federal minimum contract rate for field in price_fields: price = price_fields.get(field) if price and price >= FEDERAL_MIN_CONTRACT_RATE: setattr(contract, field, price) contract.contractor_site = line[9] if upload_source: contract.upload_source = upload_source return contract
def handle(self, *args, **options): log = logging.getLogger(__name__) log.info("Begin load_data task") log.info("Deleting existing contract records") Contract.objects.all().delete() data_file = csv.reader(open(os.path.join(settings.BASE_DIR, "contracts/docs/hourly_prices.csv"), "r")) # skip header row next(data_file) # used for removing expired contracts today = date.today() contracts = [] log.info("Processing new datafile") for line in data_file: # replace annoying msft carraige return for num in range(0, len(line)): # also replace version with capital D line[num] = line[num].replace("_x000d_", "").replace("_x000D_", "") try: if line[0]: # create contract record, unique to vendor, labor cat idv_piid = line[11] vendor_name = line[10] labor_category = line[0].strip().replace("\n", " ") contract = Contract() contract.idv_piid = idv_piid contract.labor_category = labor_category contract.vendor_name = vendor_name contract.education_level = contract.get_education_code(line[6]) contract.schedule = line[12] contract.business_size = line[8] contract.contract_year = line[14] contract.sin = line[13] if line[15] != "": contract.contract_start = datetime.strptime(line[15], "%m/%d/%Y").date() if line[16] != "": contract.contract_end = datetime.strptime(line[16], "%m/%d/%Y").date() if line[7].strip() != "": contract.min_years_experience = line[7] else: contract.min_years_experience = 0 if line[1] and line[1] != "": contract.hourly_rate_year1 = contract.normalize_rate(line[1]) else: # there's no pricing info continue for count, rate in enumerate(line[2:6]): if rate and rate.strip() != "": setattr(contract, "hourly_rate_year" + str(count + 2), contract.normalize_rate(rate)) # don't create current price for records where the rate # is under the federal minimum contract rate current_price = getattr(contract, "hourly_rate_year" + str(line[14])) if current_price and current_price >= FEDERAL_MIN_CONTRACT_RATE: contract.current_price = current_price contract.contractor_site = line[9] contracts.append(contract) except Exception as e: log.exception(e) log.warning(line) break log.info("Inserting records") Contract.objects.bulk_create(contracts) log.info("Updating search index") call_command("update_search_field", Contract._meta.app_label, Contract._meta.model_name) log.info("End load_data task")
def make_contract(cls, line, upload_source=None): if line[0]: # create contract record, unique to vendor, labor cat idv_piid = line[11] vendor_name = line[10] labor_category = line[0].strip().replace('\n', ' ') contract = Contract() contract.idv_piid = idv_piid contract.labor_category = labor_category contract.vendor_name = vendor_name contract.education_level = contract.get_education_code( line[6] ) contract.schedule = line[12] contract.business_size = line[8] current_contract_year = int(float(line[14])) contract.contract_year = current_contract_year contract.sin = line[13] if line[15] != '': contract.contract_start = datetime.strptime( line[15], '%m/%d/%Y').date() if line[16] != '': contract.contract_end = datetime.strptime( line[16], '%m/%d/%Y').date() if line[7].strip() != '': contract.min_years_experience = int(float(line[7])) else: contract.min_years_experience = 0 if line[1] and line[1] != '': contract.hourly_rate_year1 = contract.normalize_rate( line[1] ) else: # there's no pricing info raise ValueError('missing price') for count, rate in enumerate(line[2:6]): if rate and rate.strip() != '': setattr(contract, 'hourly_rate_year' + str(count + 2), contract.normalize_rate(rate)) if line[14] and line[14] != '': price_fields = { 'current_price': getattr(contract, 'hourly_rate_year' + str(current_contract_year), 0) } # we have up to five years of rate data if current_contract_year < 5: price_fields['next_year_price'] = getattr( contract, 'hourly_rate_year' + str(current_contract_year + 1), 0 ) if current_contract_year < 4: price_fields['second_year_price'] = getattr( contract, 'hourly_rate_year' + str(current_contract_year + 2), 0 ) # don't create display prices for records where the # rate is under the federal minimum contract rate for field in price_fields: price = price_fields.get(field) if price and price >= FEDERAL_MIN_CONTRACT_RATE: setattr(contract, field, price) contract.contractor_site = line[9] if upload_source: contract.upload_source = upload_source return contract else: raise ValueError('missing labor category')
def __row_to_contract(self, row): if not (row['Labor Category'] and row['Contract Year'] and row['Year 1/base']): return None contract = Contract() contract.idv_piid = row['CONTRACT .'] contract.labor_category = row['Labor Category'].strip().replace('\n', ' ') contract.vendor_name = row['COMPANY NAME'] contract.education_level = contract.get_education_code(row['Education']) contract.schedule = row['Schedule'] contract.business_size = row['Bus Size'] contract.contract_year = row['Contract Year'] contract.sin = row['SIN NUMBER'] contract.hourly_rate_year1 = contract.normalize_rate(str(row['Year 1/base'])) contract.contractor_site = row['Location'] if row['Begin Date']: contract.contract_start = datetime.strptime(row['Begin Date'], '%m/%d/%Y').date() if row['End Date']: contract.contract_end = datetime.strptime(row['End Date'], '%m/%d/%Y').date() contract.min_years_experience = int(row['MinExpAct']) if row['MinExpAct'].isdigit() else 0 for count, rate in enumerate(row[2:6]): if rate: setattr(contract, 'hourly_rate_year{}'.format(count + 2), contract.normalize_rate(str(rate))) self.__generate_contract_rate_years(row, contract) return contract
def home(request): template = "orderofpi/home.html" context = {'CommitedDonationTotal': Contract.GetCommitedDonationTotal()} #import sys #print('CommitedDonationSum = ' + str(Contract.GetCommitedDonationTotal()),sys.stderr) return render(request, template, context)
def testContractVerification(self): student, teacher = self.createStudentTeacher() contract = Contract(teacher=teacher, student=student) contract.save() # Case: Neither accepted # Expected: Acceptance Error Raised with self.assertRaises(AcceptenceError) as context: contract.start_contract() self.assertTrue('This is broken' in str(context.AcceptanceError)) assert (contract.status == contract.PENDING) # Case: Student not accepted # Expected: Acceptance Error Raised contract.teacher_accepted = True contract.student_accepted = False contract.save() with self.assertRaises(AcceptenceError) as context: contract.start_contract() self.assertTrue('This is broken' in str(context.AcceptanceError)) assert (contract.status == contract.PENDING) # Case: Teacher not accepted # Expected: Acceptance Error Raised contract.teacher_accepted = False contract.student_accepted = True contract.save() with self.assertRaises(AcceptenceError) as context: contract.start_contract() self.assertTrue('This is broken' in str(context.AcceptanceError)) assert (contract.status == contract.PENDING) # Case: Both accepted contract.teacher_accepted = True contract.student_accepted = True contract.start_contract() contract.save() assert (contract.student_accepted == True) assert (contract.teacher_accepted == True) assert (contract.status == contract.ACTIVE)
def approve(self, user): ''' Approve this SubmittedPriceList. This causes its rows of pricing data to be converted to Contract models, which are then accessible via CALC's API and in the Data Explorer. ''' self._change_status(self.STATUS_APPROVED, user) for row in self.rows.filter(is_muted=False): if row.contract_model is not None: raise AssertionError() contract = Contract( idv_piid=self.contract_number, contract_start=self.contract_start, contract_end=self.contract_end, vendor_name=self.vendor_name, labor_category=row.labor_category, education_level=row.education_level, min_years_experience=row.min_years_experience, contractor_site=self.contractor_site, schedule=self.get_schedule_title(), business_size=self.get_business_size_string(), sin=row.sin, ) contract.adjust_contract_year() # Assuming the rate in the price list is the 'base rate' # Escalate the hourly_rate_yearX fields contract.escalate_hourly_rate_fields( row.base_year_rate, self.escalation_rate) # Update current/next/second year price fields contract.update_price_fields() contract.full_clean(exclude=['piid']) contract.save() row.contract_model = contract row.save() self.save()
def __row_to_contract(self, row): if not (row['Labor Category'] and row['Contract Year'] and row['Year 1/base']): return None contract = Contract() contract.idv_piid = row['CONTRACT .'] contract.labor_category = row['Labor Category'].strip().replace( '\n', ' ') contract.vendor_name = row['COMPANY NAME'] contract.education_level = contract.get_education_code( row['Education']) contract.schedule = row['Schedule'] contract.business_size = row['Bus Size'] contract.contract_year = row['Contract Year'] contract.sin = row['SIN NUMBER'] contract.hourly_rate_year1 = contract.normalize_rate( str(row['Year 1/base'])) contract.contractor_site = row['Location'] if row['Begin Date']: contract.contract_start = datetime.strptime( row['Begin Date'], '%m/%d/%Y').date() if row['End Date']: contract.contract_end = datetime.strptime(row['End Date'], '%m/%d/%Y').date() contract.min_years_experience = int( row['MinExpAct']) if row['MinExpAct'].isdigit() else 0 for count, rate in enumerate(row[2:6]): if rate: setattr(contract, 'hourly_rate_year{}'.format(count + 2), contract.normalize_rate(str(rate))) self.__generate_contract_rate_years(row, contract) return contract
def handle(self, *args, **options): log = logging.getLogger(__name__) log.info("Begin load_data task") log.info("Deleting existing contract records") Contract.objects.all().delete() data_file = csv.reader(open(os.path.join(settings.BASE_DIR, 'contracts/docs/hourly_prices.csv'), 'r')) #skip header row next(data_file) #used for removing expired contracts today = date.today() contracts = [] log.info("Processing new datafile") for line in data_file: #replace annoying msft carraige return for num in range(0, len(line)): #also replace version with capital D line[num] = line[num].replace("_x000d_", "").replace("_x000D_", "") try: if line[0]: #create contract record, unique to vendor, labor cat idv_piid = line[11] vendor_name = line[10] labor_category = line[0].strip().replace('\n', ' ') contract = Contract() contract.idv_piid = idv_piid contract.labor_category = labor_category contract.vendor_name = vendor_name contract.education_level = contract.get_education_code(line[6]) contract.schedule = line[12] contract.business_size = line[8] contract.sin = line[13] if line[14] != '': contract.contract_start = datetime.strptime(line[14], '%m/%d/%Y').date() if line[15] != '': contract.contract_end = datetime.strptime(line[15], '%m/%d/%Y').date() if line[7].strip() != '': contract.min_years_experience = line[7] else: contract.min_years_experience = 0 if line[1] and line[1] != '': contract.hourly_rate_year1 = contract.normalize_rate(line[1]) else: #there's no pricing info continue for count, rate in enumerate(line[2:6]): if rate and rate.strip() != '': setattr(contract, 'hourly_rate_year' + str(count+2), contract.normalize_rate(rate)) if contract.contract_end > today and contract.contract_start < today: #it's a current contract, need to find which year we're in start_day = contract.contract_start for plus_year in range(0,5): if date(year=start_day.year + plus_year, month=start_day.month, day=start_day.day) < today: contract.current_price = getattr(contract, 'hourly_rate_year' + str(plus_year + 1)) contract.contractor_site = line[9] contracts.append(contract) except Exception as e: log.exception(e) log.warning(line) break log.info("Inserting records") Contract.objects.bulk_create(contracts) log.info("Updating search index") call_command('update_search_field', Contract._meta.app_label, Contract._meta.model_name) log.info("End load_data task")
def handle(self, *args, **options): log = logging.getLogger(__name__) log.info("Begin load_data task") log.info("Deleting existing contract records") Contract.objects.all().delete() data_file = csv.reader( open( os.path.join(settings.BASE_DIR, 'contracts/docs/hourly_prices.csv'), 'r')) #skip header row next(data_file) #used for removing expired contracts today = date.today() contracts = [] log.info("Processing new datafile") for line in data_file: #replace annoying msft carraige return for num in range(0, len(line)): #also replace version with capital D line[num] = line[num].replace("_x000d_", "").replace("_x000D_", "") try: if line[0]: #create contract record, unique to vendor, labor cat idv_piid = line[11] vendor_name = line[10] labor_category = line[0].strip().replace('\n', ' ') contract = Contract() contract.idv_piid = idv_piid contract.labor_category = labor_category contract.vendor_name = vendor_name contract.education_level = contract.get_education_code( line[6]) contract.schedule = line[12] contract.business_size = line[8] contract.contract_year = line[14] contract.sin = line[13] if line[15] != '': contract.contract_start = datetime.strptime( line[15], '%m/%d/%Y').date() if line[16] != '': contract.contract_end = datetime.strptime( line[16], '%m/%d/%Y').date() if line[7].strip() != '': contract.min_years_experience = line[7] else: contract.min_years_experience = 0 if line[1] and line[1] != '': contract.hourly_rate_year1 = contract.normalize_rate( line[1]) else: #there's no pricing info continue for count, rate in enumerate(line[2:6]): if rate and rate.strip() != '': setattr(contract, 'hourly_rate_year' + str(count + 2), contract.normalize_rate(rate)) if line[14] and line[14] != '': price_fields = { 'current_price': getattr(contract, 'hourly_rate_year' + str(line[14]), 0) } current_year = int(line[14]) # we have up to five years of rate data if current_year < 5: price_fields['next_year_price'] = getattr( contract, 'hourly_rate_year' + str(current_year + 1), 0) if current_year < 4: price_fields['second_year_price'] = getattr( contract, 'hourly_rate_year' + str(current_year + 2), 0) # don't create display prices for records where the rate # is under the federal minimum contract rate for field in price_fields: price = price_fields.get(field) if price and price >= FEDERAL_MIN_CONTRACT_RATE: setattr(contract, field, price) contract.contractor_site = line[9] contracts.append(contract) except Exception as e: log.exception(e) log.warning(line) break log.info("Inserting records") Contract.objects.bulk_create(contracts) log.info("Updating search index") call_command('update_search_field', Contract._meta.app_label, Contract._meta.model_name) log.info("End load_data task")
def create(self, validated_data): return Contract.objects.bulk_create( [Contract(**item) for item in validated_data])