chore: clean unused code, imports, and unreachable code

oh_security
Cizz22 2 weeks ago
parent 2ba2c5750a
commit 9322a89822

@ -59,7 +59,7 @@ class AccessControl:
if (action == Allow and is_permitted) and (principal in principals or principal == Everyone): if (action == Allow and is_permitted) and (principal in principals or principal == Everyone):
granted = True granted = True
break 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 granted = False
break break
permits.append(granted) permits.append(granted)

@ -19,7 +19,7 @@ class JWTBearer(HTTPBearer):
raise HTTPException(status_code=401, detail='Invalid authentication scheme.') raise HTTPException(status_code=401, detail='Invalid authentication scheme.')
method = request.method method = request.method
if method == 'OPTIONS': if method == 'OPTIONS':
return return None
path = extract_template(request.url.path, request.path_params) path = extract_template(request.url.path, request.path_params)
endpoint = f'/optimumoh{path}' endpoint = f'/optimumoh{path}'
user_info, message = self.verify_jwt(credentials.credentials, method, endpoint) user_info, message = self.verify_jwt(credentials.credentials, method, endpoint)
@ -39,8 +39,7 @@ class JWTBearer(HTTPBearer):
if hasattr(message, 'role'): if hasattr(message, 'role'):
set_role(message.role) set_role(message.role)
return message 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): def verify_jwt(self, jwtoken: str, method: str, endpoint: str):
try: try:
@ -61,8 +60,7 @@ async def get_token(request: Request):
token = request.headers.get('Authorization') token = request.headers.get('Authorization')
if token: if token:
return token.replace('Bearer ', '') return token.replace('Bearer ', '')
else: return request.cookies.get('access_token')
return request.cookies.get('access_token')
return '' return ''
async def internal_key(request: Request): async def internal_key(request: Request):

@ -25,20 +25,19 @@ async def get_target_reliability(db_session: DbSession, token: Token, collector_
if duration != 17520: if duration != 17520:
if not simulation_id: 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.') raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Simulation ID is required for non-default duration. Please run simulation first.')
else: try:
try: temporal_client = await Client.connect(TEMPORAL_URL)
temporal_client = await Client.connect(TEMPORAL_URL) handle = temporal_client.get_workflow_handle(f'simulation-{simulation_id}')
handle = temporal_client.get_workflow_handle(f'simulation-{simulation_id}') desc = await handle.describe()
desc = await handle.describe() status_name = desc.status.name
status_name = desc.status.name if status_name in ['RUNNING', 'CONTINUED_AS_NEW']:
if status_name in ['RUNNING', 'CONTINUED_AS_NEW']: raise HTTPException(status_code=status.HTTP_425_TOO_EARLY, detail='Simulation is still running.')
raise HTTPException(status_code=status.HTTP_425_TOO_EARLY, detail='Simulation is still running.') if status_name != 'COMPLETED':
elif status_name != 'COMPLETED': raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f'Simulation failed with status: {status_name}')
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f'Simulation failed with status: {status_name}') except HTTPException:
except HTTPException: raise
raise except Exception as e:
except Exception as e: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Simulation not found or error checking status: {str(e)}')
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Simulation not found or error checking status: {str(e)}')
else: else:
simulation_id = TR_RBD_ID simulation_id = TR_RBD_ID
results = await get_simulation_results(simulation_id=simulation_id, token=token) results = await get_simulation_results(simulation_id=simulation_id, token=token)

@ -41,10 +41,9 @@ async def wait_for_workflow(simulation_id, max_retries=3):
if retries > max_retries: if retries > max_retries:
print(f'⚠️ Workflow {workflow_id} not found after {max_retries} retries, treating as done. Error: {e}') print(f'⚠️ Workflow {workflow_id} not found after {max_retries} retries, treating as done. Error: {e}')
break break
else: print(f'⚠️ Workflow {workflow_id} not found (retry {retries}/{max_retries}), waiting 10s before retry...')
print(f'⚠️ Workflow {workflow_id} not found (retry {retries}/{max_retries}), waiting 10s before retry...') await asyncio.sleep(10)
await asyncio.sleep(10) continue
continue
retries = 0 retries = 0
await asyncio.sleep(30) await asyncio.sleep(30)
return simulation_id return simulation_id

