Skip to content

Commit

Permalink
Merge pull request #173 from shibaken/working
Browse files Browse the repository at this point in the history
Working to main
  • Loading branch information
shibaken authored Feb 29, 2024
2 parents dee61b8 + d64c290 commit af87e1a
Show file tree
Hide file tree
Showing 9 changed files with 128 additions and 44 deletions.
23 changes: 20 additions & 3 deletions mooringlicensing/components/approvals/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1403,6 +1403,23 @@ class WaitingListAllocationViewSet(viewsets.ModelViewSet):
queryset = WaitingListAllocation.objects.all().order_by('id')
serializer_class = WaitingListAllocationSerializer

def get_queryset(self):
# return super().get_queryset()
user = self.request.user
if is_internal(self.request):
qs = WaitingListAllocation.objects.all()
return qs
elif is_customer(self.request):
# queryset = WaitingListAllocation.objects.filter(Q(proxy_applicant_id=user.id) | Q(submitter=user.id))
user_orgs = Organisation.objects.filter(delegates__contains=[self.request.user.id])
queryset = WaitingListAllocation.objects.filter(Q(org_applicant__in=user_orgs) | Q(submitter=self.request.user.id))
return queryset
# user_orgs = Organisation.objects.filter(delegates__contains=[self.request.user.id])
# queryset = Approval.objects.filter(Q(org_applicant__in=user_orgs) | Q(submitter = self.request.user.id))
logger.warn("User is neither customer nor internal user: {} <{}>".format(user.get_full_name(), user.email))
return WaitingListAllocation.objects.none()


@detail_route(methods=['POST',], detail=True)
@basic_exception_handler
def create_mooring_licence_application(self, request, *args, **kwargs):
Expand Down Expand Up @@ -1447,7 +1464,7 @@ def create_mooring_licence_application(self, request, *args, **kwargs):
return Response({"proposal_created": new_proposal.lodgement_number})


class MooringLicenceViewSet(viewsets.ModelViewSet):
queryset = MooringLicence.objects.all().order_by('id')
serializer_class = ApprovalSerializer
# class MooringLicenceViewSet(viewsets.ModelViewSet):
# queryset = MooringLicence.objects.all().order_by('id')
# serializer_class = ApprovalSerializer

36 changes: 35 additions & 1 deletion mooringlicensing/components/approvals/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,7 +648,41 @@ def save(self, *args, **kwargs):
kwargs['no_revision'] = True
super(Approval, self).save(*args, **kwargs)
self.child_obj.refresh_from_db()
if type(self.child_obj) == MooringLicence and self.status in [Approval.APPROVAL_STATUS_EXPIRED, Approval.APPROVAL_STATUS_CANCELLED, Approval.APPROVAL_STATUS_SURRENDERED,]:

if type(self.child_obj) == MooringLicence and self.status in [
Approval.APPROVAL_STATUS_EXPIRED,
Approval.APPROVAL_STATUS_CANCELLED,
Approval.APPROVAL_STATUS_SURRENDERED,
]:
if type(self.child_obj) == MooringLicence and self.status in [
Approval.APPROVAL_STATUS_CANCELLED,
Approval.APPROVAL_STATUS_SURRENDERED,
]:
current_stickers = self.stickers.filter(
status__in=[
# Sticker.STICKER_STATUS_CURRENT,
Sticker.STICKER_STATUS_AWAITING_PRINTING,
Sticker.STICKER_STATUS_NOT_READY_YET,
Sticker.STICKER_STATUS_READY,
]
)
# When sticker is not printed yet, its status gets 'Cancelled'.
for sticker in current_stickers:
sticker.status = Sticker.STICKER_STATUS_CANCELLED
sticker.save()
logger.info(f'Status: [{Sticker.STICKER_STATUS_CANCELLED}] has been set to the sticker: [{sticker}] due to the status: [{self.status}] of the approval: [{self}].')

current_stickers = self.stickers.filter(
status__in=[
Sticker.STICKER_STATUS_CURRENT,
]
)
# When sticker is current status, it should be returned.
for sticker in current_stickers:
sticker.status = Sticker.STICKER_STATUS_TO_BE_RETURNED
sticker.save()
logger.info(f'Status: [{Sticker.STICKER_STATUS_TO_BE_RETURNED}] has been set to the sticker: [{sticker}] due to the status: [{self.status}] of the approval: [{self}].')

