Skip to content

Commit

Permalink
Merge branch 'geo_survey'
Browse files Browse the repository at this point in the history
  • Loading branch information
arniverd committed May 10, 2021
2 parents 956f582 + ca0d3b5 commit 2d69d8c
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 83 deletions.
14 changes: 8 additions & 6 deletions app/crud/contact.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
from app.crud.enmarche import get_candidate_zone


def get_contacts(db: Session, adherent: Adherents):
zone = get_candidate_zone(db, adherent)
filter_zone = {zone.type: zone.name}
def get_contacts(db: Session, uuid: str):
if (zone := get_candidate_zone(db, uuid)) is None:
return None
filter_zone = {'departement': zone.name} if zone.type == 'department' else {zone.type: zone.name}

contacts = [contact.serialize() for contact in
db.query(Contact).filter_by(**filter_zone).all()]
Expand All @@ -28,9 +29,10 @@ def get_contacts(db: Session, adherent: Adherents):
}


def get_number_of_contacts(db: Session, adherent: Adherents):
zone = get_candidate_zone(db, adherent)
filter_zone = {zone.type: zone.name}
def get_number_of_contacts(db: Session, uuid: str):
if (zone := get_candidate_zone(db, uuid)) is None:
return None
filter_zone = {'departement': zone.name} if zone.type == 'department' else {zone.type: zone.name}