@ -22,8 +22,7 @@ class OptimumCostModel:
response = requests.get(url, headers=header) response = requests.get(url, headers=header)
response.raise_for_status() response.raise_for_status()
data = response.json() data = response.json()
reliability = data['data']['value'] return data['data']['value']
return reliability
except requests.RequestException as e: except requests.RequestException as e:
print(f'API Error: {e}') print(f'API Error: {e}')
return None return None

@ -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): 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) 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 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 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
async def get_or_create_scope_equipment_calculation(*, db_session: DbSession, scope_calculation_id, calculation_time_constrains_in: Optional[CalculationTimeConstrainsParametersCreate]): 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) scope_calculation = await get_calculation_data_by_id(db_session=db_session, calculation_id=scope_calculation_id)

@ -80,8 +80,7 @@ class OptimumCostModelWithSpareparts:
self.logger.warning(f'No plot data available for {location_tag}') self.logger.warning(f'No plot data available for {location_tag}')
return None return None
time_series = create_time_series_data(plot_data, self.time_window_months * 24 * 31) 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 analyze_monthly_metrics(time_series, self.last_oh_date)
return monthly_data
async def get_simulation_results(self, simulation_id: str='default'): async def get_simulation_results(self, simulation_id: str='default'):
headers = {'Authorization': f'Bearer {self.token}', 'Content-Type': 'application/json'} 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): 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: if calculation_param_in.ohSessionId is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='overhaul_session_id is required') 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 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
async def get_calculation_result(db_session: DbSession, calculation_id: str, token, include_risk_cost): async def get_calculation_result(db_session: DbSession, calculation_id: str, token, include_risk_cost):
try: 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) current = current.replace(year=current.year + 1, month=1)
else: else:
current = current.replace(month=current.month + 1) current = current.replace(month=current.month + 1)
results = dict(sorted(results.items())) return dict(sorted(results.items()))
return results
async def get_equipment_foh(location_tag: str, token: str): async def get_equipment_foh(location_tag: str, token: str):
url_mdt = f'{REALIBILITY_SERVICE_API}/asset/mdt/{location_tag}' 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() result = response.json()
except (requests.RequestException, ValueError) as e: except (requests.RequestException, ValueError) as e:
raise Exception(f'Failed to fetch or parse mdt data: {e}') raise Exception(f'Failed to fetch or parse mdt data: {e}')
mdt_data = result['data']['hours'] return result['data']['hours']
return mdt_data
def simulate_equipment_overhaul(equipment, preventive_cost, predicted_num_failures, interval_months, forced_outage_hours_value, total_months=24): def simulate_equipment_overhaul(equipment, preventive_cost, predicted_num_failures, interval_months, forced_outage_hours_value, total_months=24):
total_preventive_cost = 0 total_preventive_cost = 0

@ -4,8 +4,7 @@ import requests
from src.config import RBD_SERVICE_API from src.config import RBD_SERVICE_API
def get_months_between(start_date: datetime.datetime, end_date: datetime.datetime) -> int: 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 (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)
return months
def create_time_series_data(chart_data, max_hours=None): def create_time_series_data(chart_data, max_hours=None):
filtered_data = [d for d in chart_data if d['currentEvent'] != 'ON_OH'] filtered_data = [d for d in chart_data if d['currentEvent'] != 'ON_OH']