self.child_obj.update_auth_user_permits()

def __str__(self):
Expand Down
14 changes: 11 additions & 3 deletions mooringlicensing/components/proposals/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,19 +299,27 @@ def get(self, request, format=None):
Q(mooring_bay__id=mooring_bay_id) &
Q(vessel_size_limit__gte=vessel_details.vessel_applicable_length) &
Q(vessel_draft_limit__gte=vessel_details.vessel_draft) &
~Q(id__in=aup_mooring_ids)
~Q(id__in=aup_mooring_ids) &
Q(active=True) &
Q(mooring_licence__status__in=MooringLicence.STATUSES_AS_CURRENT) # Make sure this mooring is licensed because an unlicensed mooring would never be allocated to an AU permit.
)
data = Mooring.authorised_user_moorings.filter(mooring_filter, active=True).values('id', 'name', 'mooring_licence')[:num_of_moorings_to_return]
data = Mooring.authorised_user_moorings.filter(mooring_filter).values('id', 'name', 'mooring_licence')[:num_of_moorings_to_return]
else:
data = []
else:
data = Mooring.private_moorings.filter(name__icontains=search_term, active=True).values('id', 'name', 'mooring_licence')[:num_of_moorings_to_return]
mooring_filter = Q(
Q(name__icontains=search_term) &
Q(active=True) &
Q(mooring_licence__status__in=MooringLicence.STATUSES_AS_CURRENT) # Make sure this mooring is licensed because an unlicensed mooring would never be allocated to an AU permit.
)
data = Mooring.private_moorings.filter(mooring_filter).values('id', 'name', 'mooring_licence')[:num_of_moorings_to_return]
# data_transform = [{'id': mooring['id'], 'text': mooring['name']} for mooring in data]
data_transform = []
for mooring in data:
if 'mooring_licence' in mooring and mooring['mooring_licence']:
data_transform.append({'id': mooring['id'], 'text': mooring['name'] + ' (licensed)'})
else:
# Should not reach here. An unlicensed mooring would never be allocated to an AU permit.
data_transform.append({'id': mooring['id'], 'text': mooring['name'] + ' (unlicensed)'})
return Response({"results": data_transform})
return Response()
Expand Down
73 changes: 45 additions & 28 deletions mooringlicensing/components/proposals/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2583,55 +2583,72 @@ def validate_against_existing_proposals_and_approvals(self):
from mooringlicensing.components.approvals.models import Approval, ApprovalHistory, WaitingListAllocation, MooringLicence
today = datetime.datetime.now(pytz.timezone(TIME_ZONE)).date()

# Get blocking proposals
# Get blocking proposals
# Checking if there are any applications still in process, but it might not be necessary to check for that because the blocking approvals are checked below.
proposals = Proposal.objects.filter(
vessel_details__vessel=self.vessel_ownership.vessel,
vessel_ownership__end_date__gt=today, # Vessel has not been sold yet
Q(vessel_details__vessel=self.vessel_ownership.vessel) &
(Q(vessel_ownership__end_date__gt=today) | Q(vessel_ownership__end_date__isnull=True)) # Vessel has not been sold yet
).exclude(id=self.id)
child_proposals = [proposal.child_obj for proposal in proposals]
proposals_wla = []
proposals_mla = []
logger.debug(f'child_proposals: [{child_proposals}]')
# proposals_wla = []
# proposals_mla = []
blocking_proposals = [] #
for proposal in child_proposals:
if proposal.processing_status not in [
Proposal.PROCESSING_STATUS_APPROVED,
# Proposal.PROCESSING_STATUS_APPROVED,
Proposal.PROCESSING_STATUS_DECLINED,
Proposal.PROCESSING_STATUS_EXPIRED,
Proposal.PROCESSING_STATUS_DISCARDED,
]:
if type(proposal) == WaitingListApplication:
proposals_wla.append(proposal)
if type(proposal) == MooringLicenceApplication:
proposals_mla.append(proposal)
] and proposal.succeeding_proposals.count() == 0: # There are no succeeding proposals, which means this proposal is the lastest proposal.
# if type(proposal) == WaitingListApplication:
# proposals_wla.append(proposal)
# if type(proposal) == MooringLicenceApplication:
# proposals_mla.append(proposal)
blocking_proposals.append(proposal)