return {
'adherentCount': db.query(Contact).filter_by(**filter_zone).count(),
Expand Down
21 changes: 6 additions & 15 deletions app/crud/enmarche.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,9 @@ def me(db: Session, uuid: str) -> Adherents:
return adherent


def get_candidate_zone(db: Session, adherent: Adherents):
if adherent is None:
raise Exception('Adherent not found')

if (managedArea := db.query(CandidateManagedArea) \
.filter(CandidateManagedArea.id == adherent.get_candidate_managed_area()) \
.first()) is None:
raise Exception('No managed area found')

if (geoZone := db.query(GeoZone) \
.filter(GeoZone.id == managedArea.get_zone_id()) \
.first()) is None:
raise Exception('Geo_zone not found')

return geoZone
def get_candidate_zone(db: Session, uuid: str):
return db.query(GeoZone) \
.join(CandidateManagedArea) \
.join(Adherents) \
.filter(Adherents.uuid == uuid) \
.first()
46 changes: 24 additions & 22 deletions app/crud/jemengage.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""
Endpoints de notre api
"""
from sqlalchemy.orm import Session
from sqlalchemy.orm import Session, joinedload
from sqlalchemy import func, desc, Date
from datetime import date, timedelta

from typing import Optional
from app.models.models_enmarche import GeoCity, GeoDepartment, GeoRegion
from app.models.models_enmarche import Adherents, JecouteSurvey
from app.models.models_enmarche import Adherents, JecouteDataSurvey, JecouteSurvey
from app.models.models_crm import Downloads, Users
from app.crud.enmarche import me, get_candidate_zone
from app.database.database_crm import engine_crm
Expand All @@ -17,11 +17,11 @@

def get_downloads(
db: Session,
adherent: Adherents,
uuid: str,
before: Date = date.today(),
range: int = 28
):
if (zone := get_candidate_zone(db, adherent)) is None:
if (zone := get_candidate_zone(db, uuid)) is None:
return None

# We first add filter by geo_zone
Expand Down Expand Up @@ -54,11 +54,11 @@ def get_downloads(

def get_users(
db: Session,
adherent: Adherents,
uuid: str,
before: Date = date.today(),
range: int = 28
):
if (zone := get_candidate_zone(db, adherent)) is None:
if (zone := get_candidate_zone(db, uuid)) is None:
return None

# We first add filter by geo_zone
Expand Down Expand Up @@ -91,28 +91,30 @@ def get_users(

def get_survey(
db: Session,
adherent: Adherents
uuid: str
):
if (zone := get_candidate_zone(db, adherent)) is None:
if (zone := get_candidate_zone(db, uuid)) is None:
return None

if zone.type == 'department':
return db.query(JecouteSurvey) \
.filter(JecouteSurvey.postal_code != '') \
.join(GeoCity, GeoCity.postal_code == JecouteSurvey.postal_code) \
return db.query(JecouteDataSurvey, JecouteSurvey) \
.filter(JecouteDataSurvey.postal_code is not None) \
.join(GeoCity, func.instr(GeoCity.postal_code, JecouteDataSurvey.postal_code)) \
.join(GeoDepartment) \
.join(JecouteSurvey) \
.filter(GeoDepartment.code == zone.code) \
.filter(JecouteSurvey.latitude != '') \
.filter(JecouteSurvey.longitude != '') \
.filter(JecouteDataSurvey.latitude != '') \
.filter(JecouteDataSurvey.longitude != '') \
.all()

if zone.type == 'region':
return db.query(JecouteSurvey) \
.filter(JecouteSurvey.postal_code != '') \
.join(GeoCity, GeoCity.postal_code.like('%' + JecouteSurvey.postal_code + '%')) \
.join(GeoDepartment) \
.join(GeoRegion) \
.filter(GeoRegion.code == zone.code) \
.filter(JecouteSurvey.latitude != '') \
.filter(JecouteSurvey.longitude != '') \
.all()
return db.query(JecouteDataSurvey) \
.options(joinedload(JecouteDataSurvey.jecoute_survey)) \
.filter(JecouteDataSurvey.postal_code != '') \
.join(GeoCity, GeoCity.postal_code.like('%' + JecouteDataSurvey.postal_code + '%')) \
.join(GeoDepartment) \
.join(GeoRegion) \
.filter(GeoRegion.code == zone.code) \
.filter(JecouteDataSurvey.latitude != '') \
.filter(JecouteDataSurvey.longitude != '') \
.all()
28 changes: 21 additions & 7 deletions app/models/models_enmarche.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,17 @@ class Adherents(Base):

id = Column(Integer, primary_key=True, index=True)
uuid = Column(String(36), unique=True, nullable=False, index=True)
candidate_managed_area_id = Column(Integer)

def get_candidate_managed_area(self):
return self.candidate_managed_area_id
candidate_managed_area_id = Column(Integer, ForeignKey('candidate_managed_area.id'))
candidate_managed_area = relationship('CandidateManagedArea')


class CandidateManagedArea(Base):
""" Table candidate_managed_area pour retrouver la zone_id """
__tablename__ = 'candidate_managed_area'

id = Column(Integer, primary_key=True, index=True)
zone_id = Column(Integer, nullable=False)
zone_id = Column(Integer, ForeignKey('geo_zone.id'))
candidate_managed_zone = relationship('GeoZone')

def get_zone_id(self):
return self.zone_id
Expand Down Expand Up @@ -89,16 +88,31 @@ class OauthAccessTokens(Base):
created_at = Column(DateTime, nullable=False, index=True)


class JecouteSurvey(Base):
class JecouteDataSurvey(Base):
""" Table jecoute_data_survey """
__tablename__ = 'jecoute_data_survey'

id = Column(Integer, primary_key=True, index=True)
author_id = Column(Integer, nullable=True)
survey_id = Column(Integer, nullable=False)
posted_at = Column(DateTime, nullable=False)
postal_code = Column(String, nullable=True)
age_range = Column(String, nullable=True)
gender = Column(String, nullable=True)
latitude = Column(Float, nullable=True)
longitude = Column(Float, nullable=True)
survey_id = Column(Integer, ForeignKey('jecoute_survey.id'))
jecoute_survey = relationship('JecouteSurvey', lazy='joined')


class JecouteSurvey(Base):
""" Table jecoute_data_survey """
__tablename__ = 'jecoute_survey'

id = Column(Integer, primary_key=True, index=True)
author_id = Column(Integer, nullable=True)
name = Column(String, nullable=False)
created_at = Column(DateTime, nullable=False)
updated_at = Column(DateTime, nullable=False)
type = Column(String, nullable=False)
zone_id = Column(Integer, ForeignKey('geo_zone.id'))
geo_zone = relationship('GeoZone')
16 changes: 14 additions & 2 deletions app/schemas/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,16 +76,28 @@ class Config:
"""


class JecouteSurvey(BaseModel):

class Survey(BaseModel):
id: int
author_id: Optional[str]
name: str
created_at: datetime
updated_at: datetime

class Config:
orm_mode = True


class DataSurvey(BaseModel):
id: int
author_id: Optional[str]
survey_id: str
posted_at: datetime
postal_code: Optional[str]
age_range: Optional[str]
gender: Optional[str]
latitude: Optional[float]
longitude: Optional[float]
survey: Survey

class Config:
orm_mode = True
38 changes: 7 additions & 31 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,7 @@ async def read_contacts(
return HTTPException(status_code=401, detail='You are not authenticated.')

try:
me = enmarche.me(db, X_User_UUID)
except:
return HTTPException(status_code=403, detail='You are not allowed to access these datas.')

try:
contacts = contact.get_contacts(db, adherent=me)
contacts = contact.get_contacts(db, X_User_UUID)
except:
return HTTPException(status_code=204, detail='No contact found')
return contacts
Expand All @@ -84,12 +79,7 @@ async def get_adherents(
if not X_User_UUID:
return HTTPException(status_code=401, detail='You are not authenticated.')

try:
me = enmarche.me(db, X_User_UUID)
except:
return HTTPException(status_code=403, detail='You are not allowed to access these datas.')

return contact.get_number_of_contacts(db, me)
return contact.get_number_of_contacts(db, X_User_UUID)



Expand All @@ -101,12 +91,7 @@ async def jemengage_downloads(
if not X_User_UUID:
return HTTPException(status_code=401, detail='You are not authenticated.')

try:
me = enmarche.me(db, X_User_UUID)
except:
return HTTPException(status_code=403, detail='You are not allowed to access these datas.')

res = jemengage.get_downloads(db, me)
res = jemengage.get_downloads(db, X_User_UUID)
if res.empty:
return HTTPException(status_code=204, detail='No content')

Expand All @@ -122,33 +107,24 @@ async def jemengage_users(
if not X_User_UUID:
return HTTPException(status_code=401, detail='You are not authenticated.')

try:
me = enmarche.me(db, X_User_UUID)
except:
return HTTPException(status_code=403, detail='You are not allowed to access these datas.')

res = jemengage.get_users(db, me)
res = jemengage.get_users(db, X_User_UUID)
if res.empty:
return HTTPException(status_code=204, detail='No content')

res = res.to_json(orient='records')
return {'users': json.loads(res)}


@app.get('/jemengage/survey', response_model=List[schemas.JecouteSurvey], response_class=ORJSONResponse)
#@app.get('/jemengage/survey', response_model=List[schemas.DataSurvey], response_class=ORJSONResponse)
@app.get('/jemengage/survey', response_class=ORJSONResponse)
async def jemengage_survey(
db: Session = Depends(get_db),
X_User_UUID: Optional[str] = Header(None)
):
if not X_User_UUID:
return HTTPException(status_code=401, detail='You are not authenticated.')

try:
me = enmarche.me(db, X_User_UUID)
except:
return HTTPException(status_code=403, detail='You are not allowed to access these datas.')

return jemengage.get_survey(db, adherent=me)
return jemengage.get_survey(db, X_User_UUID)


if __name__ == "__main__":
Expand Down

0 comments on commit 2d69d8c

Please sign in to comment.