@ -29,7 +29,7 @@ def system_availability(structure: Structure, availabilities: Dict[str, float])
availability = system_availability(s, availabilities) availability = system_availability(s, availabilities)
product *= Decimal(str(availability)) product *= Decimal(str(availability))
return float(product) return float(product)
elif 'parallel' in structure: if 'parallel' in structure:
components = structure['parallel'] components = structure['parallel']
if not components: if not components:
return 0.0 return 0.0
@ -40,7 +40,7 @@ def system_availability(structure: Structure, availabilities: Dict[str, float])
product *= unavailability product *= unavailability
result = Decimal('1.0') - product result = Decimal('1.0') - product
return float(result) return float(result)
elif 'parallel_no_redundancy' in structure: if 'parallel_no_redundancy' in structure:
components = structure['parallel_no_redundancy'] components = structure['parallel_no_redundancy']
if not components: if not components:
return 0.0 return 0.0
@ -76,8 +76,7 @@ def criticality_importance(structure: Structure, availabilities: Dict[str, float
component_avail = availabilities[component] component_avail = availabilities[component]
if system_avail >= 1.0: if system_avail >= 1.0:
return 0.0 return 0.0
criticality = birnbaum * (1.0 - component_avail) / (1.0 - system_avail) return birnbaum * (1.0 - component_avail) / (1.0 - system_avail)
return criticality
def fussell_vesely_importance(structure: Structure, availabilities: Dict[str, float], component: str) -> float: def fussell_vesely_importance(structure: Structure, availabilities: Dict[str, float], component: str) -> float:
system_avail = system_availability(structure, availabilities) 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 = availabilities.copy()
avail_down[component] = 0.0 avail_down[component] = 0.0
system_down = system_availability(structure, avail_down) system_down = system_availability(structure, avail_down)
fv = (system_avail - system_down) / system_avail return (system_avail - system_down) / system_avail
return fv
def compute_all_importance_measures(structure: Structure, availabilities: Dict[str, float]) -> Dict[str, Dict[str, float]]: def compute_all_importance_measures(structure: Structure, availabilities: Dict[str, float]) -> Dict[str, Dict[str, float]]:
normalized_availabilities = {} normalized_availabilities = {}

@ -78,6 +78,6 @@ def get_class_by_tablename(table_fullname: str) -> Any:
if hasattr(c, '__table__'): if hasattr(c, '__table__'):
if c.__table__.fullname.lower() == name.lower(): if c.__table__.fullname.lower() == name.lower():
return c return c
return None
mapped_name = resolve_table_name(table_fullname) mapped_name = resolve_table_name(table_fullname)
mapped_class = _find_class(mapped_name) return _find_class(mapped_name)
return mapped_class

@ -16,8 +16,7 @@ async def get_all(*, common, location_tag: str, scope: Optional[str]=None):
query = apply_not_deleted_filter(query, EquipmentWorkscopeGroup) query = apply_not_deleted_filter(query, EquipmentWorkscopeGroup)
if scope: if scope:
query = query.join(EquipmentWorkscopeGroup.workscope_group).join(MasterActivity.oh_types).join(WorkscopeOHType.oh_type).filter(MaintenanceType.name == 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 await search_filter_sort_paginate(model=query, **common)
return results
async def create(*, db_session: DbSession, assetnum, scope_job_in: ScopeEquipmentJobCreate): async def create(*, db_session: DbSession, assetnum, scope_job_in: ScopeEquipmentJobCreate):
scope_jobs = [] scope_jobs = []

@ -169,12 +169,11 @@ def _build_error_response(request: Request, exc: Exception, error_id: str) -> JS
if 'unique constraint' in orig_lower: if 'unique constraint' in orig_lower:
_store_log_state(request, 409, error_id, 'Conflict', f'Unique constraint violation: {short}') _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}') 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}') _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}') 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}')
_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}')
return _json_response(422, f'{_FIXED_MESSAGES[422]}. Error ID: {error_id}')
if isinstance(exc, DataError): if isinstance(exc, DataError):
_store_log_state(request, 422, error_id, 'Unprocessable Entity', f'Invalid data format: {short}') _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}') 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: 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}') _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}') 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}') _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}') 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}') _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}') 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}')
_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}')
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}') _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}') return _json_response(500, f'An unexpected error occurred. Error ID: {error_id}')
try: try:
@ -224,23 +222,20 @@ def handle_sqlalchemy_error(error: SQLAlchemyError):
if isinstance(error, IntegrityError): if isinstance(error, IntegrityError):
if 'unique constraint' in str(error).lower(): if 'unique constraint' in str(error).lower():
return ('This record already exists.', 409) 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) return ('Related record not found.', 400)
else: return ('Data integrity error.', 400)
return ('Data integrity error.', 400) if isinstance(error, DataError) or isinstance(original_error, AsyncPGDataError):
elif isinstance(error, DataError) or isinstance(original_error, AsyncPGDataError):
return ('Invalid data provided.', 400) return ('Invalid data provided.', 400)
elif isinstance(error, DBAPIError): if isinstance(error, DBAPIError):
if 'unique constraint' in str(error).lower(): if 'unique constraint' in str(error).lower():
return ('This record already exists.', 409) 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) 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) 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) return ('Invalid data provided.', 400)
else: return ('Database error.', 500)
return ('Database error.', 500) log.error(f'Unexpected database error: {str(error)}')
else: return ('An unexpected database error occurred.', 500)
log.error(f'Unexpected database error: {str(error)}')
return ('An unexpected database error occurred.', 500)

