Skip to content

Commit

Permalink
Merge pull request #447 from MTES-MCT/revert-445-revert-444-master
Browse files Browse the repository at this point in the history
Revert "Revert "Release 28/10/2024""
  • Loading branch information
tristan-gueguen authored Oct 28, 2024
2 parents 956b988 + 0004a3e commit cf65e90
Show file tree
Hide file tree
Showing 14 changed files with 712 additions and 9 deletions.
33 changes: 33 additions & 0 deletions app/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,3 +323,36 @@ def load_company_stats():
def temp_command_generate_xm_control(id):
control = ControllerControl.query.get(id)
temp_write_greco_xml(control)


@app.cli.command("sync_brevo", with_appcontext=True)
@click.argument("pipeline_names", nargs=-1)
@click.option(
"--verbose",
is_flag=True,
help="Enable verbose mode for more detailed output",
)
def sync_brevo_command(pipeline_names, verbose):
"""
Command to sync companies between the database and Brevo.
You can specify one or more pipeline names as arguments.
Example usage: flask sync_brevo "Test Dev churn"
"""
from app.services.sync_companies_with_brevo import (
sync_companies_with_brevo,
)
from app.helpers.brevo import BrevoApiClient

if not pipeline_names:
print("Please provide at least one pipeline name.")
return

brevo = BrevoApiClient(app.config["BREVO_API_KEY"])

app.logger.info(
f"Process sync companies with Brevo began for pipelines: {pipeline_names}"
)

sync_companies_with_brevo(brevo, list(pipeline_names), verbose=verbose)

app.logger.info("Process sync companies with Brevo done")
37 changes: 36 additions & 1 deletion app/controllers/mission.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
)
from app.controllers.utils import atomic_transaction
from app.data_access.mission import MissionOutput
from app.domain.mission import get_start_end_time_at_employee_validation
from app.domain.mission import (
get_start_end_time_at_employee_validation,
get_mission_start_and_end_from_activities,
)
from app.domain.notifications import (
warn_if_mission_changes_since_latest_user_action,
)
Expand All @@ -24,6 +27,8 @@
company_admin,
check_actor_can_write_on_mission_for_user,
)
from app.domain.regulations import compute_regulations
from app.domain.user import get_current_employment_in_company
from app.domain.validation import (
validate_mission,
pre_check_validate_mission_by_admin,
Expand All @@ -41,6 +46,7 @@
UnavailableSwitchModeError,
)
from app.helpers.graphene_types import TimeStamp
from app.helpers.submitter_type import SubmitterType
from app.models import Company, User, Activity
from app.models.mission import Mission
from app.models.mission_end import MissionEnd
Expand Down Expand Up @@ -480,8 +486,37 @@ def mutate(cls, _, info, mission_id, user_id):
mission = Mission.query.get(mission_id)
user = User.query.get(user_id)
activities_to_update = mission.activities_for(user)
is_current_user_admin = company_admin(
current_user, mission.company_id
)
should_recompute_regulations = (
not mission.is_holiday()
and is_current_user_admin
and len(activities_to_update) > 0
)

for activity in activities_to_update:
activity.dismiss()

if should_recompute_regulations:
employment = get_current_employment_in_company(
user=user, company=mission.company
)
business = employment.business if employment else None
(
mission_start,
mission_end,
) = get_mission_start_and_end_from_activities(
activities=activities_to_update, user=user
)
compute_regulations(
user=user,
period_start=mission_start,
period_end=mission_end,
submitter_type=SubmitterType.ADMIN,
business=business,
)

return mission


Expand Down
118 changes: 115 additions & 3 deletions app/helpers/brevo.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

from app import app
from app.helpers.errors import MobilicError
from config import BREVO_API_KEY_ENV


class BrevoRequestError(MobilicError):
Expand Down Expand Up @@ -39,11 +38,29 @@ class LinkCompanyContactData:
contact_id: int


@dataclass
class GetDealData:
deal_id: str


@dataclass
class UpdateDealStageData:
deal_id: str
pipeline_id: str
stage_id: str


@dataclass
class GetDealsByPipelineData:
pipeline_id: str
limit: Optional[int] = None


