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):
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)

@ -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,7 +39,6 @@ class JWTBearer(HTTPBearer):
if hasattr(message, 'role'):
set_role(message.role)
return message
else:
raise HTTPException(status_code=401, detail='Invalid authorization code.')
def verify_jwt(self, jwtoken: str, method: str, endpoint: str):
@ -61,7 +60,6 @@ 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 ''

@ -25,7 +25,6 @@ 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}')
@ -33,7 +32,7 @@ async def get_target_reliability(db_session: DbSession, token: Token, collector_
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':
if status_name != 'COMPLETED':
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f'Simulation failed with status: {status_name}')
except HTTPException:
raise

@ -41,7 +41,6 @@ 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

@ -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

@ -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)

@ -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

@ -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']

@ -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 = {}

@ -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)

@ -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 = []

@ -169,10 +169,9 @@ 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}')
if isinstance(exc, DataError):
@ -183,13 +182,12 @@ 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 error: {short}')
@ -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):
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)

@ -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%'}}

@ -8,7 +8,6 @@ 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)
return float(0)
@ -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)
return float(0)

@ -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 = []

@ -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 = []

@ -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())

@ -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):

@ -7,7 +7,6 @@ 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)
return float(0)
@ -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)
return float(0)

@ -116,18 +116,16 @@ 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'
def _generate_procurement_recommendations(self, pr_po_summary: Dict, target_month: int) -> List[Dict]:

@ -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)

@ -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,7 +65,6 @@ 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}'
def update_model(model, update_data: dict):

@ -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())

@ -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())

Loading…
Cancel
Save