@ -10,8 +10,7 @@ from src.overhaul_scope.model import OverhaulScope
from src.overhaul_scope.service import get_overview_overhaul from src.overhaul_scope.service import get_overview_overhaul
async def get_overhaul_overview(db_session: DbSession): async def get_overhaul_overview(db_session: DbSession):
results = await get_overview_overhaul(db_session=db_session) return await get_overview_overhaul(db_session=db_session)
return results
async def get_simulation_results(*, simulation_id: str, token: str): async def get_simulation_results(*, simulation_id: str, token: str):
headers = {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'} headers = {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'}
@ -48,6 +47,5 @@ def get_overhaul_system_components():
percentages = calculate_contribution(availabilities) percentages = calculate_contribution(availabilities)
for schema, contribution in percentages.items(): for schema, contribution in percentages.items():
powerplant_reliability[schema]['critical_contribution'] = contribution['criticality_importance'] 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 dict(sorted(powerplant_reliability.items(), key=lambda x: x[1]['critical_contribution'], reverse=True))
return sorted_powerplant_reliability
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%'}} 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%'}}

@ -8,9 +8,8 @@ def get_material_cost(scope, total_equipment):
if scope == 'B': if scope == 'B':
result = Decimal(f'{cost}') / Decimal(str(total_equipment)) result = Decimal(f'{cost}') / Decimal(str(total_equipment))
return float(result) return float(result)
else: result = Decimal('8565468127') / Decimal(str(total_equipment))
result = Decimal('8565468127') / Decimal(str(total_equipment)) return float(result)
return float(result)
return float(0) return float(0)
def get_service_cost(scope, total_equipment): def get_service_cost(scope, total_equipment):
@ -20,7 +19,6 @@ def get_service_cost(scope, total_equipment):
if scope == 'B': if scope == 'B':
result = Decimal('36405830225') / Decimal(str(total_equipment)) result = Decimal('36405830225') / Decimal(str(total_equipment))
return float(result) return float(result)
else: result = Decimal('36000000000') / Decimal(str(total_equipment))
result = Decimal('36000000000') / Decimal(str(total_equipment)) return float(result)
return float(result)
return float(0) return float(0)

@ -6,9 +6,7 @@ def get_spreatsheed_service(credentials):
return build('sheets', 'v4', credentials=credentials, cache_discovery=False) return build('sheets', 'v4', credentials=credentials, cache_discovery=False)
def get_google_creds(): def get_google_creds():
creds = None return Credentials.from_service_account_file('credentials.json', scopes=SCOPES)
creds = Credentials.from_service_account_file('credentials.json', scopes=SCOPES)
return creds
def process_spreadsheet_data(rows): def process_spreadsheet_data(rows):
processed_data = [] processed_data = []

