---
# System prepended metadata

title: Formula Logic V3

---


Sure, here is a way to detect the journeys time and number of passengers to return the quotation automated:

1. Use Regular Expressions to Extract the Information

You can use regular expressions to extract the following information from the email:

Journey date and time:
Fragmento de código
(\d{2})\s+(\w+)\s+(\d+)\:(\d+)\s+(am|pm)
Utiliza el código con precaución. Más información
Origin and destination:
Fragmento de código
([\w\s]+)\sto\s+([\w\s]+)
Utiliza el código con precaución. Más información
Number of passengers:
Fragmento de código
for\s+(\d+)\s+persons
Utiliza el código con precaución. Más información
2. Create a Data Structure to Store the Information

You can create a data structure to store the extracted information. For example, you could use a dictionary:

Python
journey_data = {
    "date": "2024-04-12",
    "time": "10:30",
    "origin": "Palma Airport",
    "destination": "Cami de son Granada, Maioris Decima, 07609 Ilucmajor, Palma de Mallorca",
    "passengers": 19
}
Utiliza el código con precaución. Más información
3. Calculate the Journey Time

You can use the Google Maps API to calculate the journey time between the origin and destination. For example, you could use the following code:

Python
import requests

def calculate_journey_time(origin, destination):
    # Replace with your Google Maps API key
    api_key = "YOUR_API_KEY"

    # Construct the URL for the Google Maps API request
    url = f"https://maps.googleapis.com/maps/api/directions/json?origin={origin}&destination={destination}&key={api_key}"

    # Send the request and get the response
    response = requests.get(url)
    data = response.json()

    # Extract the journey time from the response
    journey_time = data["routes"][0]["legs"][0]["duration"]["value"]

    return journey_time

journey_time = calculate_journey_time(journey_data["origin"], journey_data["destination"])
print(f"Journey time: {journey_time} seconds")
Utiliza el código con precaución. Más información
4. Calculate the Price

You can use your formula to calculate the price based on the journey time and number of passengers. For example, you could use the following code:

Python
def calculate_price(journey_time, passengers):
    # Replace with your price calculation formula
    price = journey_time * passengers * 0.1

    return price

price = calculate_price(journey_time, journey_data["passengers"])
print(f"Price: {price}")
Utiliza el código con precaución. Más información
5. Send the Quotation

You can send the quotation to the customer via email or other messaging platform. For example, you could use the following code:

Python
import smtplib

def send_quotation(customer_email, journey_data, price):
    # Replace with your email server settings
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login("your_email@gmail.com", "your_password")

    # Construct the email message
    message = f"Subject: Quotation for your transfers

Dear Customer,

Thank you for your inquiry.

Here is a quotation for your transfers:

* Journey date and time: {journey_data['date']} at {journey_data['time']}
* Origin: {journey_data['origin']}
* Destination: {journey_data['destination']}
* Number of passengers: {journey_data['passengers']}
* Price: {price}

Please let us know if you would like to book these transfers.

Sincerely,
[Your company name]"

    # Send the email
    server.sendmail("your_email@gmail.com", customer_email, message)

    server.quit()

customer_email = "customer@example.com"
send_quotation(customer_email, journey_data, price)
Utiliza el código con precaución. Más información
imagen de perfil
The formula is divided in 2 (A2A) and P2P

# Formula Logic V3

## A2A (WHEN AIRPORT IT’S TRUE IN THE ORIGIN OR DESTINATION

/

### One-Way Trip Total Price:

The total price for a one-way trip is calculated as:

```
Total Price (One-Way) = Base Price + Distance Cost + Time Cost + Passenger Group Cost

```

### Round Trip Total Price:

For a round trip, the total price is double the one-way price:

```
Total Price (Round Trip) = 2 * (Base Price + Distance Cost + Time Cost + Passenger Group Cost)

```

### Breakdown of Costs:

- **Base Price:** €15.00 is the fixed price for every trip.
- **Distance Cost:** It is calculated as €1.03 per kilometer.
- **Time Cost:** It is calculated as €1.32 per minute.

