<commit_before>import collections
from datetime import datetime, timedelta
from functools import reduce

from flask import Blueprint, request
from flask_security import current_user, login_required, roles_accepted

from sqlalchemy import func, or_
from sqlalchemy.orm import joinedload

from APITaxi_models2 import (
    ADS,
    db,
    Departement,
    Driver,
    Taxi,
    Town,
    Vehicle,
    VehicleDescription,
    ZUPC,
)

from .. import debug, redis_backend, schemas
from ..utils import get_short_uuid
from ..validators import (
    make_error_json_response,
    validate_schema
)


blueprint = Blueprint('taxis', __name__)


@blueprint.route('/taxis', methods=['POST'])
@login_required
@roles_accepted('admin', 'operateur')
def taxis_create():
    """Endpoint POST /taxis to create Taxi object. If the taxi already exists, which is
    defined as the combination of an ads, a vehicle and a driver, it is
    returned instead of being created.

    ---
    post:
      tags:
        - operator
      summary: Create a new taxi.
      description: |
        This is the last step after creating the driver, the vehicle, and the ADS.

        A taxi is the combination of an ADS, a Vehicle and a Driver.
        If the same user posts the same combination, no new taxi is created,
        and the API returns 200 instead.

        The driver departement is the departement number.
      requestBody:
        content:
          application/json:
            schema: DataCreateTaxiSchema
            example: {
                data: [
                    {
                        driver: {
                            professional_licence: "foobar-994468249464",
                            departement: "76",
                        },
                        vehicle: {
                            licence_plate: "AB-123-CD",
                        },
                        ads: {
                            numero: "123",
                            insee: "75056",
                        }
                    }
                ]
            }
      security:
        - ApiKeyAuth: []
      responses:
        200:
          description: Return the existing taxi.
          content:
            application/json:
              schema: DataTaxiSchema
        201:
          description: Return the new taxi.
    """
    schema = schemas.DataTaxiSchema()

    params, errors = validate_schema(schema, request.json)
    if errors:
        return make_error_json_response(errors)

    args = params['data'][0]

    errors = {}

    ads = ADS.query.options(joinedload(ADS.town)).filter_by(
        insee=args['ads']['insee'],
        numero=args['ads']['numero'],
        added_by=current_user
    ).order_by(ADS.id.desc()).first()
    if not ads:
        errors['ads'] = {
            'insee': ['ADS not found with this INSEE/numero'],
            'numero': ['ADS not found with this INSEE/numero']
        }
    vehicle = Vehicle.query.options(joinedload('*')).filter_by(
        licence_plate=args['vehicle']['licence_plate']
    ).one_or_none()
    if not vehicle:
        errors['vehicle'] = {
            'licence_plate': ['Invalid licence plate']
        }
    else:
        for vehicle_description in vehicle.descriptions:
            if vehicle_description.added_by == current_user:
                break
        else:
            errors['vehicle'] = {
                'licence_plate': ['Vehicle exists but has not been created by the user making the request']
            }

    departement = Departement.query.filter_by(
        numero=args['driver']['departement']['numero']
    ).one_or_none()
    if not departement:
        errors['driver'] = {
            'departement': ['Departement not found']
        }

    driver = Driver.query.options(joinedload('*')).filter_by(
        professional_licence=args['driver']['professional_licence'],
        departement=departement,
        added_by=current_user
    ).order_by(Driver.id.desc()).first()
    if not driver:
        if 'driver' not in errors:
            errors['driver'] = {}
        errors['driver'].update({
            'professional_licence': ['Driver not found with this professional_licence. Is it the correct departement?'],
        })

    if errors:
        return make_error_json_response({
            'data': {'0': errors}
        }, status_code=404)

    # Try to get existing Taxi, or create it.
    taxi = Taxi.query.options(joinedload('*')).filter_by(
        ads=ads,
        driver=driver,
        vehicle=vehicle,
        added_by=current_user
    ).order_by(Taxi.id.desc()).first()

    status_code = 200

    if not taxi:
        status_code = 201
        taxi = Taxi(<commit_msg>views: getting rid of joinloading the universe<commit_after>import collections
from datetime import datetime, timedelta
from functools import reduce

from flask import Blueprint, request
from flask_security import current_user, login_required, roles_accepted

from sqlalchemy import func, or_
from sqlalchemy.orm import joinedload

from APITaxi_models2 import (
    ADS,
    db,
    Departement,
    Driver,
    Taxi,
    Town,
    Vehicle,
    VehicleDescription,
    ZUPC,
)

from .. import debug, redis_backend, schemas
from ..utils import get_short_uuid
from ..validators import (
    make_error_json_response,
    validate_schema
)


blueprint = Blueprint('taxis', __name__)


@blueprint.route('/taxis', methods=['POST'])
@login_required
@roles_accepted('admin', 'operateur')
def taxis_create():
    """Endpoint POST /taxis to create Taxi object. If the taxi already exists, which is
    defined as the combination of an ads, a vehicle and a driver, it is
    returned instead of being created.

    ---
    post:
      tags:
        - operator
      summary: Create a new taxi.
      description: |
        This is the last step after creating the driver, the vehicle, and the ADS.

        A taxi is the combination of an ADS, a Vehicle and a Driver.
        If the same user posts the same combination, no new taxi is created,
        and the API returns 200 instead.

        The driver departement is the departement number.
      requestBody:
        content:
          application/json:
            schema: DataCreateTaxiSchema
            example: {
                data: [
                    {
                        driver: {
                            professional_licence: "foobar-994468249464",
                            departement: "76",
                        },
                        vehicle: {
                            licence_plate: "AB-123-CD",
                        },
                        ads: {
                            numero: "123",
                            insee: "75056",
                        }
                    }
                ]
            }
      security:
        - ApiKeyAuth: []
      responses:
        200:
          description: Return the existing taxi.
          content:
            application/json:
              schema: DataTaxiSchema
        201:
          description: Return the new taxi.
    """
    schema = schemas.DataTaxiSchema()

    params, errors = validate_schema(schema, request.json)
    if errors:
        return make_error_json_response(errors)

    args = params['data'][0]

    errors = {}

    ads = ADS.query.options(joinedload(ADS.town)).filter_by(
        insee=args['ads']['insee'],
        numero=args['ads']['numero'],
        added_by=current_user
    ).order_by(ADS.id.desc()).first()
    if not ads:
        errors['ads'] = {
            'insee': ['ADS not found with this INSEE/numero'],
            'numero': ['ADS not found with this INSEE/numero']
        }
    vehicle = Vehicle.query.options(
        joinedload(Vehicle.descriptions).joinedload(VehicleDescription.added_by)
    ).filter_by(
        licence_plate=args['vehicle']['licence_plate']
    ).one_or_none()
    if not vehicle:
        errors['vehicle'] = {
            'licence_plate': ['Invalid licence plate']
        }
    else:
        for vehicle_description in vehicle.descriptions:
            if vehicle_description.added_by == current_user:
                break
        else:
            errors['vehicle'] = {
                'licence_plate': ['Vehicle exists but has not been created by the user making the request']
            }

    departement = Departement.query.filter_by(
        numero=args['driver']['departement']['numero']
    ).one_or_none()
    if not departement:
        errors['driver'] = {
            'departement': ['Departement not found']
        }

    driver = Driver.query.options(
        joinedload(Driver.added_by), joinedload(Driver.departement)
    ).filter_by(
        professional_licence=args['driver']['professional_licence'],
        departement=departement,
        added_by=current_user
    ).order_by(Driver.id.desc()).first()
    if not driver:
        if 'driver' not in errors:
            errors['driver'] = {}
        errors['driver'].update({
            'professional_licence': ['Driver not found with this professional_licence. Is it the correct departement?'],
        })

    if errors:
        return make_error_json_response({
            'data': {'0': errors}
        }, status_code=404)

    # Try to get existing Taxi, or create it.
    taxi = Taxi.query.options(
        joinedload(Taxi.ads),
        joinedload(Taxi.driver),
        joinedload(Taxi.vehicle),
        joinedload(Taxi.added_by),
    ).filter_by(
        ads=ads,
        driver=driver,
        vehicle=vehicle,
        added_by=current_user
    ).order_by(Taxi.id.desc()).first()

    status_code = 200

    if not taxi:
        status_code = 201
        taxi = Taxi(
{'fraction_non_alphanumeric': 0.09761658031088083, 'fraction_numerical': 0.009533678756476684, 'mean_word_length': 1.9316524908869988, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3912950', 'n_tokens_mistral': 2766, 'n_tokens_neox': 2636, 'n_words': 709}