# Get blocking approvals
approval_histories = ApprovalHistory.objects.filter(
end_date=None,
vessel_ownership__vessel=self.vessel_ownership.vessel,
vessel_ownership__end_date__gt=today, # Vessel has not been sold yet
Q(end_date=None) &
Q(vessel_ownership__vessel=self.vessel_ownership.vessel) &
(Q(vessel_ownership__end_date__gt=today) | Q(vessel_ownership__end_date__isnull=True)) # Vessel has not been sold yet
).exclude(approval_id=self.approval_id)
approvals = [ah.approval for ah in approval_histories]
approvals = list(dict.fromkeys(approvals)) # remove duplicates
approvals_wla = []
approvals_ml = []
approvals = list(dict.fromkeys(approvals)) # remove duplicateS
# approvals_wla = []
# approvals_ml = []
blocking_approvals = []
for approval in approvals:
if approval.status in Approval.APPROVED_STATUSES:
if type(approval.child_obj) == WaitingListAllocation:
approvals_wla.append(approval)
if type(approval.child_obj) == MooringLicence:
approvals_ml.append(approval)

if (proposals_wla or approvals_wla or proposals_mla or approvals_ml):
raise serializers.ValidationError("The vessel in the application is already listed in " +
", ".join(['{} {} '.format(proposal.description, proposal.lodgement_number) for proposal in proposals_wla]) +
", ".join(['{} {} '.format(approval.description, approval.lodgement_number) for approval in approvals_wla])
)
# if type(approval.child_obj) == WaitingListAllocation:
# approvals_wla.append(approval)
# if type(approval.child_obj) == MooringLicence:
# approvals_ml.append(approval)
blocking_approvals.append(approval)

# if (proposals_wla or approvals_wla or proposals_mla or approvals_ml):
if (blocking_proposals or blocking_approvals):
bp = ", ".join(['{} {} '.format(proposal.description, proposal.lodgement_number) for proposal in blocking_proposals])
ba = ", ".join(['{} {} '.format(approval.description, approval.lodgement_number) for approval in blocking_approvals])
msg = f'The vessel: {self.vessel_ownership.vessel} in the application is already listed in {bp}{ba}'
# raise serializers.ValidationError("The vessel in the application is already listed in " +
# ", ".join(['{} {} '.format(proposal.description, proposal.lodgement_number) for proposal in proposals_wla]) +
# ", ".join(['{} {} '.format(proposal.description, proposal.lodgement_number) for proposal in blocking_proposals]) +
# ", ".join(['{} {} '.format(approval.description, approval.lodgement_number) for approval in approvals_wla])
# ", ".join(['{} {} '.format(approval.description, approval.lodgement_number) for approval in blocking_approvals])
# )
logger.error(msg)
raise serializers.ValidationError(msg)
# Person can have only one WLA, Waiting Liast application, Mooring Licence and Mooring Licence application
elif (
WaitingListApplication.get_intermediate_proposals(self.submitter).exclude(id=self.id) or
WaitingListAllocation.get_intermediate_approvals(self.submitter).exclude(approval=self.approval) or
MooringLicenceApplication.get_intermediate_proposals(self.submitter) or
MooringLicence.get_valid_approvals(self.submitter)
):
raise serializers.ValidationError("Person can have only one WLA, Waiting List application, Mooring Site Licence and Mooring Site Licence application")
msg = "Person can have only one WLA, Waiting List application, Mooring Site Licence and Mooring Site Licence application"
logger.error(msg)
raise serializers.ValidationError(msg)

def validate_vessel_length(self, request):
min_mooring_vessel_size_str = GlobalSettings.objects.get(key=GlobalSettings.KEY_MINUMUM_MOORING_VESSEL_LENGTH).value
Expand Down
5 changes: 5 additions & 0 deletions mooringlicensing/components/proposals/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -797,6 +797,11 @@ def validate(self, data):
if not self.instance.electoral_roll_documents.all():
custom_errors["Silent Elector"] = "You must provide evidence of this"

# When company ownership, vessel registration document is compalsory
if not self.instance.vessel_ownership.individual_owner:
if not self.instance.vessel_ownership.vessel_registration_documents.count():
custom_errors["Copy of registration papers"] = "You must provide evidence of this"