@ -15,8 +15,7 @@ async def get_all(*, common, location_tag: str, scope: Optional[str]=None):
query = apply_not_deleted_filter(query, EquipmentWorkscopeGroup) query = apply_not_deleted_filter(query, EquipmentWorkscopeGroup)
if scope: if scope:
query = query.join(EquipmentWorkscopeGroup.workscope_group).join(MasterActivity.oh_types).join(WorkscopeOHType.oh_type).filter(MaintenanceType.name == 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 await search_filter_sort_paginate(model=query, **common)
return results
async def create(*, db_session: DbSession, overhaul_equipment_id, overhaul_job_in: OverhaulJobCreate): async def create(*, db_session: DbSession, overhaul_equipment_id, overhaul_job_in: OverhaulJobCreate):
overhaul_jobs = [] overhaul_jobs = []

@ -9,8 +9,7 @@ from .schema import OverhaulScheduleCreate, OverhaulScheduleUpdate
async def get_all(*, common): async def get_all(*, common):
query = Select(OverhaulSchedule).order_by(OverhaulSchedule.start.desc()) query = Select(OverhaulSchedule).order_by(OverhaulSchedule.start.desc())
query = apply_not_deleted_filter(query, OverhaulSchedule) query = apply_not_deleted_filter(query, OverhaulSchedule)
results = await search_filter_sort_paginate(model=query, **common) return await search_filter_sort_paginate(model=query, **common)
return results
async def create(*, db_session: DbSession, overhaul_job_in: OverhaulScheduleCreate): async def create(*, db_session: DbSession, overhaul_job_in: OverhaulScheduleCreate):
schedule = OverhaulSchedule(**overhaul_job_in.model_dump()) schedule = OverhaulSchedule(**overhaul_job_in.model_dump())

@ -33,8 +33,7 @@ async def get_all(*, common, scope_name: Optional[str]=None):
query = apply_not_deleted_filter(query, OverhaulScope) query = apply_not_deleted_filter(query, OverhaulScope)
if scope_name: if scope_name:
query = query.filter(OverhaulScope.maintenance_type.name == scope_name) query = query.filter(OverhaulScope.maintenance_type.name == scope_name)
results = await search_filter_sort_paginate(model=query, **common) return await search_filter_sort_paginate(model=query, **common)
return results
async def create(*, db_session: DbSession, scope_in: ScopeCreate): async def create(*, db_session: DbSession, scope_in: ScopeCreate):
if isinstance(scope_in.start_date, str): if isinstance(scope_in.start_date, str):

@ -7,9 +7,8 @@ def get_material_cost(scope, total_equipment):
if scope == 'B': if scope == 'B':
result = Decimal('365539731101') / Decimal(str(total_equipment)) result = Decimal('365539731101') / Decimal(str(total_equipment))
return float(result) return float(result)
else: result = Decimal('8565468127') / Decimal(str(total_equipment))
result = Decimal('8565468127') / Decimal(str(total_equipment)) return float(result)
return float(result)
return float(0) return float(0)
def get_service_cost(scope, total_equipment): def get_service_cost(scope, total_equipment):
@ -19,7 +18,6 @@ def get_service_cost(scope, total_equipment):
if scope == 'B': if scope == 'B':
result = Decimal('36405830225') / Decimal(str(total_equipment)) result = Decimal('36405830225') / Decimal(str(total_equipment))
return float(result) return float(result)
else: result = Decimal('36000000000') / Decimal(str(total_equipment))
result = Decimal('36000000000') / Decimal(str(total_equipment)) return float(result)
return float(result)
return float(0) return float(0)

@ -116,19 +116,17 @@ class SparepartManager:
def _calculate_months_until_delivery(self, delivery_date: date, target_month: int) -> int: def _calculate_months_until_delivery(self, delivery_date: date, target_month: int) -> int:
target_date = self.analysis_start_date + timedelta(days=target_month * 30) 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 (delivery_date.year - target_date.year) * 12 + (delivery_date.month - target_date.month)
return months_diff
def _calculate_urgency(self, order_month: int, target_month: int) -> str: def _calculate_urgency(self, order_month: int, target_month: int) -> str:
time_gap = target_month - order_month time_gap = target_month - order_month
if time_gap <= 1: if time_gap <= 1:
return 'URGENT' return 'URGENT'
elif time_gap <= 3: if time_gap <= 3:
return 'HIGH' return 'HIGH'
elif time_gap <= 6: if time_gap <= 6:
return 'MEDIUM' return 'MEDIUM'
else: return 'LOW'
return 'LOW'
def _generate_procurement_recommendations(self, pr_po_summary: Dict, target_month: int) -> List[Dict]: def _generate_procurement_recommendations(self, pr_po_summary: Dict, target_month: int) -> List[Dict]:
recommendations = [] recommendations = []

@ -94,8 +94,7 @@ async def get_all_master_equipment(*, common: CommonParameters, scope_name):
query = apply_not_deleted_filter(query, MasterEquipment) query = apply_not_deleted_filter(query, MasterEquipment)
if equipments_scope: if equipments_scope:
query = query.filter(MasterEquipment.location_tag.not_in(equipments_scope)) query = query.filter(MasterEquipment.location_tag.not_in(equipments_scope))
results = await search_filter_sort_paginate(model=query, **common) return await search_filter_sort_paginate(model=query, **common)
return results
async def get_equipment_level_by_no(*, db_session: DbSession, level: int): async def get_equipment_level_by_no(*, db_session: DbSession, level: int):
query = Select(MasterEquipment).join(MasterEquipment.equipment_tree).where(MasterEquipmentTree.level_no == level) query = Select(MasterEquipment).join(MasterEquipment.equipment_tree).where(MasterEquipmentTree.level_no == level)

@ -15,14 +15,14 @@ def parse_relative_expression(date_str: str) -> Optional[datetime]:
jakarta_tz = pytz.timezone('Asia/Jakarta') jakarta_tz = pytz.timezone('Asia/Jakarta')
today = datetime.now(jakarta_tz) today = datetime.now(jakarta_tz)
if unit == 'H': if unit == 'H':
result_time = today + timedelta(hours=offset) return today + timedelta(hours=offset)
return result_time if unit == 'T':
elif unit == 'T':
return today + timedelta(days=offset) return today + timedelta(days=offset)
elif unit == 'M': if unit == 'M':
return today + relativedelta(months=offset) return today + relativedelta(months=offset)
elif unit == 'Y': if unit == 'Y':
return today + relativedelta(years=offset) return today + relativedelta(years=offset)
return None
def parse_date_string(date_str: str) -> Optional[datetime]: def parse_date_string(date_str: str) -> Optional[datetime]:
relative_result = parse_relative_expression(date_str) 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: for fmt, type_name in date_formats:
try: try:
dt = datetime.strptime(date_str, fmt) dt = datetime.strptime(date_str, fmt)
dt = dt.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.timezone('Asia/Jakarta')) return dt.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.timezone('Asia/Jakarta'))
return dt
except ValueError: except ValueError:
continue 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') 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) response = requests.post(url, data=payload)
if response.status_code == 200: if response.status_code == 200:
return response.text 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): def update_model(model, update_data: dict):
for key, value in update_data.items(): for key, value in update_data.items():