def check_api_key(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if self.api_key is None:
app.logger.warning(f"{BREVO_API_KEY_ENV} not found.")
app.logger.warning("BREVO_API_KEY not found.")
return None
else:
return func(self, *args, **kwargs)
Expand Down Expand Up @@ -130,6 +147,101 @@ def link_company_and_contact(self, data: LinkCompanyContactData):
except ApiException as e:
raise BrevoRequestError(f"Request to Brevo API failed: {e}")

@check_api_key
def get_deal(self, data: GetDealData):
try:
url = f"{self.BASE_URL}crm/deals/{data.deal_id}"
response = self._session.get(url)
response.raise_for_status()
return response.json()
except ApiException as e:
raise BrevoRequestError(f"Request to Brevo API failed: {e}")

@check_api_key
def update_deal_stage(self, data: UpdateDealStageData):
try:
url = f"{self.BASE_URL}crm/deals/{data.deal_id}"
payload = {
"attributes": {
"pipeline": data.pipeline_id,
"deal_stage": data.stage_id,
}
}
response = self._session.patch(url, json=payload)
response.raise_for_status()

if response.status_code == 204:
return {"message": "Deal stage updated successfully"}

return response.json()
except ApiException as e:
raise BrevoRequestError(f"Request to Brevo API failed: {e}")

@check_api_key
def get_deals_by_pipeline(self, data: GetDealsByPipelineData):
try:
url = f"{self.BASE_URL}crm/deals"
params = {
"filters[attributes.pipeline]": data.pipeline_id,
"limit": data.limit,
}
response = self._session.get(url, params=params)
response.raise_for_status()
return response.json()
except ApiException as e:
raise BrevoRequestError(f"Request to Brevo API failed: {e}")

@check_api_key
def get_all_pipelines(self):
try:
url = f"{self.BASE_URL}crm/pipeline/details/all"
response = self._session.get(url)
response.raise_for_status()
return response.json()
except ApiException as e:
raise BrevoRequestError(f"Request to Brevo API failed: {e}")

@check_api_key
def get_pipeline_details(self, pipeline_id: str):
try:
url = f"{self.BASE_URL}crm/pipeline/details/{pipeline_id}"
response = self._session.get(url)
response.raise_for_status()
return response.json()
except ApiException as e:
raise BrevoRequestError(f"Request to Brevo API failed: {e}")

@check_api_key
def get_stage_name(self, pipeline_id: str, stage_id: str):
pipeline_details = self.get_pipeline_details(pipeline_id)

if isinstance(pipeline_details, list):
pipeline = next(
(
item
for item in pipeline_details
if item.get("pipeline") == pipeline_id
),
None,
)
if not pipeline:
app.logger.warning(
f"Pipeline with ID {pipeline_id} not found."
)
return None
else:
pipeline = pipeline_details

stages = pipeline.get("stages", [])
for stage in stages:
if stage["id"] == stage_id:
return stage["name"]

app.logger.warning(
f"Stage with ID {stage_id} not found in pipeline {pipeline_id}."
)
return None

@staticmethod
def remove_plus_sign(phone_number):
if phone_number.startswith("+"):
Expand All @@ -146,4 +258,4 @@ def remove_plus_sign(phone_number):
except (ValueError, TypeError):
raise ValueError("BREVO_COMPANY_SUBSCRIBE_LIST must be an integer")

brevo = BrevoApiClient(app.config[BREVO_API_KEY_ENV])
brevo = BrevoApiClient(app.config["BREVO_API_KEY"])
6 changes: 6 additions & 0 deletions app/models/business.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,17 @@ class TransportType(str, Enum):


class BusinessType(str, Enum):
# TRM
LONG_DISTANCE = "Longue distance"
SHORT_DISTANCE = "Courte distance"
SHIPPING = "Messagerie, Fonds et valeur"
# TRV
FREQUENT = "Lignes régulières"
INFREQUENT = "Occasionnels"
TAXI_GENERAL = "Taxi général"
TAXI_REGULATED = "Taxi conventionné"
VTC = "VTC"
LOTI = "LOTI"


class Business(BaseModel):
Expand Down
3 changes: 1 addition & 2 deletions app/seed/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def clean():
DELETE FROM team_vehicle;
"""
)

Email.query.delete()
CompanyStats.query.delete()
CompanyCertification.query.delete()
CompanyKnownAddress.query.delete()
Expand All @@ -99,7 +99,6 @@ def clean():

RefreshToken.query.delete()
UserReadToken.query.delete()
Email.query.delete()
RegulatoryAlert.query.delete()
RegulationComputation.query.delete()

Expand Down
7 changes: 7 additions & 0 deletions app/seed/scenarios/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
run_scenario_busy_admin,
)
from app.seed.scenarios.certificated_company import run_scenario_certificated
from app.seed.scenarios.run_certificate import scenario_run_certificate
from app.seed.scenarios.temps_de_liaison import (
ADMIN_EMAIL as ADMIN_TEMPS_DE_LIAISON,
EMPLOYEE_EMAIL as EMPLOYEE_TEMPS_DE_LIAISON,
Expand Down Expand Up @@ -127,4 +128,10 @@ def run(self):
[],
run_scenario_controls,
),
SeedScenario(
"Certificate computation",
"Run certificate computation",
[],
scenario_run_certificate,
),
]
7 changes: 7 additions & 0 deletions app/seed/scenarios/run_certificate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from datetime import date

from app.domain.certificate_criteria import compute_company_certifications


def scenario_run_certificate():
compute_company_certifications(date.today())
Loading

0 comments on commit cf65e90

Please sign in to comment.