diff --git a/src/auth/access_control.py b/src/auth/access_control.py index fc2f09a..372770f 100644 --- a/src/auth/access_control.py +++ b/src/auth/access_control.py @@ -59,7 +59,7 @@ class AccessControl: if (action == Allow and is_permitted) and (principal in principals or principal == Everyone): granted = True break - elif (action == Deny and is_permitted) and (principal in principals or principal == Everyone): + if (action == Deny and is_permitted) and (principal in principals or principal == Everyone): granted = False break permits.append(granted) diff --git a/src/auth/service.py b/src/auth/service.py index f7f9f9b..1c219d5 100644 --- a/src/auth/service.py +++ b/src/auth/service.py @@ -19,7 +19,7 @@ class JWTBearer(HTTPBearer): raise HTTPException(status_code=401, detail='Invalid authentication scheme.') method = request.method if method == 'OPTIONS': - return + return None path = extract_template(request.url.path, request.path_params) endpoint = f'/optimumoh{path}' user_info, message = self.verify_jwt(credentials.credentials, method, endpoint) @@ -39,8 +39,7 @@ class JWTBearer(HTTPBearer): if hasattr(message, 'role'): set_role(message.role) return message - else: - raise HTTPException(status_code=401, detail='Invalid authorization code.') + raise HTTPException(status_code=401, detail='Invalid authorization code.') def verify_jwt(self, jwtoken: str, method: str, endpoint: str): try: @@ -61,8 +60,7 @@ async def get_token(request: Request): token = request.headers.get('Authorization') if token: return token.replace('Bearer ', '') - else: - return request.cookies.get('access_token') + return request.cookies.get('access_token') return '' async def internal_key(request: Request): diff --git a/src/calculation_target_reliability/router.py b/src/calculation_target_reliability/router.py index 4f6caea..9643a2b 100644 --- a/src/calculation_target_reliability/router.py +++ b/src/calculation_target_reliability/router.py @@ -25,20 +25,19 @@ async def get_target_reliability(db_session: DbSession, token: Token, collector_ if duration != 17520: if not simulation_id: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Simulation ID is required for non-default duration. Please run simulation first.') - else: - try: - temporal_client = await Client.connect(TEMPORAL_URL) - handle = temporal_client.get_workflow_handle(f'simulation-{simulation_id}') - desc = await handle.describe() - status_name = desc.status.name - if status_name in ['RUNNING', 'CONTINUED_AS_NEW']: - raise HTTPException(status_code=status.HTTP_425_TOO_EARLY, detail='Simulation is still running.') - elif status_name != 'COMPLETED': - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f'Simulation failed with status: {status_name}') - except HTTPException: - raise - except Exception as e: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Simulation not found or error checking status: {str(e)}') + try: + temporal_client = await Client.connect(TEMPORAL_URL) + handle = temporal_client.get_workflow_handle(f'simulation-{simulation_id}') + desc = await handle.describe() + status_name = desc.status.name + if status_name in ['RUNNING', 'CONTINUED_AS_NEW']: + raise HTTPException(status_code=status.HTTP_425_TOO_EARLY, detail='Simulation is still running.') + if status_name != 'COMPLETED': + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f'Simulation failed with status: {status_name}') + except HTTPException: + raise + except Exception as e: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Simulation not found or error checking status: {str(e)}') else: simulation_id = TR_RBD_ID results = await get_simulation_results(simulation_id=simulation_id, token=token) diff --git a/src/calculation_target_reliability/utils.py b/src/calculation_target_reliability/utils.py index cc41cad..93cc152 100644 --- a/src/calculation_target_reliability/utils.py +++ b/src/calculation_target_reliability/utils.py @@ -41,10 +41,9 @@ async def wait_for_workflow(simulation_id, max_retries=3): if retries > max_retries: print(f'⚠️ Workflow {workflow_id} not found after {max_retries} retries, treating as done. Error: {e}') break - else: - print(f'⚠️ Workflow {workflow_id} not found (retry {retries}/{max_retries}), waiting 10s before retry...') - await asyncio.sleep(10) - continue + print(f'⚠️ Workflow {workflow_id} not found (retry {retries}/{max_retries}), waiting 10s before retry...') + await asyncio.sleep(10) + continue retries = 0 await asyncio.sleep(30) return simulation_id diff --git a/src/calculation_time_constrains/class.py b/src/calculation_time_constrains/class.py index da4c32b..01288c8 100644 --- a/src/calculation_time_constrains/class.py +++ b/src/calculation_time_constrains/class.py @@ -22,8 +22,7 @@ class OptimumCostModel: response = requests.get(url, headers=header) response.raise_for_status() data = response.json() - reliability = data['data']['value'] - return reliability + return data['data']['value'] except requests.RequestException as e: print(f'API Error: {e}') return None diff --git a/src/calculation_time_constrains/flows.py b/src/calculation_time_constrains/flows.py index 39a9254..1be1c8f 100644 --- a/src/calculation_time_constrains/flows.py +++ b/src/calculation_time_constrains/flows.py @@ -27,8 +27,7 @@ async def get_create_calculation_parameters(*, db_session: DbSession, calculatio async def create_calculation(*, token: str, db_session: DbSession, collector_db_session: CollectorDbSession, calculation_time_constrains_in: CalculationTimeConstrainsParametersCreate, created_by: str, simulation_id): calculation_data = await create_param_and_data(db_session=db_session, calculation_param_in=calculation_time_constrains_in, created_by=created_by) rbd_simulation_id = simulation_id or TC_RBD_ID - results = await run_simulation_with_spareparts(db_session=db_session, calculation=calculation_data, token=token, collector_db_session=collector_db_session, simulation_id=rbd_simulation_id) - return results + return await run_simulation_with_spareparts(db_session=db_session, calculation=calculation_data, token=token, collector_db_session=collector_db_session, simulation_id=rbd_simulation_id) async def get_or_create_scope_equipment_calculation(*, db_session: DbSession, scope_calculation_id, calculation_time_constrains_in: Optional[CalculationTimeConstrainsParametersCreate]): scope_calculation = await get_calculation_data_by_id(db_session=db_session, calculation_id=scope_calculation_id) diff --git a/src/calculation_time_constrains/service.py b/src/calculation_time_constrains/service.py index 8ccaf5c..594b6bd 100644 --- a/src/calculation_time_constrains/service.py +++ b/src/calculation_time_constrains/service.py @@ -80,8 +80,7 @@ class OptimumCostModelWithSpareparts: self.logger.warning(f'No plot data available for {location_tag}') return None time_series = create_time_series_data(plot_data, self.time_window_months * 24 * 31) - monthly_data = analyze_monthly_metrics(time_series, self.last_oh_date) - return monthly_data + return analyze_monthly_metrics(time_series, self.last_oh_date) async def get_simulation_results(self, simulation_id: str='default'): headers = {'Authorization': f'Bearer {self.token}', 'Content-Type': 'application/json'} @@ -338,8 +337,7 @@ async def run_simulation_with_spareparts(*, db_session, calculation, token: str, async def create_param_and_data(*, db_session: DbSession, calculation_param_in: CalculationTimeConstrainsParametersCreate, created_by: str, parameter_id: Optional[UUID]=None): if calculation_param_in.ohSessionId is None: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='overhaul_session_id is required') - calculationData = await CalculationData.create_with_param(db=db_session, overhaul_session_id=calculation_param_in.ohSessionId, avg_failure_cost=calculation_param_in.costPerFailure, overhaul_cost=calculation_param_in.overhaulCost, created_by=created_by, params_id=parameter_id) - return calculationData + return await CalculationData.create_with_param(db=db_session, overhaul_session_id=calculation_param_in.ohSessionId, avg_failure_cost=calculation_param_in.costPerFailure, overhaul_cost=calculation_param_in.overhaulCost, created_by=created_by, params_id=parameter_id) async def get_calculation_result(db_session: DbSession, calculation_id: str, token, include_risk_cost): try: @@ -495,8 +493,7 @@ async def get_number_of_failures(location_tag, start_date, end_date, token, max_ current = current.replace(year=current.year + 1, month=1) else: current = current.replace(month=current.month + 1) - results = dict(sorted(results.items())) - return results + return dict(sorted(results.items())) async def get_equipment_foh(location_tag: str, token: str): url_mdt = f'{REALIBILITY_SERVICE_API}/asset/mdt/{location_tag}' @@ -506,8 +503,7 @@ async def get_equipment_foh(location_tag: str, token: str): result = response.json() except (requests.RequestException, ValueError) as e: raise Exception(f'Failed to fetch or parse mdt data: {e}') - mdt_data = result['data']['hours'] - return mdt_data + return result['data']['hours'] def simulate_equipment_overhaul(equipment, preventive_cost, predicted_num_failures, interval_months, forced_outage_hours_value, total_months=24): total_preventive_cost = 0 diff --git a/src/calculation_time_constrains/utils.py b/src/calculation_time_constrains/utils.py index a0321f3..b0e40b5 100644 --- a/src/calculation_time_constrains/utils.py +++ b/src/calculation_time_constrains/utils.py @@ -4,8 +4,7 @@ import requests from src.config import RBD_SERVICE_API def get_months_between(start_date: datetime.datetime, end_date: datetime.datetime) -> int: - months = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month) - return months + return (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month) def create_time_series_data(chart_data, max_hours=None): filtered_data = [d for d in chart_data if d['currentEvent'] != 'ON_OH'] diff --git a/src/contribution_util.py b/src/contribution_util.py index b85f465..c91fc36 100644 --- a/src/contribution_util.py +++ b/src/contribution_util.py @@ -29,7 +29,7 @@ def system_availability(structure: Structure, availabilities: Dict[str, float]) availability = system_availability(s, availabilities) product *= Decimal(str(availability)) return float(product) - elif 'parallel' in structure: + if 'parallel' in structure: components = structure['parallel'] if not components: return 0.0 @@ -40,7 +40,7 @@ def system_availability(structure: Structure, availabilities: Dict[str, float]) product *= unavailability result = Decimal('1.0') - product return float(result) - elif 'parallel_no_redundancy' in structure: + if 'parallel_no_redundancy' in structure: components = structure['parallel_no_redundancy'] if not components: return 0.0 @@ -76,8 +76,7 @@ def criticality_importance(structure: Structure, availabilities: Dict[str, float component_avail = availabilities[component] if system_avail >= 1.0: return 0.0 - criticality = birnbaum * (1.0 - component_avail) / (1.0 - system_avail) - return criticality + return birnbaum * (1.0 - component_avail) / (1.0 - system_avail) def fussell_vesely_importance(structure: Structure, availabilities: Dict[str, float], component: str) -> float: system_avail = system_availability(structure, availabilities) @@ -86,8 +85,7 @@ def fussell_vesely_importance(structure: Structure, availabilities: Dict[str, fl avail_down = availabilities.copy() avail_down[component] = 0.0 system_down = system_availability(structure, avail_down) - fv = (system_avail - system_down) / system_avail - return fv + return (system_avail - system_down) / system_avail def compute_all_importance_measures(structure: Structure, availabilities: Dict[str, float]) -> Dict[str, Dict[str, float]]: normalized_availabilities = {} diff --git a/src/database/core.py b/src/database/core.py index 13e09f1..406256c 100644 --- a/src/database/core.py +++ b/src/database/core.py @@ -78,6 +78,6 @@ def get_class_by_tablename(table_fullname: str) -> Any: if hasattr(c, '__table__'): if c.__table__.fullname.lower() == name.lower(): return c + return None mapped_name = resolve_table_name(table_fullname) - mapped_class = _find_class(mapped_name) - return mapped_class + return _find_class(mapped_name) diff --git a/src/equipment_workscope_group/service.py b/src/equipment_workscope_group/service.py index 3eb4eb8..5ea6b91 100644 --- a/src/equipment_workscope_group/service.py +++ b/src/equipment_workscope_group/service.py @@ -16,8 +16,7 @@ async def get_all(*, common, location_tag: str, scope: Optional[str]=None): query = apply_not_deleted_filter(query, EquipmentWorkscopeGroup) if scope: query = query.join(EquipmentWorkscopeGroup.workscope_group).join(MasterActivity.oh_types).join(WorkscopeOHType.oh_type).filter(MaintenanceType.name == scope) - results = await search_filter_sort_paginate(model=query, **common) - return results + return await search_filter_sort_paginate(model=query, **common) async def create(*, db_session: DbSession, assetnum, scope_job_in: ScopeEquipmentJobCreate): scope_jobs = [] diff --git a/src/exceptions.py b/src/exceptions.py index 45ee53d..7c10927 100644 --- a/src/exceptions.py +++ b/src/exceptions.py @@ -169,12 +169,11 @@ def _build_error_response(request: Request, exc: Exception, error_id: str) -> JS if 'unique constraint' in orig_lower: _store_log_state(request, 409, error_id, 'Conflict', f'Unique constraint violation: {short}') return _json_response(409, f'This record already exists. Error ID: {error_id}') - elif 'foreign key constraint' in orig_lower: + if 'foreign key constraint' in orig_lower: _store_log_state(request, 422, error_id, 'Unprocessable Entity', f'Foreign key constraint violation: {short}') return _json_response(422, f'{_FIXED_MESSAGES[422]}. Error ID: {error_id}') - else: - _store_log_state(request, 422, error_id, 'Unprocessable Entity', f'Database integrity error: {short}') - return _json_response(422, f'{_FIXED_MESSAGES[422]}. Error ID: {error_id}') + _store_log_state(request, 422, error_id, 'Unprocessable Entity', f'Database integrity error: {short}') + return _json_response(422, f'{_FIXED_MESSAGES[422]}. Error ID: {error_id}') if isinstance(exc, DataError): _store_log_state(request, 422, error_id, 'Unprocessable Entity', f'Invalid data format: {short}') return _json_response(422, f'{_FIXED_MESSAGES[422]}. Error ID: {error_id}') @@ -183,15 +182,14 @@ def _build_error_response(request: Request, exc: Exception, error_id: str) -> JS if 'invalid input syntax' in orig_lower or 'invalid uuid' in orig_lower or 'invalid input for query argument' in orig_lower: _store_log_state(request, 422, error_id, 'Unprocessable Entity', f'Invalid input format: {short}') return _json_response(422, f'{_FIXED_MESSAGES[422]}. Error ID: {error_id}') - elif 'unique constraint' in orig_lower: + if 'unique constraint' in orig_lower: _store_log_state(request, 409, error_id, 'Conflict', f'Unique constraint violation: {short}') return _json_response(409, f'This record already exists. Error ID: {error_id}') - elif 'foreign key constraint' in orig_lower: + if 'foreign key constraint' in orig_lower: _store_log_state(request, 422, error_id, 'Unprocessable Entity', f'Foreign key constraint violation: {short}') return _json_response(422, f'{_FIXED_MESSAGES[422]}. Error ID: {error_id}') - else: - _store_log_state(request, 500, error_id, 'Internal Server Error', f'Database query error: {short}') - return _json_response(500, f'An unexpected error occurred. Error ID: {error_id}') + _store_log_state(request, 500, error_id, 'Internal Server Error', f'Database query error: {short}') + return _json_response(500, f'An unexpected error occurred. Error ID: {error_id}') _store_log_state(request, 500, error_id, 'Internal Server Error', f'Database error: {short}') return _json_response(500, f'An unexpected error occurred. Error ID: {error_id}') try: @@ -224,23 +222,20 @@ def handle_sqlalchemy_error(error: SQLAlchemyError): if isinstance(error, IntegrityError): if 'unique constraint' in str(error).lower(): return ('This record already exists.', 409) - elif 'foreign key constraint' in str(error).lower(): + if 'foreign key constraint' in str(error).lower(): return ('Related record not found.', 400) - else: - return ('Data integrity error.', 400) - elif isinstance(error, DataError) or isinstance(original_error, AsyncPGDataError): + return ('Data integrity error.', 400) + if isinstance(error, DataError) or isinstance(original_error, AsyncPGDataError): return ('Invalid data provided.', 400) - elif isinstance(error, DBAPIError): + if isinstance(error, DBAPIError): if 'unique constraint' in str(error).lower(): return ('This record already exists.', 409) - elif 'foreign key constraint' in str(error).lower(): + if 'foreign key constraint' in str(error).lower(): return ('Related record not found.', 400) - elif 'null value in column' in str(error).lower(): + if 'null value in column' in str(error).lower(): return ('Required data missing.', 400) - elif 'invalid input for query argument' in str(error).lower(): + if 'invalid input for query argument' in str(error).lower(): return ('Invalid data provided.', 400) - else: - return ('Database error.', 500) - else: - log.error(f'Unexpected database error: {str(error)}') - return ('An unexpected database error occurred.', 500) + return ('Database error.', 500) + log.error(f'Unexpected database error: {str(error)}') + return ('An unexpected database error occurred.', 500) diff --git a/src/overhaul/service.py b/src/overhaul/service.py index 7e3262d..8c21fcd 100644 --- a/src/overhaul/service.py +++ b/src/overhaul/service.py @@ -10,8 +10,7 @@ from src.overhaul_scope.model import OverhaulScope from src.overhaul_scope.service import get_overview_overhaul async def get_overhaul_overview(db_session: DbSession): - results = await get_overview_overhaul(db_session=db_session) - return results + return await get_overview_overhaul(db_session=db_session) async def get_simulation_results(*, simulation_id: str, token: str): headers = {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'} @@ -48,6 +47,5 @@ def get_overhaul_system_components(): percentages = calculate_contribution(availabilities) for schema, contribution in percentages.items(): powerplant_reliability[schema]['critical_contribution'] = contribution['criticality_importance'] - sorted_powerplant_reliability = dict(sorted(powerplant_reliability.items(), key=lambda x: x[1]['critical_contribution'], reverse=True)) - return sorted_powerplant_reliability + return dict(sorted(powerplant_reliability.items(), key=lambda x: x[1]['critical_contribution'], reverse=True)) return {'HPT': {'efficiency': '92%', 'work_hours': '1200', 'reliability': '96%'}, 'IPT': {'efficiency': '91%', 'work_hours': '1100', 'reliability': '95%'}, 'LPT': {'efficiency': '90%', 'work_hours': '1000', 'reliability': '94%'}, 'EG': {'efficiency': '88%', 'work_hours': '950', 'reliability': '93%'}, 'boiler': {'efficiency': '90%', 'work_hours': '1000', 'reliability': '95%'}, 'HPH1': {'efficiency': '89%', 'work_hours': '1050', 'reliability': '94%'}, 'HPH2': {'efficiency': '88%', 'work_hours': '1020', 'reliability': '93%'}, 'HPH3': {'efficiency': '87%', 'work_hours': '1010', 'reliability': '92%'}, 'HPH5': {'efficiency': '86%', 'work_hours': '980', 'reliability': '91%'}, 'HPH6': {'efficiency': '85%', 'work_hours': '970', 'reliability': '90%'}, 'HPH7': {'efficiency': '84%', 'work_hours': '960', 'reliability': '89%'}, 'Condensor': {'efficiency': '83%', 'work_hours': '940', 'reliability': '88%'}, 'Deaerator': {'efficiency': '82%', 'work_hours': '930', 'reliability': '87%'}} diff --git a/src/overhaul_activity/utils.py b/src/overhaul_activity/utils.py index 8a9d4e1..9a2b112 100644 --- a/src/overhaul_activity/utils.py +++ b/src/overhaul_activity/utils.py @@ -8,9 +8,8 @@ def get_material_cost(scope, total_equipment): if scope == 'B': result = Decimal(f'{cost}') / Decimal(str(total_equipment)) return float(result) - else: - result = Decimal('8565468127') / Decimal(str(total_equipment)) - return float(result) + result = Decimal('8565468127') / Decimal(str(total_equipment)) + return float(result) return float(0) def get_service_cost(scope, total_equipment): @@ -20,7 +19,6 @@ def get_service_cost(scope, total_equipment): if scope == 'B': result = Decimal('36405830225') / Decimal(str(total_equipment)) return float(result) - else: - result = Decimal('36000000000') / Decimal(str(total_equipment)) - return float(result) + result = Decimal('36000000000') / Decimal(str(total_equipment)) + return float(result) return float(0) diff --git a/src/overhaul_gantt/utils.py b/src/overhaul_gantt/utils.py index 0d1d9bc..2075559 100644 --- a/src/overhaul_gantt/utils.py +++ b/src/overhaul_gantt/utils.py @@ -6,9 +6,7 @@ def get_spreatsheed_service(credentials): return build('sheets', 'v4', credentials=credentials, cache_discovery=False) def get_google_creds(): - creds = None - creds = Credentials.from_service_account_file('credentials.json', scopes=SCOPES) - return creds + return Credentials.from_service_account_file('credentials.json', scopes=SCOPES) def process_spreadsheet_data(rows): processed_data = [] diff --git a/src/overhaul_job/service.py b/src/overhaul_job/service.py index c6e50a9..58f5814 100644 --- a/src/overhaul_job/service.py +++ b/src/overhaul_job/service.py @@ -15,8 +15,7 @@ async def get_all(*, common, location_tag: str, scope: Optional[str]=None): query = apply_not_deleted_filter(query, EquipmentWorkscopeGroup) if scope: query = query.join(EquipmentWorkscopeGroup.workscope_group).join(MasterActivity.oh_types).join(WorkscopeOHType.oh_type).filter(MaintenanceType.name == scope) - results = await search_filter_sort_paginate(model=query, **common) - return results + return await search_filter_sort_paginate(model=query, **common) async def create(*, db_session: DbSession, overhaul_equipment_id, overhaul_job_in: OverhaulJobCreate): overhaul_jobs = [] diff --git a/src/overhaul_schedule/service.py b/src/overhaul_schedule/service.py index 0c1befb..a410c29 100644 --- a/src/overhaul_schedule/service.py +++ b/src/overhaul_schedule/service.py @@ -9,8 +9,7 @@ from .schema import OverhaulScheduleCreate, OverhaulScheduleUpdate async def get_all(*, common): query = Select(OverhaulSchedule).order_by(OverhaulSchedule.start.desc()) query = apply_not_deleted_filter(query, OverhaulSchedule) - results = await search_filter_sort_paginate(model=query, **common) - return results + return await search_filter_sort_paginate(model=query, **common) async def create(*, db_session: DbSession, overhaul_job_in: OverhaulScheduleCreate): schedule = OverhaulSchedule(**overhaul_job_in.model_dump()) diff --git a/src/overhaul_scope/service.py b/src/overhaul_scope/service.py index 612a6cf..ab4839a 100644 --- a/src/overhaul_scope/service.py +++ b/src/overhaul_scope/service.py @@ -33,8 +33,7 @@ async def get_all(*, common, scope_name: Optional[str]=None): query = apply_not_deleted_filter(query, OverhaulScope) if scope_name: query = query.filter(OverhaulScope.maintenance_type.name == scope_name) - results = await search_filter_sort_paginate(model=query, **common) - return results + return await search_filter_sort_paginate(model=query, **common) async def create(*, db_session: DbSession, scope_in: ScopeCreate): if isinstance(scope_in.start_date, str): diff --git a/src/overhaul_scope/utils.py b/src/overhaul_scope/utils.py index cf31852..ee548f5 100644 --- a/src/overhaul_scope/utils.py +++ b/src/overhaul_scope/utils.py @@ -7,9 +7,8 @@ def get_material_cost(scope, total_equipment): if scope == 'B': result = Decimal('365539731101') / Decimal(str(total_equipment)) return float(result) - else: - result = Decimal('8565468127') / Decimal(str(total_equipment)) - return float(result) + result = Decimal('8565468127') / Decimal(str(total_equipment)) + return float(result) return float(0) def get_service_cost(scope, total_equipment): @@ -19,7 +18,6 @@ def get_service_cost(scope, total_equipment): if scope == 'B': result = Decimal('36405830225') / Decimal(str(total_equipment)) return float(result) - else: - result = Decimal('36000000000') / Decimal(str(total_equipment)) - return float(result) + result = Decimal('36000000000') / Decimal(str(total_equipment)) + return float(result) return float(0) diff --git a/src/sparepart/service.py b/src/sparepart/service.py index ef49091..58a7bf6 100644 --- a/src/sparepart/service.py +++ b/src/sparepart/service.py @@ -116,19 +116,17 @@ class SparepartManager: def _calculate_months_until_delivery(self, delivery_date: date, target_month: int) -> int: target_date = self.analysis_start_date + timedelta(days=target_month * 30) - months_diff = (delivery_date.year - target_date.year) * 12 + (delivery_date.month - target_date.month) - return months_diff + return (delivery_date.year - target_date.year) * 12 + (delivery_date.month - target_date.month) def _calculate_urgency(self, order_month: int, target_month: int) -> str: time_gap = target_month - order_month if time_gap <= 1: return 'URGENT' - elif time_gap <= 3: + if time_gap <= 3: return 'HIGH' - elif time_gap <= 6: + if time_gap <= 6: return 'MEDIUM' - else: - return 'LOW' + return 'LOW' def _generate_procurement_recommendations(self, pr_po_summary: Dict, target_month: int) -> List[Dict]: recommendations = [] diff --git a/src/standard_scope/service.py b/src/standard_scope/service.py index afb903b..0b220d0 100644 --- a/src/standard_scope/service.py +++ b/src/standard_scope/service.py @@ -94,8 +94,7 @@ async def get_all_master_equipment(*, common: CommonParameters, scope_name): query = apply_not_deleted_filter(query, MasterEquipment) if equipments_scope: query = query.filter(MasterEquipment.location_tag.not_in(equipments_scope)) - results = await search_filter_sort_paginate(model=query, **common) - return results + return await search_filter_sort_paginate(model=query, **common) async def get_equipment_level_by_no(*, db_session: DbSession, level: int): query = Select(MasterEquipment).join(MasterEquipment.equipment_tree).where(MasterEquipmentTree.level_no == level) diff --git a/src/utils.py b/src/utils.py index bd6b4ca..4b9f54c 100644 --- a/src/utils.py +++ b/src/utils.py @@ -15,14 +15,14 @@ def parse_relative_expression(date_str: str) -> Optional[datetime]: jakarta_tz = pytz.timezone('Asia/Jakarta') today = datetime.now(jakarta_tz) if unit == 'H': - result_time = today + timedelta(hours=offset) - return result_time - elif unit == 'T': + return today + timedelta(hours=offset) + if unit == 'T': return today + timedelta(days=offset) - elif unit == 'M': + if unit == 'M': return today + relativedelta(months=offset) - elif unit == 'Y': + if unit == 'Y': return today + relativedelta(years=offset) + return None def parse_date_string(date_str: str) -> Optional[datetime]: relative_result = parse_relative_expression(date_str) @@ -32,8 +32,7 @@ def parse_date_string(date_str: str) -> Optional[datetime]: for fmt, type_name in date_formats: try: dt = datetime.strptime(date_str, fmt) - dt = dt.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.timezone('Asia/Jakarta')) - return dt + return dt.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.timezone('Asia/Jakarta')) except ValueError: continue raise ValueError('Invalid date format. Supported formats:\nRelative formats:\n- T (days): T, T-n, T+n\n- M (months): M, M-1, M+2\n- Y (years): Y, Y-1, Y+1\nRegular formats:\n- YYYY-MM-DD\n- YYYY/MM/DD\n- DD-MM-YYYY\n- DD/MM/YYYY\n- YYYY.MM.DD\n- DD.MM.YYYY') @@ -66,8 +65,7 @@ def save_to_pastebin(data, title='Result Log', expire_date='1H'): response = requests.post(url, data=payload) if response.status_code == 200: return response.text - else: - return f'Error: {response.status_code} - {response.text}' + return f'Error: {response.status_code} - {response.text}' def update_model(model, update_data: dict): for key, value in update_data.items(): diff --git a/src/workscope_group/service.py b/src/workscope_group/service.py index af33c90..d5bea22 100644 --- a/src/workscope_group/service.py +++ b/src/workscope_group/service.py @@ -17,8 +17,7 @@ async def get(*, db_session: DbSession, activity_id: str) -> Optional[ActivityMa async def get_all(common: CommonParameters): query = Select(MasterActivity) query = apply_not_deleted_filter(query, MasterActivity) - results = await search_filter_sort_paginate(model=query, **common) - return results + return await search_filter_sort_paginate(model=query, **common) async def create(*, db_session: DbSession, activty_in: ActivityMasterCreate): activity = MasterActivity(**activty_in.model_dump()) diff --git a/src/workscope_group_maintenance_type/service.py b/src/workscope_group_maintenance_type/service.py index af33c90..d5bea22 100644 --- a/src/workscope_group_maintenance_type/service.py +++ b/src/workscope_group_maintenance_type/service.py @@ -17,8 +17,7 @@ async def get(*, db_session: DbSession, activity_id: str) -> Optional[ActivityMa async def get_all(common: CommonParameters): query = Select(MasterActivity) query = apply_not_deleted_filter(query, MasterActivity) - results = await search_filter_sort_paginate(model=query, **common) - return results + return await search_filter_sort_paginate(model=query, **common) async def create(*, db_session: DbSession, activty_in: ActivityMasterCreate): activity = MasterActivity(**activty_in.model_dump())