@ -17,8 +17,7 @@ async def get(*, db_session: DbSession, activity_id: str) -> Optional[ActivityMa
async def get_all(common: CommonParameters): async def get_all(common: CommonParameters):
query = Select(MasterActivity) query = Select(MasterActivity)
query = apply_not_deleted_filter(query, MasterActivity) query = apply_not_deleted_filter(query, MasterActivity)
results = await search_filter_sort_paginate(model=query, **common) return await search_filter_sort_paginate(model=query, **common)
return results
async def create(*, db_session: DbSession, activty_in: ActivityMasterCreate): async def create(*, db_session: DbSession, activty_in: ActivityMasterCreate):
activity = MasterActivity(**activty_in.model_dump()) activity = MasterActivity(**activty_in.model_dump())

@ -17,8 +17,7 @@ async def get(*, db_session: DbSession, activity_id: str) -> Optional[ActivityMa
async def get_all(common: CommonParameters): async def get_all(common: CommonParameters):
query = Select(MasterActivity) query = Select(MasterActivity)
query = apply_not_deleted_filter(query, MasterActivity) query = apply_not_deleted_filter(query, MasterActivity)
results = await search_filter_sort_paginate(model=query, **common) return await search_filter_sort_paginate(model=query, **common)
return results
async def create(*, db_session: DbSession, activty_in: ActivityMasterCreate): async def create(*, db_session: DbSession, activty_in: ActivityMasterCreate):
activity = MasterActivity(**activty_in.model_dump()) activity = MasterActivity(**activty_in.model_dump())

Loading…
Cancel
Save