Untitled

mail@pastecode.io avatar
unknown
plain_text
16 days ago
5.9 kB
1
Indexable
Never
def currentvoyage_selecthandler(request):
	# for Longest common substring
	from difflib import SequenceMatcher

	if request.user.is_authenticated():
		user_type = models.Users.objects.filter(user = request.user)[0].user_type
		# print "User Type", user_type
		key = json.loads(request.GET['id'])
		check_cache=False
		if "only_cache" in request.GET:
			# print (request.GET["only_cache"])
			check_cache = True
		check_DP = False
		if "only_DP" in request.GET:
			check_DP = True
		check_VA = False
		if "only_VA" in request.GET:
			check_VA = True
		# print "key ", key
		if user_type == 'voyage_manager':
			voyage_manager = models.Users.objects.filter(user = request.user)[0].voyage_manager
			voyage_det= (models.Voyage.objects.values_list('id', 'voyage_no').filter(ship=key, voyage_manager = voyage_manager, live_on_comparator=True))
		elif user_type == 'receiver':
			receiver = models.Users.objects.filter(user = request.user)[0].receiver
			# print receiver
			voyage_det= (models.Voyage.objects.values_list('id', 'voyage_no').filter(ship=key, receiver = receiver, live_on_comparator=True))
			# print "voy_det", voyage_det
		elif user_type == 'charterer':
			charterer = models.Users.objects.filter(user = request.user)[0].charterer
			voyage_det= (models.Voyage.objects.values_list('id', 'voyage_no').filter(ship=key, charterer = charterer, live_on_comparator=True))
		else:
			voyage_det= (models.Voyage.objects.values_list('id', 'voyage_no').filter(ship=key, live_on_comparator=True))
			# print "Admin..", voyage_det
		voyage_det = voyage_det.order_by('-completed_date')
		voyage_det = list(voyage_det)
		voyage_data=[]
		# print voyage_det
		grouped_voyages = {}
		voyage_start_dates = []
		start_dates = []
		voyage_det_ids = [v[0] for v in voyage_det]
		
		# filtered_voyage_det_ids = set()

		# if check_DP:
		# 	latest_queue_entries = models.dp_queue_entries.objects.filter(audit_log__voyage__in=voyage_det_ids).values('audit_log').annotate(latest_queue_entry = Max('id'))
		# 	latest_queue_entry_ids = []
		# 	for latest_queue_entry in latest_queue_entries:
		# 		latest_queue_entry_ids.append(latest_queue_entry['latest_queue_entry'])
		# 	dp_transferred_voyage_ids = set(models.dp_queue_entries.objects.filter(id__in=latest_queue_entry_ids, status=6).values_list('audit_log__voyage', flat=True))
		# 	cache_exist_voyages_ids = set(models.generate_cache_entry.objects.filter(generate_status = 'generated', voyage__in = voyage_det_ids).values_list("voyage", flat = True).distinct())
		# 	filtered_voyage_det_ids = set.union(dp_transferred_voyage_ids,cache_exist_voyages_ids)

		# port_det = models.Port.objects.filter(voyage__in = filtered_voyage_det_ids).values("voyage_id").annotate(first_port = Min(F('id')), last_port = Max(F('id'))).values('voyage_id','first_port', 'last_port')

		# port_ids = []
		# for det in port_det:
		# 	port_ids += [det['first_port'], det['last_port']]
		
		# port_instances = models.Port.objects.filter(id__in = port_ids).order_by('id')

		# v_wise_port = {}
		# for port in port_instances:
		# 	voyage_id = port.voyage_id 
		# 	if voyage_id not in v_wise_port:
		# 		v_wise_port[voyage_id] = {
		# 			'first_port' : port,
		# 		}
		# 	v_wise_port[voyage_id]['last_port'] = port
		for v in voyage_det:
			voyage_id = v[0]
			if check_cache==True:
				mypath=os.path.join(settings.PYTH_DIR,"Data/Cached_Plans/")
				if not os.path.exists(mypath+'cached_header'+str(v[0])+'.p'):
					continue
			if check_DP == True:
				mypath = os.path.join(settings.PYTH_DIR,"Data/DP/")
				if not os.path.exists(mypath+'fastdp_voyage_'+str(v[0])+'.p'):
					if not os.path.exists(mypath+'fastdp_route_voyage_'+str(v[0])+'.p'):
						dp_exist_flag = False
				cache_path = os.path.join(settings.PYTH_DIR,"Data/Cache_Dir/")
				if not os.path.exists(cache_path+str(v[0])+"/"):
					cache_exist_flag = False
				if dp_exist_flag is False and cache_exist_flag is False:
					continue
				# if voyage_id not in filtered_voyage_det_ids:
				# 	continue
			
			if check_VA == True:
				gridpath = os.path.join(settings.PYTH_DIR,"Data/WeatherGrids/")
				cp_schedpath = os.path.join(settings.PYTH_DIR,"Data/speed_schedules/")
				if not os.path.exists(gridpath+'cp_grid_'+str(v[0])+'.p'):
					if not os.path.exists(cp_schedpath+str(v[0])+'.json'):
						continue
			last_port = models.Port.objects.filter(voyage_id=v[0]).order_by('-id').first()
			if last_port:
				eta=last_port.ETA
				# print eta,v[0],"====v0"
				eta=eta+timedelta(days=2)
				current_date=datetime.now()
				eta=eta.strftime('%Y-%m-%d')
				current_date=current_date
				current_date=current_date.strftime('%Y-%m-%d')
				if eta>current_date:
					# print v[0]
					voyage_data.append(v)
					first_port_det=models.Port.objects.filter(voyage_id=v[0]).order_by('id').first()
					start_date = first_port_det.ETA
					start_date_key = str(start_date)
					start_date_diff_today = abs((start_date.replace(tzinfo=None) - datetime.now()).total_seconds())

					if start_date_key in grouped_voyages:
						grouped_voyages[start_date_key].append(v)
					else:
						grouped_voyages[start_date_key] = [v]
						start_dates.append((start_date_diff_today, start_date_key))

		start_dates.sort()
		start_date_keys_sorted = [r[1] for r in start_dates]
		formatted_grouped_voyages = {}
		for key in grouped_voyages:
			voyage_names = [r[1] for r in grouped_voyages[key]]
			voyage_name = findlcs(voyage_names) # longest common substring
			voyage_ids_json = json.dumps([r[0] for r in grouped_voyages[key]])
			formatted_grouped_voyages[key] = [voyage_ids_json, voyage_name]

		resp_data = {}
		resp_data['voyage_det'] = list(voyage_data)
		resp_data['grouped_voyages'] = formatted_grouped_voyages
		resp_data['start_date_keys_sorted'] = start_date_keys_sorted
		# resp_data['ship']=key
		resp_data = json.dumps(resp_data)

		return HttpResponse(resp_data)

	else:
		return HttpResponseRedirect('/vast/user_login')
Leave a Comment