def open_pay(id):
	if 'plan' not in request.args:
		abort(400, {'message': PLAN_INVALID_OR_NOT_PROVIDED })

	lead = _get_lead(int(id))
	plan = Plan.find_by_slug(request.args['plan'])
	payment = Payment.find_last(lead.key, plan.key)

	if payment is not None:
		return jsonify(data=payment.to_json()), 200
	else:
		abort(404, {'message': 'Payment not found'})
def _create_or_replace_payment(lead, plan_slug, instalments):
	plan = Plan.find_by_slug(plan_slug)
	payment = Payment.find_open(lead.key, plan.key)

	if payment is None:
		payment = Payment()

	payment.lead = lead.key
	payment.plan = plan.key
	payment.status = 'PENDING'
	payment.message = 'Pending processing'
	payment.instalments = instalments
	payment.iframe_url = ''
	payment.put()

	_enqueue_payment_message(lead, payment)

	return payment
def create():

	# get the post data
	post_data = get_post_data()

	sender_broker = None
	owner = None
	agency = None
	listing = None

	# validates required parameters
	_validates_required_parameters(post_data)

	# creates or find the property owner
	if 'property_owner' in post_data:
		owner = _create_property_owner(post_data['property_owner'])

	# creates or find the agency
	if 'agency' in post_data:
		agency = _create_agency(post_data['agency'], post_data['source_application'])

	# creates or find the property
	if 'listing' in post_data:
		listing = _create_listing(post_data['listing'])

	# if broker is sent
	if 'sender' in post_data:
		# creates or find the broker
		sender_broker = _create_broker(post_data['sender'], agency)

	# defines the buyer type and creates the lead
	buyer_type = ''

	if 'sender' in post_data and owner is not None:
		buyer_type = 'PROPERTY_OWNER'
	else:
		buyer_type = 'PROPERTY_OWNER_FROM_GAIAFLIX'


	# check if the plan is valid
	plan = None
	if 'plan' in post_data:
		plan = Plan.find_by_slug(post_data['plan'])
		if plan is None:
			abort(400, {'message': PLAN_INVALID_OR_NOT_PROVIDED })
	else:
		abort(400, {'message': PLAN_INVALID_OR_NOT_PROVIDED })

	# creates the lead
	lead = Lead()

	lead.sender_broker = sender_broker.key if sender_broker is not None else None
	lead.property_owner = owner.key if owner is not None else None
	lead.listing = listing.key if listing is not None else None
	lead.plan = plan.key
	lead.buyer_type = buyer_type
	lead.status = 'SENT'

	if lead.put():
		json_lead = lead.to_json()

		if lead.property_owner is not None:
			_enqueue_lead_message(json_lead)
			create_activity('LEAD_SENT', lead=lead)

		return jsonify(data=json_lead), 201
	else:
		return jsonify({'error': 'Error creating Lead'})