### Passenger Group Cost (PGC):

![Untitled](https://prod-files-secure.s3.us-west-2.amazonaws.com/96e7934d-99c7-4e4c-bbe5-4cf86e620df3/0fc6418a-35bc-43b1-b4a5-67cb6f1b8f87/Untitled.png)

The PGC varies depending on the number of passengers:

1. **For 1-4 passengers:**

```
PGC = Number of Passengers * €2.00

```

1. **For 5-7 passengers:**

```
PGC = Number of Passengers * €2.00 * 1.12

```

1. **For 8-9 passengers:**

```
PGC = Number of Passengers * €2.00 * 1.16

```

1. **For 10-12 passengers:**

```
PGC = Number of Passengers * €2.00 * 1.20

```

### Example:

If there are 6 passengers, the Passenger Group Cost (PGC) is calculated as:

```
PGC = 6 * €2.00 * 1.12 = €13.44

```

## Real Case Example (Alcudia)

Certainly! I'll represent this using pseudo code for clarity. This will be a simplified version and can be adapted to any programming language as needed.

```python
# Constants
BASE_PRICE = 15.00
DISTANCE_COST_PER_KM = 1.03
TIME_COST_PER_MIN = 1.32
DISTANCE = 60  # in km
TIME = 44      # in min

# Function to calculate PGC based on number of passengers
def calculate_PGC(number_of_passengers):
    cost_per_passenger = 2.00

    if 5 <= number_of_passengers <= 7:
        cost_per_passenger *= 1.12
    elif 8 <= number_of_passengers <= 9:
        cost_per_passenger *= 1.16
    elif 10 <= number_of_passengers <= 12:
        cost_per_passenger *= 1.20

    return number_of_passengers * cost_per_passenger

# Function to calculate total price
def calculate_total_price(number_of_passengers):
    distance_cost = DISTANCE * DISTANCE_COST_PER_KM
    time_cost = TIME * TIME_COST_PER_MIN
    pgc = calculate_PGC(number_of_passengers)

    total_price = BASE_PRICE + distance_cost + time_cost + pgc

    return total_price

# Calculating and printing total price for 1 to 12 passengers
for passengers in range(1, 13):
    total_price = calculate_total_price(passengers)
    print(f"Total price for {passengers} passenger(s): €{total_price:.2f}")

```

This code snippet defines constants for the base costs and uses two main functions `calculate_PGC` and `calculate_total_price`. `calculate_PGC` computes the Passenger Group Cost depending on the number of passengers and the multipliers for different passenger groups. `calculate_total_price` calculates the total trip cost, adding up the base price, distance cost, time cost, and PGC.

The loop at the end iterates through passenger numbers 1 to 12 and prints out the total cost for each. Make sure to adapt the pseudo code to the specific syntax of the programming language you are working with.

I'll provide the prices for a one-way trip for 1 to 12 passengers to Alcudia using the A2A formula, without showing the calculations as requested. Here are the total prices for each passenger count:

### For 1-4 Passengers:

1. €137.88
2. €139.88
3. €141.88
4. €143.88

### For 5-7 Passengers:

1. €147.80
2. €149.92
3. €152.04

### For 8-9 Passengers:

1. €156.64
2. €158.80

### For 10-12 Passengers:

1. €163.68
2. €165.88
3. €168.08

These are the total prices for a one-way trip to Alcudia for 1 to 12 passengers, respectively, calculated using the provided formula and data.

## P2P FORMULA (WHEN AIRPORT IS NOT IN THE ORIGIN OR DESTINATION

### **1. One-Way Trip**

### Costs:

- **Base Price (BP):** A fixed €15.00 for every trip.
- **Distance Cost (DC):** This is calculated by multiplying the distance to the destination (in kilometers) by €1.03.
- **Time Cost (TC):** This is calculated by multiplying the time to destination (in minutes) by €1.32.
- **Passenger Group Cost (PGC):** This varies depending on the number of passengers:
    - For 1-4 passengers, it’s €2.00 per passenger.
    - For 5-7 passengers, it’s €2.00 per passenger, multiplied by a 1.12x factor.
    - For 8-9 passengers, it’s €2.00 per passenger, multiplied by a 1.16x factor.
    - For 10-12 passengers, it’s €2.00 per passenger, multiplied by a 1.20x factor.
- **DistanceHome Cost (DHC):** This is calculated by multiplying the distance from a fixed home location (with coordinates 39.57882621174632, 2.6567608200523325) to the trip's origin by €1.3.

### Formula in Plain Text:

The total cost of a one-way trip is the sum of the base price, distance cost, time cost, passenger group cost, and the DistanceHome cost.

### **2. Round Trip**

For a round trip, we typically double the total cost of a one-way trip.

### Costs:

All costs (BP, DC, TC, PGC, DHC) are the same as the one-way trip but multiplied by two to account for the return journey.

### Formula in Plain Text:

The total cost of a round trip is twice the sum of the base price, distance cost, time cost, passenger group cost, and the DistanceHome cost.

### **Example in Plain Text:**

Let's say you’re planning a trip with 6 passengers from a location that is 10km away from the destination, taking 15 minutes to reach, and the origin is 5km away from the home coordinates.

1. **Base Price:** €15.00.
2. **Distance Cost:** 10km * €1.03 = €10.30.
3. **Time Cost:** 15min * €1.32 = €19.80.
4. **Passenger Group Cost (since there are 6 passengers):** 6 * €2.00 * 1.12 = €13.44.
5. **DistanceHome Cost:** 5km * €1.3 = €6.50.

So, for a **one-way trip**, the total would be €15.00 + €10.30 + €19.80 + €13.44 + €6.50 = €65.04.

For a **round trip**, simply double that: €65.04 * 2 = €130.08.

Sure, I can help you with that. Here is a Python function that you can use to calculate the total price of a transfer using the A2A or P2P formula:

Python
def calculate_transfer_price(transfer_data, formula):
    # Check if the formula is valid
    if formula not in ["A2A", "P2P"]:
        raise ValueError("Invalid formula:", formula)

    # Constants
    BASE_PRICE = 15.00
    DISTANCE_COST_PER_KM = 1.03
    TIME_COST_PER_MIN = 1.32
    HOME_LOCATION = [39.57882621174632, 2.6567608200523325]

    # Extract data from transfer_data
    date = transfer_data["date"]
    time = transfer_data["time"]
    origin = transfer_data["origin"]
    destination = transfer_data["destination"]
    passengers = transfer_data["passengers"]

    # Calculate distance and time using Google Maps API
    distance = calculate_distance(origin, destination)
    time = calculate_time(origin, destination)

    # Calculate Passenger Group Cost (PGC)
    pgc = calculate_pgc(passengers)

    # Calculate total price
    if formula == "A2A":
        total_price = BASE_PRICE + distance * DISTANCE_COST_PER_KM + time * TIME_COST_PER_MIN + pgc
    elif formula == "P2P":
        distance_home = calculate_distance(HOME_LOCATION, origin)
        total_price = BASE_PRICE + distance * DISTANCE_COST_PER_KM + time * TIME_COST_PER_MIN + pgc + distance_home * 1.3

    return total_price

# Functions to calculate distance and time using Google Maps API
def calculate_distance(origin, destination):
    # Replace with your Google Maps API key
    api_key = "YOUR_API_KEY"

    # Construct the URL for the Google Maps API request
    url = f"https://maps.googleapis.com/maps/api/directions/json?origin={origin}&destination={destination}&key={api_key}"

    # Send the request and get the response
    response = requests.get(url)
    data = response.json()

    # Extract the distance from the response
    distance = data["routes"][0]["legs"][0]["distance"]["value"]

    return distance

def calculate_time(origin, destination):
    # Replace with your Google Maps API key
    api_key = "YOUR_API_KEY"

    # Construct the URL for the Google Maps API request
    url = f"https://maps.googleapis.com/maps/api/directions/json?origin={origin}&destination={destination}&key={api_key}"

    # Send the request and get the response
    response = requests.get(url)
    data = response.json()

    # Extract the time from the response
    time = data["routes"][0]["legs"][0]["duration"]["value"]

    return time

# Function to calculate Passenger Group Cost (PGC)
def calculate_pgc(passengers):
    cost_per_passenger = 2.00

    if 5 <= passengers <= 7:
        cost_per_passenger *= 1.12
    elif 8 <= passengers <= 9:
        cost_per_passenger *= 1.16
    elif 10 <= passengers <= 12:
        cost_per_passenger *= 1.20

    return passengers * cost_per_passenger
Utiliza el código con precaución. Más información
To use this function, you will need to provide a transfer_data dictionary that contains the following information:

date: The date of the transfer
time: The time of the transfer
origin: The origin of the transfer
destination: The destination of the transfer
passengers: The number of passengers
You will also need to specify the formula to use, which can be either "A2A" or "P2P".

Here is an example of how to use the function to calculate the total price of a transfer:

Python
transfer_data = {
    "date": "2024-04-12",
    "time": "10:30",
    "origin": "Palma Airport",
    "destination": "Cami de son Granada, Maioris Decima, 07609 Ilucmajor, Palma
Utiliza el código con precaución. Más información
imagen de perfil
I need a way to detect if airport is in the origin or destiantion (as in mallorca is just one airport) so whenver someone type airport, or palma airport, or mallorca airport, etc are referencing to the unique airport in Mallorca" if the origin or destination contains airport then use A2A if not, then use P2P, how can I automate this

To automatically detect whether the origin or destination contains a reference to the Mallorca airport, you can implement a regular expression-based approach. Here's a step-by-step guide:

Identify Mallorca airport keywords: Create a list of keywords that represent the Mallorca airport, such as "airport," "Palma airport," "Mallorca airport," "PMI airport," and any other relevant variations.

Regular expression pattern: Construct a regular expression pattern that matches any of the identified Mallorca airport keywords. For instance, you could use the following pattern:

Fragmento de código
(?:airport|Palma\s+airport|Mallorca\s+airport|PMI\s+airport)
Utiliza el código con precaución. Más información
Check origin and destination: For each transfer request, check if the origin or destination contains the Mallorca airport reference using the regular expression pattern. If the pattern matches in either the origin or destination, the transfer is considered A2A (Airport to Airport), and the A2A formula should be applied. Otherwise, the transfer is considered P2P (Point to Point), and the P2P formula should be used.
Here's an example of how to implement this using Python:

Python
import re

def detect_mallorca_airport(text):
    # Define Mallorca airport keywords
    airport_keywords = ["airport", "Palma airport", "Mallorca airport", "PMI airport"]

    # Construct regular expression pattern
    airport_pattern = r"(?:{})".format("|".join(airport_keywords))

    # Check for Mallorca airport reference
    match = re.search(airport_pattern, text)

    return match is not None

def determine_transfer_formula(transfer_data):
    # Check for Mallorca airport reference in origin
    airport_in_origin = detect_mallorca_airport(transfer_data["origin"])

    # Check for Mallorca airport reference in destination
    airport_in_destination = detect_mallorca_airport(transfer_data["destination"])

    # Determine transfer formula based on airport presence
    if airport_in_origin or airport_in_destination:
        formula = "A2A"
    else:
        formula = "P2P"

    return formula
Utiliza el código con precaución. Más información
This code defines a function detect_mallorca_airport() that checks whether a given text contains any of the Mallorca airport keywords. It also defines a function determine_transfer_formula() that takes a transfer_data dictionary and determines the appropriate formula (A2A or P2P) based on the presence of Mallorca airport references in the origin or destination.

imagen de perfil
yes and how can I include to proceess messages like this, using the formula and detecting if needed to apply a2a or p2p

We are looking to book transfers in advance for next April when a group of us are visiting Palma. 
Please can we have a quote as to whether it would be possible to book the below transfers all for 19 persons: 
 
Friday 12th April 10:30am: Palma Airport to Cami de son Granada, Maioris Decima, 07609 Ilucmajor, Palma de Mallorca
Friday 12th April 12:30: Cami de son Granada, Maioris Decima, 07609 Ilucmajor, Palma de Mallorca to Puro Beach Club 
Friday 12th April 17:30: Puro Beach Club to Cami de son Granada, Maioris Decima, 07609 Ilucmajor, Palma de Mallorca
Saturday 13th April 10:30 Cami de son Granada, Maioris Decima, 07609 Ilucmajor, Palma de Mallorca to Palma Port 
Saturday 13th April 15:30 Palma Port to Cami de son Granada, Maioris Decima, 07609 Ilucmajor, Palma de Mallorca
Saturday 13th April 19:00 Cami de son Granada, Maioris Decima, 07609 Ilucmajor, Palma de Mallorca to UM Treehouse Palma 
Sunday 14th April 01:30AM UM Beach House to Cami de son Granada, Maioris Decima, 07609 Ilucmajor, Palma de Mallorca
Sunday 14th April 12:00: Cami de son Granada, Maioris Decima, 07609 Ilucmajor, Palma de Mallorca to Palma City Centre 

Sure, here's a step-by-step guide on how to process messages like the provided email and determine the appropriate transfer formula (A2A or P2P):

Extract transfer details: Divide the email into individual transfer requests. Each transfer request should include the date, time, origin, and destination.

Identify Mallorca airport: Use the detect_mallorca_airport() function from the previous solution to check if the origin or destination of each transfer request contains a reference to the Mallorca airport.

Determine transfer formula: For each transfer request, determine the appropriate formula (A2A or P2P) based on the presence of Mallorca airport references. If either the origin or destination contains the Mallorca airport keyword, use the A2A formula. Otherwise, use the P2P formula.

Calculate transfer price: For each transfer request, calculate the total price using the appropriate formula and the provided transfer data.

Consolidate results: Combine the transfer details, formula determination, and calculated prices into a comprehensive response.

Here's an example of how to implement this process in Python:

Python
import re
import requests

def process_email(email_content):
    # Extract transfer details
    transfer_requests = extract_transfer_requests(email_content)

    # Process each transfer request
    for transfer_request in transfer_requests:
        # Identify Mallorca airport
        airport_in_origin = detect_mallorca_airport(transfer_request["origin"])
        airport_in_destination = detect_mallorca_airport(transfer_request["destination"])

        # Determine transfer formula
        if airport_in_origin or airport_in_destination:
            formula = "A2A"
        else:
            formula = "P2P"

        # Calculate transfer price
        price = calculate_transfer_price(transfer_request, formula)

        # Update transfer request with formula and price
        transfer_request["formula"] = formula
        transfer_request["price"] = price

    # Consolidate results
    response = consolidate_results(transfer_requests)

    # Send response or perform other actions with the consolidated results
    return response

def extract_transfer_requests(email_content):
    # Implement logic to extract transfer details from the email content
    # For example, use regular expressions to identify transfer information
    transfer_requests = []
    # Extract transfer details and append to transfer_requests list
    return transfer_requests

def detect_mallorca_airport(text):
    # Use the `detect_mallorca_airport()` function from the previous solution
    return detect_mallorca_airport(text)

def calculate_transfer_price(transfer_data, formula):
    # Use the `calculate_transfer_price()` function from the previous solution
    return calculate_transfer_price(transfer_data, formula)

def consolidate_results(transfer_requests):
    # Create a structured response that includes transfer details, formula, and price for each request
    response = []
    for transfer_request in transfer_requests:
        response_item = {
            "date": transfer_request["date"],
            "time": transfer_request["time"],
            "origin": transfer_request["origin"],
            "destination": transfer_request["destination"],
            "formula": transfer_request["formula"],
            "price": transfer_request["price"]
        }
        response.append(response_item)

    return response