if custom_errors.keys():
raise serializers.ValidationError(custom_errors)

Expand Down
11 changes: 6 additions & 5 deletions mooringlicensing/components/proposals/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,10 +585,10 @@ def submit_vessel_data(instance, request, vessel_data):
else:
raise serializers.ValidationError("Application cannot be submitted without a vessel listed")

# Handle fields of the Proposal obj
# Update Proposal obj
save_vessel_data(instance, request, vessel_data)

# Handle VesselDetails obj
# Update VesselDetails obj
vessel, vessel_details = store_vessel_data(request, vessel_data)

# Associate the vessel_details with the proposal
Expand Down Expand Up @@ -915,13 +915,14 @@ def ownership_percentage_validation(vessel_ownership, proposal):
})

## Calc total existing
vessel_ownerships_to_excluded = proposal.get_previous_vessel_ownerships()
logger.info(f'Vessel ownerships to be excluded from the calculation: {vessel_ownerships_to_excluded}')
previous_vessel_ownerships = proposal.get_previous_vessel_ownerships()
logger.info(f'Vessel ownerships to be excluded from the calculation: {previous_vessel_ownerships}')

total_percent = vessel_ownership_percentage
vessel = vessel_ownership.vessel
for vo in vessel.filtered_vesselownership_set.all():
if vo in vessel_ownerships_to_excluded:
if vo in previous_vessel_ownerships:
# We don't want to count the percentage in the previous vessel ownerships
continue
# if hasattr(vo.company_ownership, 'id'):
if vo.company_ownerships.count():
Expand Down
2 changes: 1 addition & 1 deletion mooringlicensing/frontend/mooringlicensing/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ module.exports = {
vessel_internal_list: '/api/vessel/list_internal',
waitinglistapplication: '/api/waitinglistapplication/',
waitinglistallocation: '/api/waitinglistallocation/',
existing_mooring_licences: '/api/mooringlicence/existing_mooring_licences',
// existing_mooring_licences: '/api/mooringlicence/existing_mooring_licences',
existing_licences: '/api/approvals/existing_licences',
annualadmissionapplication: '/api/annualadmissionapplication/',
authoriseduserapplication: '/api/authoriseduserapplication/',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,6 @@ export default {
},
templateSelection: function (data) {
console.log("in templateSelection()");
console.log({ data })
return vm.validateRegoNo(data.text);
},
}).
Expand Down Expand Up @@ -894,7 +893,8 @@ export default {
this.$nextTick(async () => {
console.log('in mounted nextTick()')
await this.fetchVesselTypes();
if ((this.proposal && this.keep_current_vessel) || (!this.keep_current_vessel && this.proposal && this.proposal.proposal_type.code !== 'new')) {
// if ((this.proposal && this.keep_current_vessel) || (!this.keep_current_vessel && this.proposal && this.proposal.proposal_type.code !== 'new')) {
if (this.proposal){
console.log('%cPerform fetchDraftData', consoleColour)
// fetches vessel data from proposal (saved as draft)
Expand Down
4 changes: 3 additions & 1 deletion mooringlicensing/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
from django.urls import path

router = routers.DefaultRouter()
if settings.DEBUG is not True:
router.include_root_view = False
router.register(r'organisations', org_api.OrganisationViewSet)
router.register(r'proposal', proposal_api.ProposalViewSet)
router.register(r'proposal_by_uuid', proposal_api.ProposalByUuidViewSet)
Expand All @@ -54,7 +56,7 @@
router.register(r'moorings_paginated', proposal_api.MooringPaginatedViewSet)
router.register(r'approvals', approval_api.ApprovalViewSet)
router.register(r'waitinglistallocation', approval_api.WaitingListAllocationViewSet)
router.register(r'mooringlicence', approval_api.MooringLicenceViewSet)
# router.register(r'mooringlicence', approval_api.MooringLicenceViewSet)
router.register(r'compliances', compliances_api.ComplianceViewSet)
router.register(r'proposal_requirements', proposal_api.ProposalRequirementViewSet)
router.register(r'proposal_standard_requirements', proposal_api.ProposalStandardRequirementViewSet)
Expand Down

0 comments on commit af87e1a

Please sign in to comment.