From b1c6903c1c144928f437b7f4a5b006fd136231db Mon Sep 17 00:00:00 2001 From: Mike Phares Date: Wed, 4 Dec 2024 11:58:13 -0700 Subject: [PATCH] Tasks 184281, 184799, 184800, 184801 and 184802 Align .editorconfig files Move Controller logic to DMO classes GlobalVars.AppSettings = Models.AppSettings.GetFromConfigurationManager(); Question EditorConfig Project level editorconfig Format White Spaces AppSetting when EnvironmentVariable not set Corrective Actions Tests Schedule Actions Tests DMO Tests Controller Tests Get ready to use VSCode IDE --- Fab2ApprovalMKLink/.editorconfig | 380 ++ Fab2ApprovalMKLink/.vscode/format-report.json | 1 + Fab2ApprovalMKLink/.vscode/launch.json | 33 + Fab2ApprovalMKLink/.vscode/mklink.md | 37 + Fab2ApprovalMKLink/.vscode/settings.json | 424 ++ Fab2ApprovalMKLink/.vscode/tasks.json | 109 + Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj | 51 + Fab2ApprovalMKLink/Program.cs | 77 + Fab2ApprovalSystem/.editorconfig | 380 ++ Fab2ApprovalSystem/.vscode/format-report.json | 1 + Fab2ApprovalSystem/.vscode/launch.json | 30 + Fab2ApprovalSystem/.vscode/settings.json | 424 ++ Fab2ApprovalSystem/.vscode/tasks.json | 20 + Fab2ApprovalSystem/App_Start/.editorconfig | 31 + Fab2ApprovalSystem/App_Start/BundleConfig.cs | 96 +- Fab2ApprovalSystem/App_Start/FilterConfig.cs | 15 +- Fab2ApprovalSystem/App_Start/RouteConfig.cs | 41 +- Fab2ApprovalSystem/App_Start/Startup.Auth.cs | 53 +- Fab2ApprovalSystem/App_Start/WebApiConfig.cs | 24 +- Fab2ApprovalSystem/Controllers/.editorconfig | 31 + .../Controllers/AccountController.cs | 617 ++- .../Controllers/AdminController.cs | 1133 ++-- .../Controllers/AuditController.cs | 901 +--- .../Controllers/ChangeControlController.cs | 2086 +++----- .../Controllers/CorrectiveActionController.cs | 3162 +++++------ .../Controllers/ECNController.cs | 4633 +++++++---------- .../Controllers/HomeController.cs | 1321 ++--- .../Controllers/LotDispositionController.cs | 2502 ++++----- .../Controllers/LotTravelerController.cs | 4280 ++++++--------- .../Controllers/MRBController.cs | 2322 +++------ .../Controllers/ManagerController.cs | 55 +- .../Controllers/PartsRequestController.cs | 1266 ++--- .../Controllers/ReportsController.cs | 333 +- .../Controllers/TrainingController.cs | 1026 ++-- .../Controllers/WebAPIController.cs | 136 +- .../Controllers/WorkflowController.cs | 156 +- Fab2ApprovalSystem/DMO/AccountDMO.cs | 59 + Fab2ApprovalSystem/DMO/AdminDMO.cs | 595 ++- Fab2ApprovalSystem/DMO/ApprovalLogDMO.cs | 39 +- Fab2ApprovalSystem/DMO/AuditDMO.cs | 1254 +++-- Fab2ApprovalSystem/DMO/ChangeControlDMO.cs | 1949 +++---- Fab2ApprovalSystem/DMO/CorrectiveActionDMO.cs | 1615 +++--- Fab2ApprovalSystem/DMO/ECNTypeChangeLogDMO.cs | 45 +- Fab2ApprovalSystem/DMO/ECN_DMO.cs | 1824 +++---- Fab2ApprovalSystem/DMO/EventLogDMO.cs | 58 +- Fab2ApprovalSystem/DMO/LotDispositionDMO.cs | 2391 ++++----- Fab2ApprovalSystem/DMO/LotTravelerDMO.cs | 2842 +++++----- Fab2ApprovalSystem/DMO/MRB_DMO.cs | 2490 +++++---- Fab2ApprovalSystem/DMO/MiscDMO.cs | 1051 ++-- Fab2ApprovalSystem/DMO/PartsRequestDMO.cs | 246 +- Fab2ApprovalSystem/DMO/SAM_DMO.cs | 29 +- Fab2ApprovalSystem/DMO/TrainingDMO.cs | 963 ++-- Fab2ApprovalSystem/DMO/UserAccountDMO.cs | 335 +- Fab2ApprovalSystem/DMO/WorkflowDMO.cs | 1626 +++--- Fab2ApprovalSystem/Fab2ApprovalSystem.csproj | 1612 +++--- Fab2ApprovalSystem/Global.asax.cs | 245 +- .../OOOTrainingReportJobSchedule.cs | 45 +- .../Jobs/OOOTrainingReportJob.cs | 100 +- Fab2ApprovalSystem/Misc/Demohelper.cs | 59 +- Fab2ApprovalSystem/Misc/Documentum.cs | 169 +- Fab2ApprovalSystem/Misc/EmailNotification.cs | 1063 ++-- Fab2ApprovalSystem/Misc/ExcelData.cs | 94 +- Fab2ApprovalSystem/Misc/FTPWrapper.cs | 89 +- Fab2ApprovalSystem/Misc/Functions.cs | 426 +- Fab2ApprovalSystem/Misc/GlobalVars.cs | 199 +- Fab2ApprovalSystem/Misc/LotNoTemplate.cs | 15 +- .../Misc/SessionExpireFilterAttribute.cs | 23 +- Fab2ApprovalSystem/Misc/UserProfileDTO.cs | 27 +- Fab2ApprovalSystem/Misc/Zipper.cs | 152 +- Fab2ApprovalSystem/Misc/ftplib.cs | 2000 ++++--- .../Models/AccountViewModels.cs | 142 +- Fab2ApprovalSystem/Models/AdminModels.cs | 101 +- Fab2ApprovalSystem/Models/AllUserModel.cs | 25 +- Fab2ApprovalSystem/Models/AppSettings.cs | 189 + Fab2ApprovalSystem/Models/ApprovalLog.cs | 25 +- .../Models/ApprovalLogHistory.cs | 29 +- Fab2ApprovalSystem/Models/ApproveListModel.cs | 34 +- Fab2ApprovalSystem/Models/AuditModels.cs | 21 + Fab2ApprovalSystem/Models/AuthAttempt.cs | 16 +- Fab2ApprovalSystem/Models/AuthTokens.cs | 14 +- .../Models/ChangeControlModel.cs | 631 +-- Fab2ApprovalSystem/Models/Common.cs | 356 +- Fab2ApprovalSystem/Models/ECNModel.cs | 405 +- Fab2ApprovalSystem/Models/ECNTypeChangeLog.cs | 19 +- Fab2ApprovalSystem/Models/EightDModel.cs | 812 ++- .../Models/FabApproval.Context.cs | 4 + Fab2ApprovalSystem/Models/IdentityModels.cs | 20 +- Fab2ApprovalSystem/Models/LoginResult.cs | 14 +- .../Models/LotDispositionModels.cs | 415 +- .../Models/LotTravellerModel.cs | 740 ++- Fab2ApprovalSystem/Models/MRBModels.cs | 325 +- .../Models/PartsRequestModels.cs | 132 +- Fab2ApprovalSystem/Models/ProductViewModel.cs | 100 +- Fab2ApprovalSystem/Models/TestModels.cs | 17 +- Fab2ApprovalSystem/Models/Training.cs | 1 - .../Models/TrainingDB.Context.cs | 4 + Fab2ApprovalSystem/Models/UserSubRoles.cs | 21 +- Fab2ApprovalSystem/Models/WinEventLogModel.cs | 27 +- Fab2ApprovalSystem/Models/WorkFlowModels.cs | 70 +- .../PdfGenerator/BinaryContentResult.cs | 23 +- Fab2ApprovalSystem/PdfGenerator/FakeView.cs | 15 +- .../PdfGenerator/HtmlViewRenderer.cs | 24 +- .../PdfGenerator/PdfViewController.cs | 40 +- .../PdfGenerator/PrintHeaderFooter.cs | 29 +- .../PdfGenerator/StandardPdfRenderer.cs | 65 +- Fab2ApprovalSystem/Startup.cs | 1 + .../Utilities/EmailUtilities.cs | 57 +- Fab2ApprovalSystem/Utilities/FileUtilities.cs | 56 +- Fab2ApprovalSystem/Utilities/UserUtilities.cs | 67 +- .../ViewModels/ApproversListViewModel.cs | 30 +- .../ViewModels/ChangeControlViewModel.cs | 100 +- .../ViewModels/CloseToQDBOptionViewModel.cs | 21 +- .../ViewModels/ECNTrainingAssignment.cs | 11 +- .../ViewModels/ECNTrainingAssignments.cs | 27 +- .../IssueWithExistingLotsViewModel.cs | 17 +- Fab2ApprovalSystem/ViewModels/LTMaterial.cs | 41 +- .../LotDispositionLotSummaryViewModel.cs | 40 +- .../ViewModels/LotDispositionViewModel.cs | 61 +- .../ViewModels/LotStatusOptionViewModel.cs | 21 +- Fab2ApprovalSystem/ViewModels/OOOViewModel.cs | 28 +- .../ViewModels/OpenActionItemViewModel.cs | 31 +- Fab2ApprovalSystem/ViewModels/PdfViewModel.cs | 383 +- .../ViewModels/ReportsViewModels.cs | 52 +- Fab2ApprovalTests/.editorconfig | 379 ++ Fab2ApprovalTests/.vscode/format-report.json | 1 + Fab2ApprovalTests/.vscode/launch.json | 30 + Fab2ApprovalTests/.vscode/mklink.md | 6 + Fab2ApprovalTests/.vscode/settings.json | 424 ++ Fab2ApprovalTests/.vscode/tasks.json | 135 + .../Controller/HomeControllerTests.cs | 96 + Fab2ApprovalTests/DMO/AccountDMOTests.cs | 63 + Fab2ApprovalTests/DMO/AdminDMOTests.cs | 93 + Fab2ApprovalTests/DMO/AuditDMOTests.cs | 100 + .../DMO/ChangeControlDMOTests.cs | 79 + .../DMO/CorrectiveActionDMOTests.cs | 123 + .../DMO/EngChangeNoticeDMOTests.cs | 103 + .../DMO/LotDispositionDMOTests.cs | 119 + Fab2ApprovalTests/DMO/LotTravelerDMOTests.cs | 105 + .../DMO/MatReviewBoardDMOTests.cs | 77 + Fab2ApprovalTests/DMO/MiscDMOTests.cs | 76 + Fab2ApprovalTests/DMO/PartsRequestDMOTests.cs | 86 + Fab2ApprovalTests/DMO/TrainingDMOTests.cs | 108 + Fab2ApprovalTests/DMO/UserAccountDMOTests.cs | 79 + Fab2ApprovalTests/DMO/WorkflowDMOTests.cs | 86 + Fab2ApprovalTests/Fab2ApprovalTests.csproj | 50 + .../General/CorrectiveActionTests.cs | 129 + Fab2ApprovalTests/General/ScheduleTests.cs | 90 + Fab2ApprovalTests/Usings.cs | 1 + .../Utilities/EmailUtilitiesTests.cs | 49 + .../Utilities/UserUtilitiesTests.cs | 50 + 150 files changed, 29146 insertions(+), 33456 deletions(-) create mode 100644 Fab2ApprovalMKLink/.editorconfig create mode 100644 Fab2ApprovalMKLink/.vscode/format-report.json create mode 100644 Fab2ApprovalMKLink/.vscode/launch.json create mode 100644 Fab2ApprovalMKLink/.vscode/mklink.md create mode 100644 Fab2ApprovalMKLink/.vscode/settings.json create mode 100644 Fab2ApprovalMKLink/.vscode/tasks.json create mode 100644 Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj create mode 100644 Fab2ApprovalMKLink/Program.cs create mode 100644 Fab2ApprovalSystem/.editorconfig create mode 100644 Fab2ApprovalSystem/.vscode/format-report.json create mode 100644 Fab2ApprovalSystem/.vscode/launch.json create mode 100644 Fab2ApprovalSystem/.vscode/settings.json create mode 100644 Fab2ApprovalSystem/.vscode/tasks.json create mode 100644 Fab2ApprovalSystem/App_Start/.editorconfig create mode 100644 Fab2ApprovalSystem/Controllers/.editorconfig create mode 100644 Fab2ApprovalSystem/DMO/AccountDMO.cs create mode 100644 Fab2ApprovalSystem/Models/AppSettings.cs create mode 100644 Fab2ApprovalSystem/Models/AuditModels.cs create mode 100644 Fab2ApprovalTests/.editorconfig create mode 100644 Fab2ApprovalTests/.vscode/format-report.json create mode 100644 Fab2ApprovalTests/.vscode/launch.json create mode 100644 Fab2ApprovalTests/.vscode/mklink.md create mode 100644 Fab2ApprovalTests/.vscode/settings.json create mode 100644 Fab2ApprovalTests/.vscode/tasks.json create mode 100644 Fab2ApprovalTests/Controller/HomeControllerTests.cs create mode 100644 Fab2ApprovalTests/DMO/AccountDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/AdminDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/AuditDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/ChangeControlDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/CorrectiveActionDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/EngChangeNoticeDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/LotDispositionDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/LotTravelerDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/MatReviewBoardDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/MiscDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/PartsRequestDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/TrainingDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/UserAccountDMOTests.cs create mode 100644 Fab2ApprovalTests/DMO/WorkflowDMOTests.cs create mode 100644 Fab2ApprovalTests/Fab2ApprovalTests.csproj create mode 100644 Fab2ApprovalTests/General/CorrectiveActionTests.cs create mode 100644 Fab2ApprovalTests/General/ScheduleTests.cs create mode 100644 Fab2ApprovalTests/Usings.cs create mode 100644 Fab2ApprovalTests/Utilities/EmailUtilitiesTests.cs create mode 100644 Fab2ApprovalTests/Utilities/UserUtilitiesTests.cs diff --git a/Fab2ApprovalMKLink/.editorconfig b/Fab2ApprovalMKLink/.editorconfig new file mode 100644 index 0000000..5c4845c --- /dev/null +++ b/Fab2ApprovalMKLink/.editorconfig @@ -0,0 +1,380 @@ +[*.md] +end_of_line = crlf +file_header_template = unset +indent_size = 2 +indent_style = space +insert_final_newline = false +root = true +tab_width = 2 +[*.csproj] +end_of_line = crlf +file_header_template = unset +indent_size = 2 +indent_style = space +insert_final_newline = false +root = true +tab_width = 2 +[*.cs] +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true +csharp_new_line_before_catch = false +csharp_new_line_before_else = false +csharp_new_line_before_finally = false +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = none +csharp_new_line_between_query_expression_clauses = true +csharp_prefer_braces = false +csharp_prefer_qualified_reference = true:error +csharp_prefer_simple_default_expression = true:warning +csharp_prefer_simple_using_statement = true:warning +csharp_prefer_static_local_function = true:warning +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = false +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true +csharp_style_allow_embedded_statements_on_same_line_experimental = true +csharp_style_conditional_delegate_call = true +csharp_style_deconstructed_variable_declaration = false +csharp_style_expression_bodied_accessors = when_on_single_line:warning +csharp_style_expression_bodied_constructors = when_on_single_line:warning +csharp_style_expression_bodied_indexers = when_on_single_line:warning +csharp_style_expression_bodied_lambdas = when_on_single_line:warning +csharp_style_expression_bodied_local_functions = when_on_single_line:warning +csharp_style_expression_bodied_methods = when_on_single_line:warning +csharp_style_expression_bodied_operators = when_on_single_line:warning +csharp_style_expression_bodied_properties = when_on_single_line:warning +csharp_style_implicit_object_creation_when_type_is_apparent = true:warning +csharp_style_inlined_variable_declaration = false +csharp_style_namespace_declarations = file_scoped:warning +csharp_style_pattern_local_over_anonymous_function = true:warning +csharp_style_pattern_matching_over_as_with_null_check = true:warning +csharp_style_pattern_matching_over_is_with_cast_check = true:warning +csharp_style_prefer_index_operator = true:warning +csharp_style_prefer_not_pattern = true:warning +csharp_style_prefer_null_check_over_type_check = true +csharp_style_prefer_pattern_matching = true:warning +csharp_style_prefer_range_operator = true:warning +csharp_style_prefer_switch_expression = true:warning +csharp_style_throw_expression = true +csharp_style_unused_value_assignment_preference = discard_variable:warning +csharp_style_unused_value_expression_statement_preference = discard_variable:warning +csharp_style_var_elsewhere = false:warning +csharp_style_var_for_built_in_types = false:warning +csharp_style_var_when_type_is_apparent = false:warning +csharp_using_directive_placement = outside_namespace +dotnet_analyzer_diagnostic.category-Design.severity = error +dotnet_analyzer_diagnostic.category-Documentation.severity = error +dotnet_analyzer_diagnostic.category-Globalization.severity = none +dotnet_analyzer_diagnostic.category-Interoperability.severity = error +dotnet_analyzer_diagnostic.category-Maintainability.severity = error +dotnet_analyzer_diagnostic.category-Naming.severity = none +dotnet_analyzer_diagnostic.category-Performance.severity = none +dotnet_analyzer_diagnostic.category-Reliability.severity = error +dotnet_analyzer_diagnostic.category-Security.severity = error +dotnet_analyzer_diagnostic.category-SingleFile.severity = error +dotnet_analyzer_diagnostic.category-Style.severity = error +dotnet_analyzer_diagnostic.category-Usage.severity = error +dotnet_code_quality_unused_parameters = all +dotnet_code_quality_unused_parameters = non_public +dotnet_code_quality.CAXXXX.api_surface = private, internal +dotnet_diagnostic.CA1001.severity = error # CA1001: Types that own disposable fields should be disposable +dotnet_diagnostic.CA1051.severity = error # CA1051: Do not declare visible instance fields +dotnet_diagnostic.CA1511.severity = warning # CA1511: Use 'ArgumentException.ThrowIfNullOrEmpty' instead of explicitly throwing a new exception instance +dotnet_diagnostic.CA1513.severity = warning # Use 'ObjectDisposedException.ThrowIf' instead of explicitly throwing a new exception instance +dotnet_diagnostic.CA1825.severity = warning # CA1825: Avoid zero-length array allocations +dotnet_diagnostic.CA1829.severity = error # CA1829: Use Length/Count property instead of Count() when available +dotnet_diagnostic.CA1834.severity = warning # CA1834: Consider using 'StringBuilder.Append(char)' when applicable +dotnet_diagnostic.CA1860.severity = error # CA1860: Prefer comparing 'Count' to 0 rather than using 'Any()', both for clarity and for performance +dotnet_diagnostic.CA1862.severity = warning # CA1862: Prefer using 'string.Equals(string, StringComparison)' to perform a case-insensitive comparison, but keep in mind that this might cause subtle changes in behavior, so make sure to conduct thorough testing after applying the suggestion, or if culturally sensitive comparison is not required, consider using 'StringComparison.OrdinalIgnoreCase' +dotnet_diagnostic.CA1869.severity = none # CA1869: Avoid creating a new 'JsonSerializerOptions' instance for every serialization operation. Cache and reuse instances instead. +dotnet_diagnostic.CA2201.severity = none # CA2201: Exception type System.NullReferenceException is reserved by the runtime +dotnet_diagnostic.CA2254.severity = none # CA2254: The logging message template should not vary between calls to 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])' +dotnet_diagnostic.IDE0001.severity = warning # IDE0001: Simplify name +dotnet_diagnostic.IDE0002.severity = warning # Simplify (member access) - System.Version.Equals("1", "2"); Version.Equals("1", "2"); +dotnet_diagnostic.IDE0004.severity = warning # IDE0004: Cast is redundant. +dotnet_diagnostic.IDE0005.severity = error # Using directive is unnecessary +dotnet_diagnostic.IDE0010.severity = none # Add missing cases to switch statement (IDE0010) +dotnet_diagnostic.IDE0028.severity = error # IDE0028: Collection initialization can be simplified +dotnet_diagnostic.IDE0031.severity = warning # Use null propagation (IDE0031) +dotnet_diagnostic.IDE0047.severity = warning # IDE0047: Parentheses can be removed +dotnet_diagnostic.IDE0048.severity = none # Parentheses preferences (IDE0047 and IDE0048) +dotnet_diagnostic.IDE0049.severity = warning # Use language keywords instead of framework type names for type references (IDE0049) +dotnet_diagnostic.IDE0051.severity = error # Private member '' is unused [, ] +dotnet_diagnostic.IDE0058.severity = error # IDE0058: Expression value is never used +dotnet_diagnostic.IDE0060.severity = error # IDE0060: Remove unused parameter +dotnet_diagnostic.IDE0074.severity = warning # IDE0074: Use compound assignment +dotnet_diagnostic.IDE0130.severity = none # Namespace does not match folder structure (IDE0130) +dotnet_diagnostic.IDE0270.severity = warning # IDE0270: Null check can be simplified +dotnet_diagnostic.IDE0290.severity = none # Use primary constructor [Distance]csharp(IDE0290) +dotnet_diagnostic.IDE0300.severity = error # IDE0300: Collection initialization can be simplified +dotnet_diagnostic.IDE0301.severity = error #IDE0301: Collection initialization can be simplified +dotnet_diagnostic.IDE0305.severity = none # IDE0305: Collection initialization can be simplified +dotnet_diagnostic.IDE2000.severity = error # IDE2000: Allow multiple blank lines +dotnet_naming_rule.abstract_method_should_be_pascal_case.severity = warning +dotnet_naming_rule.abstract_method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.abstract_method_should_be_pascal_case.symbols = abstract_method +dotnet_naming_rule.class_should_be_pascal_case.severity = warning +dotnet_naming_rule.class_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.class_should_be_pascal_case.symbols = class +dotnet_naming_rule.delegate_should_be_pascal_case.severity = warning +dotnet_naming_rule.delegate_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.delegate_should_be_pascal_case.symbols = delegate +dotnet_naming_rule.enum_should_be_pascal_case.severity = warning +dotnet_naming_rule.enum_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.enum_should_be_pascal_case.symbols = enum +dotnet_naming_rule.event_should_be_pascal_case.severity = warning +dotnet_naming_rule.event_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.event_should_be_pascal_case.symbols = event +dotnet_naming_rule.interface_should_be_begins_with_i.severity = warning +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.method_should_be_pascal_case.severity = warning +dotnet_naming_rule.method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.method_should_be_pascal_case.symbols = method +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = warning +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.private_method_should_be_pascal_case.severity = warning +dotnet_naming_rule.private_method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.private_method_should_be_pascal_case.symbols = private_method +dotnet_naming_rule.private_or_internal_field_should_be_private_of_internal_field.severity = warning +dotnet_naming_rule.private_or_internal_field_should_be_private_of_internal_field.style = private_of_internal_field +dotnet_naming_rule.private_or_internal_field_should_be_private_of_internal_field.symbols = private_or_internal_field +dotnet_naming_rule.private_or_internal_static_field_should_be_private_of_internal_field.severity = warning +dotnet_naming_rule.private_or_internal_static_field_should_be_private_of_internal_field.style = private_of_internal_field +dotnet_naming_rule.private_or_internal_static_field_should_be_private_of_internal_field.symbols = private_or_internal_static_field +dotnet_naming_rule.property_should_be_pascal_case.severity = warning +dotnet_naming_rule.property_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.property_should_be_pascal_case.symbols = property +dotnet_naming_rule.public_or_protected_field_should_be_private_of_internal_field.severity = warning +dotnet_naming_rule.public_or_protected_field_should_be_private_of_internal_field.style = private_of_internal_field +dotnet_naming_rule.public_or_protected_field_should_be_private_of_internal_field.symbols = public_or_protected_field +dotnet_naming_rule.static_field_should_be_pascal_case.severity = warning +dotnet_naming_rule.static_field_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.static_field_should_be_pascal_case.symbols = static_field +dotnet_naming_rule.static_method_should_be_pascal_case.severity = warning +dotnet_naming_rule.static_method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.static_method_should_be_pascal_case.symbols = static_method +dotnet_naming_rule.struct_should_be_pascal_case.severity = warning +dotnet_naming_rule.struct_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.struct_should_be_pascal_case.symbols = struct +dotnet_naming_rule.types_should_be_pascal_case.severity = warning +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_style.begins_with_i.capitalization = pascal_case +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.private_of_internal_field.capitalization = pascal_case +dotnet_naming_style.private_of_internal_field.required_prefix = _ +dotnet_naming_style.private_of_internal_field.required_suffix = +dotnet_naming_style.private_of_internal_field.word_separator = +dotnet_naming_symbols.abstract_method.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.abstract_method.applicable_kinds = method +dotnet_naming_symbols.abstract_method.required_modifiers = abstract +dotnet_naming_symbols.class.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.class.applicable_kinds = class +dotnet_naming_symbols.class.required_modifiers = +dotnet_naming_symbols.delegate.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.delegate.applicable_kinds = delegate +dotnet_naming_symbols.delegate.required_modifiers = +dotnet_naming_symbols.enum.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.enum.applicable_kinds = enum +dotnet_naming_symbols.enum.required_modifiers = +dotnet_naming_symbols.event.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.event.applicable_kinds = event +dotnet_naming_symbols.event.required_modifiers = +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.required_modifiers = +dotnet_naming_symbols.method.applicable_accessibilities = public +dotnet_naming_symbols.method.applicable_kinds = method +dotnet_naming_symbols.method.required_modifiers = +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.required_modifiers = +dotnet_naming_symbols.private_method.applicable_accessibilities = private +dotnet_naming_symbols.private_method.applicable_kinds = method +dotnet_naming_symbols.private_method.required_modifiers = +dotnet_naming_symbols.private_or_internal_field.applicable_accessibilities = internal, private, private_protected +dotnet_naming_symbols.private_or_internal_field.applicable_kinds = field +dotnet_naming_symbols.private_or_internal_field.required_modifiers = +dotnet_naming_symbols.private_or_internal_static_field.applicable_accessibilities = internal, private, private_protected +dotnet_naming_symbols.private_or_internal_static_field.applicable_kinds = field +dotnet_naming_symbols.private_or_internal_static_field.required_modifiers = static +dotnet_naming_symbols.property.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.property.applicable_kinds = property +dotnet_naming_symbols.property.required_modifiers = +dotnet_naming_symbols.public_or_protected_field.applicable_accessibilities = public, protected +dotnet_naming_symbols.public_or_protected_field.applicable_kinds = field +dotnet_naming_symbols.public_or_protected_field.required_modifiers = +dotnet_naming_symbols.static_field.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.static_field.applicable_kinds = field +dotnet_naming_symbols.static_field.required_modifiers = static +dotnet_naming_symbols.static_method.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.static_method.applicable_kinds = method +dotnet_naming_symbols.static_method.required_modifiers = static +dotnet_naming_symbols.struct.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.struct.applicable_kinds = struct +dotnet_naming_symbols.struct.required_modifiers = +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.required_modifiers = +dotnet_remove_unnecessary_suppression_exclusions = 0 +dotnet_separate_import_directive_groups = true +dotnet_sort_system_directives_first = true +dotnet_style_allow_multiple_blank_lines_experimental = false:warning +dotnet_style_allow_statement_immediately_after_block_experimental = true +dotnet_style_coalesce_expression = true +dotnet_style_collection_initializer = true:warning +dotnet_style_explicit_tuple_names = true:warning +dotnet_style_namespace_match_folder = true +dotnet_style_null_propagation = true:warning +dotnet_style_object_initializer = true:warning +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_operators = never_if_unnecessary +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity +dotnet_style_predefined_type_for_locals_parameters_members = true +dotnet_style_predefined_type_for_member_access = true:warning +dotnet_style_prefer_auto_properties = true:warning +dotnet_style_prefer_compound_assignment = true:warning +dotnet_style_prefer_conditional_expression_over_assignment = false +dotnet_style_prefer_conditional_expression_over_return = false +dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning +dotnet_style_prefer_inferred_tuple_names = true:warning +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning +dotnet_style_prefer_simplified_boolean_expressions = true:warning +dotnet_style_prefer_simplified_interpolation = true +dotnet_style_qualification_for_event = false:error +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_method = false:error +dotnet_style_qualification_for_property = false:error +dotnet_style_readonly_field = true:warning +dotnet_style_require_accessibility_modifiers = for_non_interface_members +end_of_line = crlf +file_header_template = unset +indent_size = 4 +indent_style = space +insert_final_newline = false +root = true +tab_width = 4 +# https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1822 +# https://github.com/dotnet/aspnetcore/blob/main/.editorconfig +# https://github.com/dotnet/project-system/blob/main/.editorconfig + +# Question +csharp_prefer_simple_using_statement = false # Question +csharp_style_expression_bodied_constructors = when_on_single_line:none # Question +csharp_style_expression_bodied_properties = true # Question +csharp_style_implicit_object_creation_when_type_is_apparent = true:warning # Question +csharp_style_pattern_matching_over_as_with_null_check = false # Question +csharp_style_prefer_pattern_matching = false # Question +csharp_style_prefer_range_operator = false # Question +csharp_style_prefer_switch_expression = false # Question +csharp_style_unused_value_assignment_preference = unused_local_variable # Question +csharp_style_unused_value_expression_statement_preference = false # Question +csharp_style_var_elsewhere = false:none # Question +csharp_style_var_for_built_in_types = false:none # Question +csharp_style_var_when_type_is_apparent = false:warning # Question +dotnet_diagnostic.CA1001.severity = none # Question - Types that own disposable fields should be disposable +dotnet_diagnostic.CA1051.severity = none # Question - Do not declare visible instance fields +dotnet_diagnostic.CA1416.severity = none # Question - This call site is reachable on all platforms. +dotnet_diagnostic.CA1510.severity = none # Question - Use +dotnet_diagnostic.CA1834.severity = none # CA1834: Consider using 'StringBuilder.Append(char)' when applicable +dotnet_diagnostic.CA1860.severity = none # Question - Avoid using +dotnet_diagnostic.CA1862.severity = none # Question - Prefer using +dotnet_diagnostic.CA2208.severity = none # Question - Instantiate argument exceptions correctly +dotnet_diagnostic.CA2211.severity = none # Question - Non-constant fields should not be visible +dotnet_diagnostic.CA2249.severity = none # Question - Use +dotnet_diagnostic.CA2253.severity = none # Question - Named placeholders should not be numeric values +dotnet_diagnostic.CS0103.severity = none # Question - The name +dotnet_diagnostic.CS0168.severity = none # Question - The variable +dotnet_diagnostic.CS0219.severity = none # Question - The variable +dotnet_diagnostic.CS0612.severity = none # Question - is obsolete +dotnet_diagnostic.CS0618.severity = none # Question - Compiler Warning (level 2) +dotnet_diagnostic.CS0659.severity = none # Question - Compiler Warning (level 3) +dotnet_diagnostic.CS8019.severity = warning # Question - Unnecessary using directive. +dotnet_diagnostic.CS8600.severity = none # Question - Converting null literal or possible null value to non-nullable type +dotnet_diagnostic.CS8602.severity = none # Question - Dereference of a possibly null reference. +dotnet_diagnostic.CS8603.severity = none # Question - Possible null reference return +dotnet_diagnostic.CS8604.severity = none # Question - Possible null reference argument for parameter. +dotnet_diagnostic.CS8618.severity = none # Question - Non-nullable variable must contain a non-null value when exiting constructor +dotnet_diagnostic.CS8625.severity = none # Question - Cannot convert null literal to non-nullable reference type. +dotnet_diagnostic.CS8629.severity = none # Question - Nullable value type may be null +dotnet_diagnostic.CS8765.severity = none # Question - Nullability of type of parameter +dotnet_diagnostic.IDE0005.severity = none # Question - Remove unnecessary using directives +dotnet_diagnostic.IDE0008.severity = warning # Question - Use explicit type instead of +dotnet_diagnostic.IDE0017.severity = none # Question - Object initialization can be simplified +dotnet_diagnostic.IDE0019.severity = none # Question - Use pattern matching +dotnet_diagnostic.IDE0021.severity = none # Question - Use expression body for constructor +dotnet_diagnostic.IDE0022.severity = none # Question - Use expression body for method +dotnet_diagnostic.IDE0025.severity = none # Question - Use expression body for property +dotnet_diagnostic.IDE0027.severity = none # Question - Use expression body for accessor +dotnet_diagnostic.IDE0028.severity = none # Question - Use collection initializers or expressions +dotnet_diagnostic.IDE0031.severity = none # Question - Null check can be simplified +dotnet_diagnostic.IDE0032.severity = none # Question - Use auto property +dotnet_diagnostic.IDE0037.severity = none # Question - Member name can be simplified +dotnet_diagnostic.IDE0041.severity = none # Question - Null check can be simplified +dotnet_diagnostic.IDE0047.severity = none # Question - Parentheses preferences +dotnet_diagnostic.IDE0049.severity = warning # Question - Name can be simplified +dotnet_diagnostic.IDE0051.severity = none # Question - Remove unused private member +dotnet_diagnostic.IDE0053.severity = none # Question - Use expression body for lambdas +dotnet_diagnostic.IDE0054.severity = none # Question - Use compound assignment +dotnet_diagnostic.IDE0055.severity = none # Question - Formatting rule +dotnet_diagnostic.IDE0057.severity = none # Question - Substring can be simplified +dotnet_diagnostic.IDE0058.severity = none # Question - Remove unnecessary expression value +dotnet_diagnostic.IDE0059.severity = none # Question - Unnecessary assignment of a value to +dotnet_diagnostic.IDE0060.severity = none # Question - Remove unused parameter +dotnet_diagnostic.IDE0063.severity = none # Question - Use simple +dotnet_diagnostic.IDE0065.severity = none # Question - +dotnet_diagnostic.IDE0066.severity = none # Question - Use +dotnet_diagnostic.IDE0078.severity = none # Question - Use pattern matching (may change code meaning) +dotnet_diagnostic.IDE0090.severity = warning # Question - Simplify new expression +dotnet_diagnostic.IDE0160.severity = warning # Question - Use block-scoped namespace +dotnet_diagnostic.IDE0161.severity = warning # Question - Namespace declaration preferences +dotnet_diagnostic.IDE0270.severity = none # Question - Null check can be simplified +dotnet_diagnostic.IDE0300.severity = none # Question - Collection initialization can be simplified +dotnet_diagnostic.IDE1006.severity = none # Question - Use collection expression for builder dotnet_style_prefer_collection_expression +dotnet_style_null_propagation = false # Question +dotnet_style_object_initializer = false # Question +dotnet_style_prefer_auto_properties = false # Question +dotnet_style_allow_statement_immediately_after_block_experimental = true # Question +dotnet_style_prefer_inferred_anonymous_type_member_names = false:warning # Question +dotnet_style_prefer_is_null_check_over_reference_equality_method = false # Question \ No newline at end of file diff --git a/Fab2ApprovalMKLink/.vscode/format-report.json b/Fab2ApprovalMKLink/.vscode/format-report.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/Fab2ApprovalMKLink/.vscode/format-report.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/Fab2ApprovalMKLink/.vscode/launch.json b/Fab2ApprovalMKLink/.vscode/launch.json new file mode 100644 index 0000000..7ecea87 --- /dev/null +++ b/Fab2ApprovalMKLink/.vscode/launch.json @@ -0,0 +1,33 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + "program": "${workspaceFolder}/bin/Debug/net8.0/Fab2ApprovalMKLink.dll", + "args": [ + "s", + "test" + ], + "cwd": "${workspaceFolder}", + "console": "integratedTerminal", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + }, + { + "type": "node", + "request": "launch", + "name": "node Launch Current Opened File", + "program": "${file}" + } + ] +} \ No newline at end of file diff --git a/Fab2ApprovalMKLink/.vscode/mklink.md b/Fab2ApprovalMKLink/.vscode/mklink.md new file mode 100644 index 0000000..93324cc --- /dev/null +++ b/Fab2ApprovalMKLink/.vscode/mklink.md @@ -0,0 +1,37 @@ +# mklink + +```bash 1731546128283 = 638671429282830000 = Wed Nov 13 2024 18:02:07 GMT-0700 (Mountain Standard Time) +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\App_Start" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\App_Start" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\bin" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\bin" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Content" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Content" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Controllers" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Controllers" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\DMO" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\DMO" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\EmailTemplates" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\EmailTemplates" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\fonts" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\fonts" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\FTPBatch" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\FTPBatch" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Jobs" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Jobs" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\JobSchedules" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\JobSchedules" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Lib" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Lib" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Misc" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Misc" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Models" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Models" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\obj" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\obj" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\PdfGenerator" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\PdfGenerator" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Properties" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Properties" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\SafeModels" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\SafeModels" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Scripts" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Scripts" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Utilities" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Utilities" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\View" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\View" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\ViewModels" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\ViewModels" +``` + +```bash 1731615429577 = 638672122295770000 = Thu Nov 14 2024 13:17:09 GMT-0700 (Mountain Standard Time) +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\.vscode\.UserSecrets" "C:\Users\phares\AppData\Roaming\Microsoft\UserSecrets\f2da5035-aba9-4676-9f8d-d6689f84663d" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\ViewModels" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\ViewModels" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Models" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Models" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Misc" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Misc" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\DMO" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\DMO" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Utilities" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Utilities" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\PdfGenerator" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\PdfGenerator" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Jobs" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Jobs" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\JobSchedules" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\JobSchedules" +``` diff --git a/Fab2ApprovalMKLink/.vscode/settings.json b/Fab2ApprovalMKLink/.vscode/settings.json new file mode 100644 index 0000000..f05d843 --- /dev/null +++ b/Fab2ApprovalMKLink/.vscode/settings.json @@ -0,0 +1,424 @@ +{ + "[markdown]": { + "editor.wordWrap": "off" + }, + "files.exclude": { + "**/.git": false, + "**/node_modules": true + }, + "files.watcherExclude": { + "**/node_modules": true + }, + "cSpell.words": [ + "abutton", + "accessibilities", + "accodingly", + "acknowledgmentby", + "Acks", + "actionsheet", + "Additonal", + "Addtional", + "againm", + "agendaview", + "Antlr", + "Appover", + "Appprrovers", + "Approvalog", + "Aprovers", + "Aproverslist", + "asax", + "aspnetmvc", + "Assignedto", + "Atachments", + "Attachemnt", + "Attachemnts", + "Attchment", + "auditee", + "Auditee", + "Auditees", + "automaically", + "Autthorized", + "beacuase", + "beforeunload", + "Belguim", + "bfound", + "bgcolor", + "Bies", + "binded", + "blackbackground", + "blackhover", + "blackpressed", + "blueenergy", + "blueopal", + "buttongroup", + "BYMRB", + "bytesgot", + "CAID", + "casection", + "CAXXXX", + "CCPCR", + "CCPCRB", + "cellspacing", + "Cheeso's", + "chkbx", + "Clib", + "colorpicker", + "columnmenu", + "columnsreorder", + "columnsresize", + "comming", + "Containmen", + "Copmments", + "correctiv", + "Correctivet", + "Creat", + "currentd", + "Cyle", + "dadada", + "darkbluehover", + "darkbluepressed", + "darkred", + "datafields", + "datasource", + "dataviz", + "datepicker", + "datetimepicker", + "dayview", + "Deletet", + "Delgation", + "DENITED", + "Deparmtent", + "departmentids", + "Descirption", + "devprog", + "dfeffc", + "Disp", + "Dispo", + "Dispoitio", + "Dispos", + "Dispositon", + "Dispostion", + "Dispostions", + "dispotypevalidation", + "Docbase", + "Documentum", + "Documetum", + "dont", + "downlaoded", + "draganddrop", + "dragcancel", + "dropdownlist", + "Eamils", + "ECNPCRB", + "Ecns", + "edmx", + "EECN", + "emai", + "emailparams", + "Emergrncy", + "energyblue", + "Eran", + "Esql", + "ETECN", + "EXCELOPENXML", + "existinglocation", + "Expando", + "extrafield", + "fadc", + "fbec", + "fcfdfd", + "fdff", + "fece", + "feeebd", + "ffdc", + "ffdd", + "fieldset", + "FILIPE", + "filtermenu", + "Fldr", + "flintstone", + "FLOWLOCS", + "FMEA", + "ftplib", + "FTPSPN", + "GETDATE", + "gitea", + "globaldocudms", + "glyphicons", + "groupable", + "Guids", + "halflings", + "Hexsize", + "highcontrast", + "Hmac", + "holdsteps", + "hostspecific", + "icenium", + "IECN", + "imagebrowser", + "IMRB", + "Infineon", + "Insertd", + "inverseicons", + "IPCRB", + "ISADMIN", + "islast", + "ISNULL", + "ITAR", + "jquery", + "jqueryval", + "jqwidgets", + "jqxbuttongroup", + "jqxbuttons", + "jqxcalendar", + "jqxchart", + "jqxcheckbox", + "jqxcolorpicker", + "jqxcombobox", + "jqxcore", + "jqxdata", + "jqxdatatable", + "jqxdatetimeinput", + "jqxdocking", + "jqxdockpanel", + "jqxdragdrop", + "jqxdropdownbutton", + "jqxdropdownlist", + "jqxexpander", + "jqxgauge", + "jqxgrid", + "jqxinput", + "jqxknockout", + "jqxlistbox", + "jqxlistmenu", + "jqxmaskedinput", + "jqxmenu", + "jqxnavigationbar", + "jqxnumberinput", + "jqxpanel", + "jqxpasswordinput", + "jqxprogressbar", + "jqxradiobutton", + "jqxrangeselector", + "jqxrating", + "jqxresponse", + "jqxscrollbar", + "jqxscrollview", + "jqxslider", + "jqxsplitter", + "jqxswitchbutton", + "jqxtabs", + "jqxtooltip", + "jqxtouch", + "jqxtree", + "jqxtreegrid", + "jqxtreemap", + "jqxvalidator", + "jqxwindow", + "kendogridcustom", + "kendoui", + "labelelement", + "labelledby", + "Leanred", + "lightgray", + "linkbutton", + "Linq", + "Listdiv", + "listview", + "Lnks", + "localfilename", + "loclist", + "logis", + "logtext", + "loopmis", + "lotdispo", + "LOTDISPSITION", + "Lotfile", + "lotlist", + "lotstatusoption", + "LTRIM", + "MADUREIRA", + "mailrelay", + "MDTM", + "meego", + "meetingid", + "menubutton", + "mesafi", + "metroblack", + "metrodark", + "miliseconds", + "modalview", + "modernizr", + "Modernizr", + "monthview", + "MRBIs", + "Mrbs", + "msecs", + "multipleextended", + "Navigatable", + "nbsp", + "newbase", + "newchange", + "newdi", + "newfilename", + "newsource", + "Newtonsoft", + "notications", + "Notifcation", + "Notifyf", + "NTLM", + "Nullcc", + "numerictextbox", + "objdata", + "OCAP", + "occured", + "odata", + "oldfilename", + "OLHOLD", + "onclick", + "onmousemove", + "OPDESC", + "OPENQUERY", + "Oper", + "operationslist", + "Orginator", + "Originatorname", + "Ouellette", + "Owin", + "pageable", + "Pageable", + "panelbar", + "parentid", + "parminput", + "parms", + "Parms", + "particula", + "pasv", + "PASV", + "PATINDEX", + "PCRB", + "PCRBID", + "pcrvalues", + "pdbonly", + "Preventitive", + "preventivet", + "Prevetative", + "proces", + "Processedl", + "procs", + "productfamilies", + "progess", + "progressbar", + "qrcode", + "Quanityt", + "rangebar", + "Recep", + "Recepient", + "recieved", + "recordlock", + "remotefilename", + "reorderable", + "reportform", + "reportslist", + "reportslistdiv", + "Reqquired", + "Reqs", + "Requiest", + "Responsibles", + "RETR", + "Revisioing", + "Revisioned", + "Revison", + "rgba", + "rkotian", + "RNFR", + "RNTO", + "Roless", + "roundbg", + "RTRIM", + "SAMDB", + "scroller", + "scrollview", + "seleced", + "selectionlog", + "Selectpart", + "sess", + "Sfisharepoint", + "shinyblack", + "showpassword", + "SIGNON", + "simpleparser", + "slddrw", + "sldprt", + "sortasc", + "sortascbutton", + "sortdesc", + "sortdescbutton", + "sortremove", + "sparkline", + "splitview", + "SPNMRB", + "SPNPDB", + "SSRS", + "Sssign", + "Staus", + "stylesheet", + "Submited", + "subrole", + "subroles", + "Succefully", + "Succesfully", + "sucessfully", + "SURP", + "Swashbuckle", + "SWRN", + "tabindex", + "tabstrip", + "Tahoma", + "taskcompleted", + "Tasklist", + "Taveler", + "TECN", + "TECNs", + "TEMIRWAP", + "tempecd", + "tempimplement", + "templabel", + "tempvalue", + "TEMSA", + "timepicker", + "Tobe", + "Toplevel", + "Totrav", + "trainingby", + "Traininglist", + "traininglistdiv", + "transanction", + "Trav", + "Traveller", + "Traverler", + "TRAVLELER", + "Travler", + "TREEVIEW", + "trigerred", + "ttinclude", + "Uhandled", + "Updat", + "Uplaod", + "Upto", + "userevents", + "userids", + "userlist", + "Validatable", + "valueelement", + "Variabls", + "Verdana", + "vgrid", + "viewmodel", + "vsdoc", + "whethere", + "windowsphone", + "Winsock", + "worlflow" + ] +} \ No newline at end of file diff --git a/Fab2ApprovalMKLink/.vscode/tasks.json b/Fab2ApprovalMKLink/.vscode/tasks.json new file mode 100644 index 0000000..1723004 --- /dev/null +++ b/Fab2ApprovalMKLink/.vscode/tasks.json @@ -0,0 +1,109 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "User Secrets Init", + "command": "dotnet", + "type": "process", + "args": [ + "user-secrets", + "-p", + "${workspaceFolder}/Fab2ApprovalMKLink.csproj", + "init" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "User Secrets Set", + "command": "dotnet", + "type": "process", + "args": [ + "user-secrets", + "-p", + "${workspaceFolder}/Fab2ApprovalMKLink.csproj", + "set", + "_UserSecretsId", + "f2da5035-aba9-4676-9f8d-d6689f84663d" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "Format", + "command": "dotnet", + "type": "process", + "args": [ + "format", + "--report", + ".vscode", + "--verbosity", + "detailed", + "--severity", + "warn" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "Format-Whitespaces", + "command": "dotnet", + "type": "process", + "args": [ + "format", + "whitespace" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/Fab2ApprovalMKLink.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/Fab2ApprovalMKLink.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/Fab2ApprovalMKLink.csproj" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "Publish AOT", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "-r", + "win-x64", + "-c", + "Release", + "-p:PublishAot=true", + "${workspaceFolder}/Fab2ApprovalMKLink.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj b/Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj new file mode 100644 index 0000000..1296406 --- /dev/null +++ b/Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj @@ -0,0 +1,51 @@ + + + SAK + SAK + SAK + SAK + f2da5035-aba9-4676-9f8d-d6689f84663d + + + true + disable + false + enable + Exe + win-x64;linux-x64 + net8.0 + + + NET8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Fab2ApprovalMKLink/Program.cs b/Fab2ApprovalMKLink/Program.cs new file mode 100644 index 0000000..381e519 --- /dev/null +++ b/Fab2ApprovalMKLink/Program.cs @@ -0,0 +1,77 @@ +using System; +using System.Diagnostics; + +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Hosting.WindowsServices; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalMKLink; + +public class Program { + + public static int Main(string[] args) { + ILogger? logger = null; + WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(args); + _ = webApplicationBuilder.Configuration.AddUserSecrets(); + AppSettings appSettings = AppSettings.Get(webApplicationBuilder.Configuration); + if (string.IsNullOrEmpty(appSettings.Company)) + throw new Exception("Company name must have a value!"); + if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName)) + throw new Exception("Working directory name must have a value!"); + try { + _ = webApplicationBuilder.Services.Configure(options => options.SuppressModelStateInvalidFilter = true); + _ = webApplicationBuilder.Services.AddControllers(); + _ = webApplicationBuilder.Services.AddDistributedMemoryCache(); + _ = webApplicationBuilder.Services.AddHttpClient(); + _ = webApplicationBuilder.Services.AddSingleton(_ => appSettings); + _ = webApplicationBuilder.Services.AddSwaggerGen(); + _ = webApplicationBuilder.Services.AddSession(sessionOptions => { + sessionOptions.IdleTimeout = TimeSpan.FromSeconds(2000); + sessionOptions.Cookie.HttpOnly = true; + sessionOptions.Cookie.IsEssential = true; + } + ); + if (WindowsServiceHelpers.IsWindowsService()) { + _ = webApplicationBuilder.Services.AddSingleton(); + _ = webApplicationBuilder.Logging.AddEventLog(settings => { +#pragma warning disable CA1416 + if (string.IsNullOrEmpty(settings.SourceName)) + settings.SourceName = webApplicationBuilder.Environment.ApplicationName; +#pragma warning restore + }); + } + WebApplication webApplication = webApplicationBuilder.Build(); + if (Debugger.IsAttached) + webApplication.Services.GetRequiredService(); + logger = webApplication.Services.GetRequiredService>(); + _ = webApplication.UseCors(corsPolicyBuilder => corsPolicyBuilder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); + if (!webApplicationBuilder.Environment.IsDevelopment()) { + _ = webApplication.UseExceptionHandler("/Error"); + _ = webApplication.UseHttpsRedirection(); + _ = webApplication.UseHsts(); + } else { + if (string.IsNullOrEmpty(appSettings.URLs)) { + Environment.ExitCode = -1; + webApplication.Lifetime.StopApplication(); + } + _ = webApplication.UseSwagger(); + _ = webApplication.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Server V1")); + } + _ = webApplication.UseSession(); + _ = webApplication.MapControllers(); + logger.LogInformation("Starting Web Application"); + webApplication.Run(); + return 0; + } catch (Exception ex) { + try { logger?.LogCritical(ex, "Host terminated unexpectedly"); } catch (Exception) { } + throw; + } + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/.editorconfig b/Fab2ApprovalSystem/.editorconfig new file mode 100644 index 0000000..23eda2b --- /dev/null +++ b/Fab2ApprovalSystem/.editorconfig @@ -0,0 +1,380 @@ +[*.md] +end_of_line = crlf +file_header_template = unset +indent_size = 2 +indent_style = space +insert_final_newline = false +root = true +tab_width = 2 +[*.csproj] +end_of_line = crlf +file_header_template = unset +indent_size = 2 +indent_style = space +insert_final_newline = false +root = true +tab_width = 2 +[*.cs] +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true +csharp_new_line_before_catch = false +csharp_new_line_before_else = false +csharp_new_line_before_finally = false +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = none +csharp_new_line_between_query_expression_clauses = true +csharp_prefer_braces = false +csharp_prefer_qualified_reference = true:error +csharp_prefer_simple_default_expression = true:warning +csharp_prefer_simple_using_statement = true:warning +csharp_prefer_static_local_function = true:warning +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = false +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true +csharp_style_allow_embedded_statements_on_same_line_experimental = true +csharp_style_conditional_delegate_call = true +csharp_style_deconstructed_variable_declaration = false +csharp_style_expression_bodied_accessors = when_on_single_line:warning +csharp_style_expression_bodied_constructors = when_on_single_line:warning +csharp_style_expression_bodied_indexers = when_on_single_line:warning +csharp_style_expression_bodied_lambdas = when_on_single_line:warning +csharp_style_expression_bodied_local_functions = when_on_single_line:warning +csharp_style_expression_bodied_methods = when_on_single_line:warning +csharp_style_expression_bodied_operators = when_on_single_line:warning +csharp_style_expression_bodied_properties = when_on_single_line:warning +csharp_style_implicit_object_creation_when_type_is_apparent = true:warning +csharp_style_inlined_variable_declaration = false +csharp_style_namespace_declarations = file_scoped:warning +csharp_style_pattern_local_over_anonymous_function = true:warning +csharp_style_pattern_matching_over_as_with_null_check = true:warning +csharp_style_pattern_matching_over_is_with_cast_check = true:warning +csharp_style_prefer_index_operator = true:warning +csharp_style_prefer_not_pattern = true:warning +csharp_style_prefer_null_check_over_type_check = true +csharp_style_prefer_pattern_matching = true:warning +csharp_style_prefer_range_operator = true:warning +csharp_style_prefer_switch_expression = true:warning +csharp_style_throw_expression = true +csharp_style_unused_value_assignment_preference = discard_variable:warning +csharp_style_unused_value_expression_statement_preference = discard_variable:warning +csharp_style_var_elsewhere = false:warning +csharp_style_var_for_built_in_types = false:warning +csharp_style_var_when_type_is_apparent = false:warning +csharp_using_directive_placement = outside_namespace +dotnet_analyzer_diagnostic.category-Design.severity = error +dotnet_analyzer_diagnostic.category-Documentation.severity = error +dotnet_analyzer_diagnostic.category-Globalization.severity = none +dotnet_analyzer_diagnostic.category-Interoperability.severity = error +dotnet_analyzer_diagnostic.category-Maintainability.severity = error +dotnet_analyzer_diagnostic.category-Naming.severity = none +dotnet_analyzer_diagnostic.category-Performance.severity = none +dotnet_analyzer_diagnostic.category-Reliability.severity = error +dotnet_analyzer_diagnostic.category-Security.severity = error +dotnet_analyzer_diagnostic.category-SingleFile.severity = error +dotnet_analyzer_diagnostic.category-Style.severity = error +dotnet_analyzer_diagnostic.category-Usage.severity = error +dotnet_code_quality_unused_parameters = all +dotnet_code_quality_unused_parameters = non_public +dotnet_code_quality.CAXXXX.api_surface = private, internal +dotnet_diagnostic.CA1001.severity = error # CA1001: Types that own disposable fields should be disposable +dotnet_diagnostic.CA1051.severity = error # CA1051: Do not declare visible instance fields +dotnet_diagnostic.CA1511.severity = warning # CA1511: Use 'ArgumentException.ThrowIfNullOrEmpty' instead of explicitly throwing a new exception instance +dotnet_diagnostic.CA1513.severity = warning # Use 'ObjectDisposedException.ThrowIf' instead of explicitly throwing a new exception instance +dotnet_diagnostic.CA1825.severity = warning # CA1825: Avoid zero-length array allocations +dotnet_diagnostic.CA1829.severity = error # CA1829: Use Length/Count property instead of Count() when available +dotnet_diagnostic.CA1834.severity = warning # CA1834: Consider using 'StringBuilder.Append(char)' when applicable +dotnet_diagnostic.CA1860.severity = error # CA1860: Prefer comparing 'Count' to 0 rather than using 'Any()', both for clarity and for performance +dotnet_diagnostic.CA1862.severity = warning # CA1862: Prefer using 'string.Equals(string, StringComparison)' to perform a case-insensitive comparison, but keep in mind that this might cause subtle changes in behavior, so make sure to conduct thorough testing after applying the suggestion, or if culturally sensitive comparison is not required, consider using 'StringComparison.OrdinalIgnoreCase' +dotnet_diagnostic.CA1869.severity = none # CA1869: Avoid creating a new 'JsonSerializerOptions' instance for every serialization operation. Cache and reuse instances instead. +dotnet_diagnostic.CA2201.severity = none # CA2201: Exception type System.NullReferenceException is reserved by the runtime +dotnet_diagnostic.CA2254.severity = none # CA2254: The logging message template should not vary between calls to 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])' +dotnet_diagnostic.IDE0001.severity = warning # IDE0001: Simplify name +dotnet_diagnostic.IDE0002.severity = warning # Simplify (member access) - System.Version.Equals("1", "2"); Version.Equals("1", "2"); +dotnet_diagnostic.IDE0004.severity = warning # IDE0004: Cast is redundant. +dotnet_diagnostic.IDE0005.severity = error # Using directive is unnecessary +dotnet_diagnostic.IDE0010.severity = none # Add missing cases to switch statement (IDE0010) +dotnet_diagnostic.IDE0028.severity = error # IDE0028: Collection initialization can be simplified +dotnet_diagnostic.IDE0031.severity = warning # Use null propagation (IDE0031) +dotnet_diagnostic.IDE0047.severity = warning # IDE0047: Parentheses can be removed +dotnet_diagnostic.IDE0048.severity = none # Parentheses preferences (IDE0047 and IDE0048) +dotnet_diagnostic.IDE0049.severity = warning # Use language keywords instead of framework type names for type references (IDE0049) +dotnet_diagnostic.IDE0051.severity = error # Private member '' is unused [, ] +dotnet_diagnostic.IDE0058.severity = error # IDE0058: Expression value is never used +dotnet_diagnostic.IDE0060.severity = error # IDE0060: Remove unused parameter +dotnet_diagnostic.IDE0074.severity = warning # IDE0074: Use compound assignment +dotnet_diagnostic.IDE0130.severity = none # Namespace does not match folder structure (IDE0130) +dotnet_diagnostic.IDE0270.severity = warning # IDE0270: Null check can be simplified +dotnet_diagnostic.IDE0290.severity = none # Use primary constructor [Distance]csharp(IDE0290) +dotnet_diagnostic.IDE0300.severity = error # IDE0300: Collection initialization can be simplified +dotnet_diagnostic.IDE0301.severity = error #IDE0301: Collection initialization can be simplified +dotnet_diagnostic.IDE0305.severity = none # IDE0305: Collection initialization can be simplified +dotnet_diagnostic.IDE2000.severity = error # IDE2000: Allow multiple blank lines +dotnet_naming_rule.abstract_method_should_be_pascal_case.severity = warning +dotnet_naming_rule.abstract_method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.abstract_method_should_be_pascal_case.symbols = abstract_method +dotnet_naming_rule.class_should_be_pascal_case.severity = warning +dotnet_naming_rule.class_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.class_should_be_pascal_case.symbols = class +dotnet_naming_rule.delegate_should_be_pascal_case.severity = warning +dotnet_naming_rule.delegate_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.delegate_should_be_pascal_case.symbols = delegate +dotnet_naming_rule.enum_should_be_pascal_case.severity = warning +dotnet_naming_rule.enum_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.enum_should_be_pascal_case.symbols = enum +dotnet_naming_rule.event_should_be_pascal_case.severity = warning +dotnet_naming_rule.event_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.event_should_be_pascal_case.symbols = event +dotnet_naming_rule.interface_should_be_begins_with_i.severity = warning +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.method_should_be_pascal_case.severity = warning +dotnet_naming_rule.method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.method_should_be_pascal_case.symbols = method +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = warning +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.private_method_should_be_pascal_case.severity = warning +dotnet_naming_rule.private_method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.private_method_should_be_pascal_case.symbols = private_method +dotnet_naming_rule.private_or_internal_field_should_be_private_of_internal_field.severity = warning +dotnet_naming_rule.private_or_internal_field_should_be_private_of_internal_field.style = private_of_internal_field +dotnet_naming_rule.private_or_internal_field_should_be_private_of_internal_field.symbols = private_or_internal_field +dotnet_naming_rule.private_or_internal_static_field_should_be_private_of_internal_field.severity = warning +dotnet_naming_rule.private_or_internal_static_field_should_be_private_of_internal_field.style = private_of_internal_field +dotnet_naming_rule.private_or_internal_static_field_should_be_private_of_internal_field.symbols = private_or_internal_static_field +dotnet_naming_rule.property_should_be_pascal_case.severity = warning +dotnet_naming_rule.property_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.property_should_be_pascal_case.symbols = property +dotnet_naming_rule.public_or_protected_field_should_be_private_of_internal_field.severity = warning +dotnet_naming_rule.public_or_protected_field_should_be_private_of_internal_field.style = private_of_internal_field +dotnet_naming_rule.public_or_protected_field_should_be_private_of_internal_field.symbols = public_or_protected_field +dotnet_naming_rule.static_field_should_be_pascal_case.severity = warning +dotnet_naming_rule.static_field_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.static_field_should_be_pascal_case.symbols = static_field +dotnet_naming_rule.static_method_should_be_pascal_case.severity = warning +dotnet_naming_rule.static_method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.static_method_should_be_pascal_case.symbols = static_method +dotnet_naming_rule.struct_should_be_pascal_case.severity = warning +dotnet_naming_rule.struct_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.struct_should_be_pascal_case.symbols = struct +dotnet_naming_rule.types_should_be_pascal_case.severity = warning +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_style.begins_with_i.capitalization = pascal_case +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.private_of_internal_field.capitalization = pascal_case +dotnet_naming_style.private_of_internal_field.required_prefix = _ +dotnet_naming_style.private_of_internal_field.required_suffix = +dotnet_naming_style.private_of_internal_field.word_separator = +dotnet_naming_symbols.abstract_method.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.abstract_method.applicable_kinds = method +dotnet_naming_symbols.abstract_method.required_modifiers = abstract +dotnet_naming_symbols.class.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.class.applicable_kinds = class +dotnet_naming_symbols.class.required_modifiers = +dotnet_naming_symbols.delegate.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.delegate.applicable_kinds = delegate +dotnet_naming_symbols.delegate.required_modifiers = +dotnet_naming_symbols.enum.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.enum.applicable_kinds = enum +dotnet_naming_symbols.enum.required_modifiers = +dotnet_naming_symbols.event.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.event.applicable_kinds = event +dotnet_naming_symbols.event.required_modifiers = +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.required_modifiers = +dotnet_naming_symbols.method.applicable_accessibilities = public +dotnet_naming_symbols.method.applicable_kinds = method +dotnet_naming_symbols.method.required_modifiers = +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.required_modifiers = +dotnet_naming_symbols.private_method.applicable_accessibilities = private +dotnet_naming_symbols.private_method.applicable_kinds = method +dotnet_naming_symbols.private_method.required_modifiers = +dotnet_naming_symbols.private_or_internal_field.applicable_accessibilities = internal, private, private_protected +dotnet_naming_symbols.private_or_internal_field.applicable_kinds = field +dotnet_naming_symbols.private_or_internal_field.required_modifiers = +dotnet_naming_symbols.private_or_internal_static_field.applicable_accessibilities = internal, private, private_protected +dotnet_naming_symbols.private_or_internal_static_field.applicable_kinds = field +dotnet_naming_symbols.private_or_internal_static_field.required_modifiers = static +dotnet_naming_symbols.property.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.property.applicable_kinds = property +dotnet_naming_symbols.property.required_modifiers = +dotnet_naming_symbols.public_or_protected_field.applicable_accessibilities = public, protected +dotnet_naming_symbols.public_or_protected_field.applicable_kinds = field +dotnet_naming_symbols.public_or_protected_field.required_modifiers = +dotnet_naming_symbols.static_field.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.static_field.applicable_kinds = field +dotnet_naming_symbols.static_field.required_modifiers = static +dotnet_naming_symbols.static_method.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.static_method.applicable_kinds = method +dotnet_naming_symbols.static_method.required_modifiers = static +dotnet_naming_symbols.struct.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.struct.applicable_kinds = struct +dotnet_naming_symbols.struct.required_modifiers = +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.required_modifiers = +dotnet_remove_unnecessary_suppression_exclusions = 0 +dotnet_separate_import_directive_groups = true +dotnet_sort_system_directives_first = true +dotnet_style_allow_multiple_blank_lines_experimental = false:warning +dotnet_style_allow_statement_immediately_after_block_experimental = true +dotnet_style_coalesce_expression = true +dotnet_style_collection_initializer = true:warning +dotnet_style_explicit_tuple_names = true:warning +dotnet_style_namespace_match_folder = true +dotnet_style_null_propagation = true:warning +dotnet_style_object_initializer = true:warning +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_operators = never_if_unnecessary +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity +dotnet_style_predefined_type_for_locals_parameters_members = true +dotnet_style_predefined_type_for_member_access = true:warning +dotnet_style_prefer_auto_properties = true:warning +dotnet_style_prefer_compound_assignment = true:warning +dotnet_style_prefer_conditional_expression_over_assignment = false +dotnet_style_prefer_conditional_expression_over_return = false +dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning +dotnet_style_prefer_inferred_tuple_names = true:warning +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning +dotnet_style_prefer_simplified_boolean_expressions = true:warning +dotnet_style_prefer_simplified_interpolation = true +dotnet_style_qualification_for_event = false:error +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_method = false:error +dotnet_style_qualification_for_property = false:error +dotnet_style_readonly_field = true:warning +dotnet_style_require_accessibility_modifiers = for_non_interface_members +end_of_line = crlf +file_header_template = unset +indent_size = 4 +indent_style = space +insert_final_newline = false +root = true +tab_width = 4 +# https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1822 +# https://github.com/dotnet/aspnetcore/blob/main/.editorconfig +# https://github.com/dotnet/project-system/blob/main/.editorconfig + +# Question +csharp_prefer_simple_using_statement = false # Question +csharp_style_expression_bodied_constructors = when_on_single_line:none # Question +csharp_style_expression_bodied_properties = true # Question +csharp_style_implicit_object_creation_when_type_is_apparent = true:warning # Question +csharp_style_pattern_matching_over_as_with_null_check = false # Question +csharp_style_prefer_pattern_matching = false # Question +csharp_style_prefer_range_operator = false # Question +csharp_style_prefer_switch_expression = false # Question +csharp_style_unused_value_assignment_preference = unused_local_variable # Question +csharp_style_unused_value_expression_statement_preference = false # Question +csharp_style_var_elsewhere = false:none # Question +csharp_style_var_for_built_in_types = false:none # Question +csharp_style_var_when_type_is_apparent = false:warning # Question +dotnet_diagnostic.CA1001.severity = none # Question - Types that own disposable fields should be disposable +dotnet_diagnostic.CA1051.severity = none # Question - Do not declare visible instance fields +dotnet_diagnostic.CA1416.severity = none # Question - This call site is reachable on all platforms. +dotnet_diagnostic.CA1510.severity = none # Question - Use +dotnet_diagnostic.CA1834.severity = none # CA1834: Consider using 'StringBuilder.Append(char)' when applicable +dotnet_diagnostic.CA1860.severity = none # Question - Avoid using +dotnet_diagnostic.CA1862.severity = none # Question - Prefer using +dotnet_diagnostic.CA2208.severity = none # Question - Instantiate argument exceptions correctly +dotnet_diagnostic.CA2211.severity = none # Question - Non-constant fields should not be visible +dotnet_diagnostic.CA2249.severity = none # Question - Use +dotnet_diagnostic.CA2253.severity = none # Question - Named placeholders should not be numeric values +dotnet_diagnostic.CS0103.severity = none # Question - The name +dotnet_diagnostic.CS0168.severity = none # Question - The variable +dotnet_diagnostic.CS0219.severity = none # Question - The variable +dotnet_diagnostic.CS0612.severity = none # Question - is obsolete +dotnet_diagnostic.CS0618.severity = none # Question - Compiler Warning (level 2) +dotnet_diagnostic.CS0659.severity = none # Question - Compiler Warning (level 3) +dotnet_diagnostic.CS8019.severity = warning # Question - Unnecessary using directive. +dotnet_diagnostic.CS8600.severity = none # Question - Converting null literal or possible null value to non-nullable type +dotnet_diagnostic.CS8602.severity = none # Question - Dereference of a possibly null reference. +dotnet_diagnostic.CS8603.severity = none # Question - Possible null reference return +dotnet_diagnostic.CS8604.severity = none # Question - Possible null reference argument for parameter. +dotnet_diagnostic.CS8618.severity = none # Question - Non-nullable variable must contain a non-null value when exiting constructor +dotnet_diagnostic.CS8625.severity = none # Question - Cannot convert null literal to non-nullable reference type. +dotnet_diagnostic.CS8629.severity = none # Question - Nullable value type may be null +dotnet_diagnostic.CS8765.severity = none # Question - Nullability of type of parameter +dotnet_diagnostic.IDE0005.severity = none # Question - Remove unnecessary using directives +dotnet_diagnostic.IDE0008.severity = warning # Question - Use explicit type instead of +dotnet_diagnostic.IDE0017.severity = none # Question - Object initialization can be simplified +dotnet_diagnostic.IDE0019.severity = none # Question - Use pattern matching +dotnet_diagnostic.IDE0021.severity = none # Question - Use expression body for constructor +dotnet_diagnostic.IDE0022.severity = none # Question - Use expression body for method +dotnet_diagnostic.IDE0025.severity = none # Question - Use expression body for property +dotnet_diagnostic.IDE0027.severity = none # Question - Use expression body for accessor +dotnet_diagnostic.IDE0028.severity = none # Question - Use collection initializers or expressions +dotnet_diagnostic.IDE0031.severity = none # Question - Null check can be simplified +dotnet_diagnostic.IDE0032.severity = none # Question - Use auto property +dotnet_diagnostic.IDE0037.severity = none # Question - Member name can be simplified +dotnet_diagnostic.IDE0041.severity = none # Question - Null check can be simplified +dotnet_diagnostic.IDE0047.severity = none # Question - Parentheses preferences +dotnet_diagnostic.IDE0049.severity = warning # Question - Name can be simplified +dotnet_diagnostic.IDE0051.severity = none # Question - Remove unused private member +dotnet_diagnostic.IDE0053.severity = none # Question - Use expression body for lambdas +dotnet_diagnostic.IDE0054.severity = none # Question - Use compound assignment +dotnet_diagnostic.IDE0055.severity = none # Question - Formatting rule +dotnet_diagnostic.IDE0057.severity = none # Question - Substring can be simplified +dotnet_diagnostic.IDE0058.severity = none # Question - Remove unnecessary expression value +dotnet_diagnostic.IDE0059.severity = none # Question - Unnecessary assignment of a value to +dotnet_diagnostic.IDE0060.severity = none # Question - Remove unused parameter +dotnet_diagnostic.IDE0063.severity = none # Question - Use simple +dotnet_diagnostic.IDE0065.severity = none # Question - +dotnet_diagnostic.IDE0066.severity = none # Question - Use +dotnet_diagnostic.IDE0078.severity = none # Question - Use pattern matching (may change code meaning) +dotnet_diagnostic.IDE0090.severity = warning # Question - Simplify new expression +dotnet_diagnostic.IDE0160.severity = warning # Question - Use block-scoped namespace +dotnet_diagnostic.IDE0161.severity = warning # Question - Namespace declaration preferences +dotnet_diagnostic.IDE0270.severity = none # Question - Null check can be simplified +dotnet_diagnostic.IDE0300.severity = none # Question - Collection initialization can be simplified +dotnet_diagnostic.IDE1006.severity = none # Question - Use collection expression for builder dotnet_style_prefer_collection_expression +dotnet_style_null_propagation = false # Question +dotnet_style_object_initializer = false # Question +dotnet_style_prefer_auto_properties = false # Question +dotnet_style_allow_statement_immediately_after_block_experimental = true # Question +dotnet_style_prefer_is_null_check_over_reference_equality_method = false # Question +dotnet_style_prefer_inferred_anonymous_type_member_names = false:warning # Question \ No newline at end of file diff --git a/Fab2ApprovalSystem/.vscode/format-report.json b/Fab2ApprovalSystem/.vscode/format-report.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/Fab2ApprovalSystem/.vscode/format-report.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/Fab2ApprovalSystem/.vscode/launch.json b/Fab2ApprovalSystem/.vscode/launch.json new file mode 100644 index 0000000..7846848 --- /dev/null +++ b/Fab2ApprovalSystem/.vscode/launch.json @@ -0,0 +1,30 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + "program": "${workspaceFolder}/bin/Debug/net8.0/win-x64/Fab2ApprovalSystem.dll", + "args": [], + "cwd": "${workspaceFolder}", + "console": "integratedTerminal", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + }, + { + "type": "node", + "request": "launch", + "name": "node Launch Current Opened File", + "program": "${file}" + } + ] +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/.vscode/settings.json b/Fab2ApprovalSystem/.vscode/settings.json new file mode 100644 index 0000000..f05d843 --- /dev/null +++ b/Fab2ApprovalSystem/.vscode/settings.json @@ -0,0 +1,424 @@ +{ + "[markdown]": { + "editor.wordWrap": "off" + }, + "files.exclude": { + "**/.git": false, + "**/node_modules": true + }, + "files.watcherExclude": { + "**/node_modules": true + }, + "cSpell.words": [ + "abutton", + "accessibilities", + "accodingly", + "acknowledgmentby", + "Acks", + "actionsheet", + "Additonal", + "Addtional", + "againm", + "agendaview", + "Antlr", + "Appover", + "Appprrovers", + "Approvalog", + "Aprovers", + "Aproverslist", + "asax", + "aspnetmvc", + "Assignedto", + "Atachments", + "Attachemnt", + "Attachemnts", + "Attchment", + "auditee", + "Auditee", + "Auditees", + "automaically", + "Autthorized", + "beacuase", + "beforeunload", + "Belguim", + "bfound", + "bgcolor", + "Bies", + "binded", + "blackbackground", + "blackhover", + "blackpressed", + "blueenergy", + "blueopal", + "buttongroup", + "BYMRB", + "bytesgot", + "CAID", + "casection", + "CAXXXX", + "CCPCR", + "CCPCRB", + "cellspacing", + "Cheeso's", + "chkbx", + "Clib", + "colorpicker", + "columnmenu", + "columnsreorder", + "columnsresize", + "comming", + "Containmen", + "Copmments", + "correctiv", + "Correctivet", + "Creat", + "currentd", + "Cyle", + "dadada", + "darkbluehover", + "darkbluepressed", + "darkred", + "datafields", + "datasource", + "dataviz", + "datepicker", + "datetimepicker", + "dayview", + "Deletet", + "Delgation", + "DENITED", + "Deparmtent", + "departmentids", + "Descirption", + "devprog", + "dfeffc", + "Disp", + "Dispo", + "Dispoitio", + "Dispos", + "Dispositon", + "Dispostion", + "Dispostions", + "dispotypevalidation", + "Docbase", + "Documentum", + "Documetum", + "dont", + "downlaoded", + "draganddrop", + "dragcancel", + "dropdownlist", + "Eamils", + "ECNPCRB", + "Ecns", + "edmx", + "EECN", + "emai", + "emailparams", + "Emergrncy", + "energyblue", + "Eran", + "Esql", + "ETECN", + "EXCELOPENXML", + "existinglocation", + "Expando", + "extrafield", + "fadc", + "fbec", + "fcfdfd", + "fdff", + "fece", + "feeebd", + "ffdc", + "ffdd", + "fieldset", + "FILIPE", + "filtermenu", + "Fldr", + "flintstone", + "FLOWLOCS", + "FMEA", + "ftplib", + "FTPSPN", + "GETDATE", + "gitea", + "globaldocudms", + "glyphicons", + "groupable", + "Guids", + "halflings", + "Hexsize", + "highcontrast", + "Hmac", + "holdsteps", + "hostspecific", + "icenium", + "IECN", + "imagebrowser", + "IMRB", + "Infineon", + "Insertd", + "inverseicons", + "IPCRB", + "ISADMIN", + "islast", + "ISNULL", + "ITAR", + "jquery", + "jqueryval", + "jqwidgets", + "jqxbuttongroup", + "jqxbuttons", + "jqxcalendar", + "jqxchart", + "jqxcheckbox", + "jqxcolorpicker", + "jqxcombobox", + "jqxcore", + "jqxdata", + "jqxdatatable", + "jqxdatetimeinput", + "jqxdocking", + "jqxdockpanel", + "jqxdragdrop", + "jqxdropdownbutton", + "jqxdropdownlist", + "jqxexpander", + "jqxgauge", + "jqxgrid", + "jqxinput", + "jqxknockout", + "jqxlistbox", + "jqxlistmenu", + "jqxmaskedinput", + "jqxmenu", + "jqxnavigationbar", + "jqxnumberinput", + "jqxpanel", + "jqxpasswordinput", + "jqxprogressbar", + "jqxradiobutton", + "jqxrangeselector", + "jqxrating", + "jqxresponse", + "jqxscrollbar", + "jqxscrollview", + "jqxslider", + "jqxsplitter", + "jqxswitchbutton", + "jqxtabs", + "jqxtooltip", + "jqxtouch", + "jqxtree", + "jqxtreegrid", + "jqxtreemap", + "jqxvalidator", + "jqxwindow", + "kendogridcustom", + "kendoui", + "labelelement", + "labelledby", + "Leanred", + "lightgray", + "linkbutton", + "Linq", + "Listdiv", + "listview", + "Lnks", + "localfilename", + "loclist", + "logis", + "logtext", + "loopmis", + "lotdispo", + "LOTDISPSITION", + "Lotfile", + "lotlist", + "lotstatusoption", + "LTRIM", + "MADUREIRA", + "mailrelay", + "MDTM", + "meego", + "meetingid", + "menubutton", + "mesafi", + "metroblack", + "metrodark", + "miliseconds", + "modalview", + "modernizr", + "Modernizr", + "monthview", + "MRBIs", + "Mrbs", + "msecs", + "multipleextended", + "Navigatable", + "nbsp", + "newbase", + "newchange", + "newdi", + "newfilename", + "newsource", + "Newtonsoft", + "notications", + "Notifcation", + "Notifyf", + "NTLM", + "Nullcc", + "numerictextbox", + "objdata", + "OCAP", + "occured", + "odata", + "oldfilename", + "OLHOLD", + "onclick", + "onmousemove", + "OPDESC", + "OPENQUERY", + "Oper", + "operationslist", + "Orginator", + "Originatorname", + "Ouellette", + "Owin", + "pageable", + "Pageable", + "panelbar", + "parentid", + "parminput", + "parms", + "Parms", + "particula", + "pasv", + "PASV", + "PATINDEX", + "PCRB", + "PCRBID", + "pcrvalues", + "pdbonly", + "Preventitive", + "preventivet", + "Prevetative", + "proces", + "Processedl", + "procs", + "productfamilies", + "progess", + "progressbar", + "qrcode", + "Quanityt", + "rangebar", + "Recep", + "Recepient", + "recieved", + "recordlock", + "remotefilename", + "reorderable", + "reportform", + "reportslist", + "reportslistdiv", + "Reqquired", + "Reqs", + "Requiest", + "Responsibles", + "RETR", + "Revisioing", + "Revisioned", + "Revison", + "rgba", + "rkotian", + "RNFR", + "RNTO", + "Roless", + "roundbg", + "RTRIM", + "SAMDB", + "scroller", + "scrollview", + "seleced", + "selectionlog", + "Selectpart", + "sess", + "Sfisharepoint", + "shinyblack", + "showpassword", + "SIGNON", + "simpleparser", + "slddrw", + "sldprt", + "sortasc", + "sortascbutton", + "sortdesc", + "sortdescbutton", + "sortremove", + "sparkline", + "splitview", + "SPNMRB", + "SPNPDB", + "SSRS", + "Sssign", + "Staus", + "stylesheet", + "Submited", + "subrole", + "subroles", + "Succefully", + "Succesfully", + "sucessfully", + "SURP", + "Swashbuckle", + "SWRN", + "tabindex", + "tabstrip", + "Tahoma", + "taskcompleted", + "Tasklist", + "Taveler", + "TECN", + "TECNs", + "TEMIRWAP", + "tempecd", + "tempimplement", + "templabel", + "tempvalue", + "TEMSA", + "timepicker", + "Tobe", + "Toplevel", + "Totrav", + "trainingby", + "Traininglist", + "traininglistdiv", + "transanction", + "Trav", + "Traveller", + "Traverler", + "TRAVLELER", + "Travler", + "TREEVIEW", + "trigerred", + "ttinclude", + "Uhandled", + "Updat", + "Uplaod", + "Upto", + "userevents", + "userids", + "userlist", + "Validatable", + "valueelement", + "Variabls", + "Verdana", + "vgrid", + "viewmodel", + "vsdoc", + "whethere", + "windowsphone", + "Winsock", + "worlflow" + ] +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/.vscode/tasks.json b/Fab2ApprovalSystem/.vscode/tasks.json new file mode 100644 index 0000000..a6074d9 --- /dev/null +++ b/Fab2ApprovalSystem/.vscode/tasks.json @@ -0,0 +1,20 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "MSBuild", + "command": "C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/MSBuild/Current/Bin/MSBuild.exe", + "type": "process", + "args": [ + "/target:Build", + "/restore:True", + "/p:RestoreSources=https://artifactory.intra.infineon.com/artifactory/api/nuget/ngt-fi-package-main-vir/%3Bhttps://packagemanagement.eu.infineon.com:4430/api/v2/%3Bhttps://api.nuget.org/v3/index.json", + "/detailedsummary", + "/consoleloggerparameters:PerformanceSummary;ErrorsOnly;", + "/property:Configuration=Debug;TargetFrameworkVersion=v4.8", + "Fab2ApprovalSystem.csproj" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/App_Start/.editorconfig b/Fab2ApprovalSystem/App_Start/.editorconfig new file mode 100644 index 0000000..d6454b1 --- /dev/null +++ b/Fab2ApprovalSystem/App_Start/.editorconfig @@ -0,0 +1,31 @@ + +#### .NET Coding Conventions #### + +# Organize usings +dotnet_separate_import_directive_groups = true +dotnet_sort_system_directives_first = true + +# New line preferences +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false +csharp_style_allow_embedded_statements_on_same_line_experimental = true + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = false +csharp_new_line_before_else = false +csharp_new_line_before_finally = false +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = none +csharp_new_line_between_query_expression_clauses = true + +#### + +insert_final_newline = false +csharp_style_namespace_declarations = file_scoped:warning +dotnet_diagnostic.IDE0161.severity = warning # Question - Namespace declaration preferences +dotnet_diagnostic.IDE2000.severity = error # IDE2000: Allow multiple blank lines \ No newline at end of file diff --git a/Fab2ApprovalSystem/App_Start/BundleConfig.cs b/Fab2ApprovalSystem/App_Start/BundleConfig.cs index 519772e..352e365 100644 --- a/Fab2ApprovalSystem/App_Start/BundleConfig.cs +++ b/Fab2ApprovalSystem/App_Start/BundleConfig.cs @@ -1,66 +1,58 @@ using System.Web; using System.Web.Optimization; -namespace Fab2ApprovalSystem -{ - public class BundleConfig - { - // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 - public static void RegisterBundles(BundleCollection bundles) - { - bundles.Add(new ScriptBundle("~/bundles/jquery").Include( - "~/Scripts/jquery-{version}.js", - "~/Scripts/jquery-ui-{version}.js") - ); +namespace Fab2ApprovalSystem; - //bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( - // "~/Scripts/jquery.validate*")); +public class BundleConfig { + // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 + public static void RegisterBundles(BundleCollection bundles) { + bundles.Add(new ScriptBundle("~/bundles/jquery").Include( + "~/Scripts/jquery-{version}.js", + "~/Scripts/jquery-ui-{version}.js") + ); - bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( - "~/Scripts/jquery.unobtrusive*", - "~/Scripts/jquery.validate*")); + //bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( + // "~/Scripts/jquery.validate*")); - // Use the development version of Modernizr to develop with and learn from. Then, when you're - // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. - bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( - "~/Scripts/modernizr-*")); + bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( + "~/Scripts/jquery.unobtrusive*", + "~/Scripts/jquery.validate*")); - bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( - "~/Scripts/bootstrap.js", - "~/Scripts/respond.min.js", - "~/Scripts/common.js")); + // Use the development version of Modernizr to develop with and learn from. Then, when you're + // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. + bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( + "~/Scripts/modernizr-*")); + bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( + "~/Scripts/bootstrap.js", + "~/Scripts/respond.min.js", + "~/Scripts/common.js")); - bundles.Add(new ScriptBundle("~/bundles/kendo").Include( - "~/Scripts/kendo/kendo.all.min.js", - "~/Scripts/kendo/kendo.aspnetmvc.min.js")); + bundles.Add(new ScriptBundle("~/bundles/kendo").Include( + "~/Scripts/kendo/kendo.all.min.js", + "~/Scripts/kendo/kendo.aspnetmvc.min.js")); - bundles.Add(new StyleBundle("~/Content/kendo/css").Include( - "~/Content/kendo/kendo.common-bootstrap.min.css", - "~/Content/kendo/kendo.bootstrap.min.css")); + bundles.Add(new StyleBundle("~/Content/kendo/css").Include( + "~/Content/kendo/kendo.common-bootstrap.min.css", + "~/Content/kendo/kendo.bootstrap.min.css")); - bundles.Add(new StyleBundle("~/Content/jqw/css").Include( - "~/Scripts/jqwidgets/styles/jqx.base.css", - "~/Scripts/jqwidgets/styles/jqx.energyblue.css", - "~/Scripts/jqwidgets/styles/jqx.arctic.css", - "~/Scripts/jqwidgets/styles/jqx.energyblue.css")); + bundles.Add(new StyleBundle("~/Content/jqw/css").Include( + "~/Scripts/jqwidgets/styles/jqx.base.css", + "~/Scripts/jqwidgets/styles/jqx.energyblue.css", + "~/Scripts/jqwidgets/styles/jqx.arctic.css", + "~/Scripts/jqwidgets/styles/jqx.energyblue.css")); + bundles.Add(new ScriptBundle("~/Content/jqw/jq").Include( + "~/Scripts/jqwidgets/jqxcore.js", + "~/Scripts/jqwidgets/jqxdata.js", + "~/Scripts/jqwidgets/jqxbuttons.js", + "~/Scripts/jqwidgets/jqxscrollbar.js", + "~/Scripts/jqwidgets/jqxlistbox.js", + "~/Scripts/jqwidgets/jqxpanel.js", + "~/Scripts/jqwidgets/jqxtree.js")); - bundles.Add(new ScriptBundle("~/Content/jqw/jq").Include( - "~/Scripts/jqwidgets/jqxcore.js", - "~/Scripts/jqwidgets/jqxdata.js", - "~/Scripts/jqwidgets/jqxbuttons.js", - "~/Scripts/jqwidgets/jqxscrollbar.js", - "~/Scripts/jqwidgets/jqxlistbox.js", - "~/Scripts/jqwidgets/jqxpanel.js", - "~/Scripts/jqwidgets/jqxtree.js")); - - - - - bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.min.css", - "~/Content/site.css", - "~/Content/jquery-ui.css")); - } + bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.min.css", + "~/Content/site.css", + "~/Content/jquery-ui.css")); } -} +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/App_Start/FilterConfig.cs b/Fab2ApprovalSystem/App_Start/FilterConfig.cs index 263e35c..ebf4bd4 100644 --- a/Fab2ApprovalSystem/App_Start/FilterConfig.cs +++ b/Fab2ApprovalSystem/App_Start/FilterConfig.cs @@ -1,13 +1,10 @@ using System.Web; using System.Web.Mvc; -namespace Fab2ApprovalSystem -{ - public class FilterConfig - { - public static void RegisterGlobalFilters(GlobalFilterCollection filters) - { - filters.Add(new HandleErrorAttribute()); - } +namespace Fab2ApprovalSystem; + +public class FilterConfig { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) { + filters.Add(new HandleErrorAttribute()); } -} +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/App_Start/RouteConfig.cs b/Fab2ApprovalSystem/App_Start/RouteConfig.cs index 1cfc3a6..d572936 100644 --- a/Fab2ApprovalSystem/App_Start/RouteConfig.cs +++ b/Fab2ApprovalSystem/App_Start/RouteConfig.cs @@ -6,27 +6,24 @@ using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; -namespace Fab2ApprovalSystem -{ - public class RouteConfig - { - public static void RegisterRoutes(RouteCollection routes) - { - routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); +namespace Fab2ApprovalSystem; - routes.MapRoute( - name: "Default", - url: "{controller}/{action}/{id}", - // fixing hyperlinks so that the login page will redirect to them - // set the default route to the desired landing page, instead of the login page - // otherwise MVC generates the wrong form action url - defaults: new { controller = "Home", action = "MyTasks", id = UrlParameter.Optional } - ); - //routes.MapHttpRoute( - // name: "ApiRoute", - // routeTemplate: "api/{controller}/{id}", - // defaults: new { id = RouteParameter.Optional } - //); - } +public class RouteConfig { + public static void RegisterRoutes(RouteCollection routes) { + routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); + + routes.MapRoute( + name: "Default", + url: "{controller}/{action}/{id}", + // fixing hyperlinks so that the login page will redirect to them + // set the default route to the desired landing page, instead of the login page + // otherwise MVC generates the wrong form action url + defaults: new { controller = "Home", action = "MyTasks", id = UrlParameter.Optional } + ); + //routes.MapHttpRoute( + // name: "ApiRoute", + // routeTemplate: "api/{controller}/{id}", + // defaults: new { id = RouteParameter.Optional } + //); } -} +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/App_Start/Startup.Auth.cs b/Fab2ApprovalSystem/App_Start/Startup.Auth.cs index 0eb7843..29dcc8b 100644 --- a/Fab2ApprovalSystem/App_Start/Startup.Auth.cs +++ b/Fab2ApprovalSystem/App_Start/Startup.Auth.cs @@ -1,38 +1,35 @@ using Microsoft.AspNet.Identity; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; + using Owin; -namespace Fab2ApprovalSystem -{ - public partial class Startup - { - // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 - public void ConfigureAuth(IAppBuilder app) - { - // Enable the application to use a cookie to store information for the signed in user - app.UseCookieAuthentication(new CookieAuthenticationOptions - { - AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, - LoginPath = new PathString("/Account/Login") - }); - // Use a cookie to temporarily store information about a user logging in with a third party login provider - // app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); +namespace Fab2ApprovalSystem; - // Uncomment the following lines to enable logging in with third party login providers - //app.UseMicrosoftAccountAuthentication( - // clientId: "", - // clientSecret: ""); +public partial class Startup { + // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 + public void ConfigureAuth(IAppBuilder app) { + // Enable the application to use a cookie to store information for the signed in user + app.UseCookieAuthentication(new CookieAuthenticationOptions { + AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, + LoginPath = new PathString("/Account/Login") + }); + // Use a cookie to temporarily store information about a user logging in with a third party login provider + // app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); - //app.UseTwitterAuthentication( - // consumerKey: "", - // consumerSecret: ""); + // Uncomment the following lines to enable logging in with third party login providers + //app.UseMicrosoftAccountAuthentication( + // clientId: "", + // clientSecret: ""); - //app.UseFacebookAuthentication( - // appId: "", - // appSecret: ""); + //app.UseTwitterAuthentication( + // consumerKey: "", + // consumerSecret: ""); - //app.UseGoogleAuthentication(); - } + //app.UseFacebookAuthentication( + // appId: "", + // appSecret: ""); + + //app.UseGoogleAuthentication(); } -} +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/App_Start/WebApiConfig.cs b/Fab2ApprovalSystem/App_Start/WebApiConfig.cs index 1343595..b618fc8 100644 --- a/Fab2ApprovalSystem/App_Start/WebApiConfig.cs +++ b/Fab2ApprovalSystem/App_Start/WebApiConfig.cs @@ -1,17 +1,15 @@ using System.Web.Http; -namespace Fab2ApprovalSystem { - public static class WebApiConfig - { - public static void Register(HttpConfiguration config) - { - config.MapHttpAttributeRoutes(); +namespace Fab2ApprovalSystem; - config.Routes.MapHttpRoute( - name: "DefaultApi", - routeTemplate: "api/{controller}/{id}", - defaults: new { id = RouteParameter.Optional } - ); - } +public static class WebApiConfig { + public static void Register(HttpConfiguration config) { + config.MapHttpAttributeRoutes(); + + config.Routes.MapHttpRoute( + name: "DefaultApi", + routeTemplate: "api/{controller}/{id}", + defaults: new { id = RouteParameter.Optional } + ); } -} +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/.editorconfig b/Fab2ApprovalSystem/Controllers/.editorconfig new file mode 100644 index 0000000..d6454b1 --- /dev/null +++ b/Fab2ApprovalSystem/Controllers/.editorconfig @@ -0,0 +1,31 @@ + +#### .NET Coding Conventions #### + +# Organize usings +dotnet_separate_import_directive_groups = true +dotnet_sort_system_directives_first = true + +# New line preferences +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false +csharp_style_allow_embedded_statements_on_same_line_experimental = true + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = false +csharp_new_line_before_else = false +csharp_new_line_before_finally = false +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = none +csharp_new_line_between_query_expression_clauses = true + +#### + +insert_final_newline = false +csharp_style_namespace_declarations = file_scoped:warning +dotnet_diagnostic.IDE0161.severity = warning # Question - Namespace declaration preferences +dotnet_diagnostic.IDE2000.severity = error # IDE2000: Allow multiple blank lines \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/AccountController.cs b/Fab2ApprovalSystem/Controllers/AccountController.cs index c9d22ac..ca67adc 100644 --- a/Fab2ApprovalSystem/Controllers/AccountController.cs +++ b/Fab2ApprovalSystem/Controllers/AccountController.cs @@ -1,367 +1,334 @@ using System; using System.Collections.Generic; +using System.Net; +using System.Net.Http; using System.Security.Claims; +using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; +using System.Web.Security; + +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; + using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; -using Microsoft.Owin.Security; -using Fab2ApprovalSystem.Models; -using System.Web.Security; -using Fab2ApprovalSystem.Misc; -using Fab2ApprovalSystem.DMO; using Microsoft.AspNet.Identity.Owin; -using System.Net.Http; +using Microsoft.Owin.Security; + using Newtonsoft.Json; -using System.Text; -using System.Net; -namespace Fab2ApprovalSystem.Controllers { - [Authorize] - public class AccountController : Controller { - private string _apiBaseUrl; +namespace Fab2ApprovalSystem.Controllers; - public AccountController() - : this(new UserManager(new UserStore(new ApplicationDbContext()))) { - _apiBaseUrl = Environment.GetEnvironmentVariable("FabApprovalApiBaseUrl") ?? - throw new ArgumentNullException("FabApprovalApiBaseUrl environment variable not found"); - } +[Authorize] +public class AccountController : Controller { + private string _apiBaseUrl; - public AccountController(UserManager userManager) { - UserManager = userManager; - } + public AccountController() + : this(new UserManager(new UserStore(new ApplicationDbContext()))) { + _apiBaseUrl = Environment.GetEnvironmentVariable("FabApprovalApiBaseUrl") ?? + throw new ArgumentNullException("FabApprovalApiBaseUrl environment variable not found"); + } - public UserManager UserManager { get; private set; } + public AccountController(UserManager userManager) { + UserManager = userManager; + } - // - // GET: /Account/Login - [AllowAnonymous] - // try to make the browser refresh the login page every time, to prevent issues with changing usernames and the anti-forgery token validation - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - public ActionResult Login(string returnUrl) { - ViewBag.ReturnUrl = returnUrl; - return View(); - } + public UserManager UserManager { get; private set; } - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - public async Task Login(LoginModel model, string returnUrl) { - try { - bool isLoginValid; + // + // GET: /Account/Login + [AllowAnonymous] + // try to make the browser refresh the login page every time, to prevent issues with changing usernames and the anti-forgery token validation + [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] + public ActionResult Login(string returnUrl) { + ViewBag.ReturnUrl = returnUrl; + return View(); + } - HttpClient httpClient = HttpClientFactory.Create(); - httpClient.BaseAddress = new Uri(_apiBaseUrl); + private void SetSessionParameters(LoginResult loginResult, LoginModel user) { + Session["JWT"] = loginResult.AuthTokens.JwtToken; + Session["RefreshToken"] = loginResult.AuthTokens.RefreshToken; - AuthAttempt authAttempt = new AuthAttempt() { - LoginID = model.LoginID, - Password = model.Password - }; + Session[GlobalVars.SESSION_USERID] = user.UserID; + Session[GlobalVars.SESSION_USERNAME] = user.FullName; + Session[GlobalVars.IS_ADMIN] = user.IsAdmin; + Session[GlobalVars.IS_MANAGER] = user.IsManager; + Session[GlobalVars.OOO] = user.OOO; + Session[GlobalVars.CAN_CREATE_PARTS_REQUEST] = user.IsAdmin || PartsRequestController.CanCreatePartsRequest(user.UserID); - HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "auth/login"); + FormsAuthentication.SetAuthCookie(user.LoginID, true); + } - request.Content = new StringContent(JsonConvert.SerializeObject(authAttempt), - Encoding.UTF8, - "application/json"); + [HttpPost] + [AllowAnonymous] + [ValidateAntiForgeryToken] + public async Task Login(LoginModel model, string returnUrl) { + try { + bool isLoginValid; - HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(request); + HttpClient httpClient = HttpClientFactory.Create(); + httpClient.BaseAddress = new Uri(_apiBaseUrl); - if (!httpResponseMessage.IsSuccessStatusCode) - throw new Exception($"The authentication API failed, because {httpResponseMessage.ReasonPhrase}"); + LoginResult loginResult = await AccountDMO.LoginAsync(httpClient, model); - string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(); - - LoginResult loginResult = JsonConvert.DeserializeObject(responseContent); - -#if(DEBUG) - isLoginValid = true; +#if (DEBUG) + isLoginValid = true; #endif #if (!DEBUG) - bool isIFX = false; - //domainProvider = Membership.Providers["NA_ADMembershipProvider"]; - //isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password); + bool isIFX = false; + //domainProvider = Membership.Providers["NA_ADMembershipProvider"]; + //isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password); - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { - isLoginValid = true; - } else { - isLoginValid = loginResult.IsAuthenticated; - if (isLoginValid) isIFX = true; - - } - -#endif - - if (isLoginValid) { - UserAccountDMO userDMO = new UserAccountDMO(); - LoginModel user = userDMO.GetUser(model.LoginID); - if (user != null) { - Session["JWT"] = loginResult.AuthTokens.JwtToken; - Session["RefreshToken"] = loginResult.AuthTokens.RefreshToken; - - Session[GlobalVars.SESSION_USERID] = user.UserID; - Session[GlobalVars.SESSION_USERNAME] = user.FullName; - Session[GlobalVars.IS_ADMIN] = user.IsAdmin; - Session[GlobalVars.IS_MANAGER] = user.IsManager; - Session[GlobalVars.OOO] = user.OOO; - Session[GlobalVars.CAN_CREATE_PARTS_REQUEST] = user.IsAdmin || PartsRequestController.CanCreatePartsRequest(user.UserID); - - FormsAuthentication.SetAuthCookie(user.LoginID, true); - - return RedirectToLocal(returnUrl); - } else { - ModelState.AddModelError("", "The user name does not exist in the DB. Please contact the System Admin"); - } - } else { - ModelState.AddModelError("", "The user name or password provided is incorrect."); - } - } catch (Exception ex) { - Functions.WriteEvent(@User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message }); - ModelState.AddModelError("", ex.Message); - } - - return View(model); - // If we got this far, something failed, redisplay form - - } - - [HttpPost] - [AllowAnonymous] - public async Task ExternalAuthSetup(AuthAttempt authAttempt) { - try { - bool isLoginValid; - - HttpClient httpClient = HttpClientFactory.Create(); - httpClient.BaseAddress = new Uri(_apiBaseUrl); - - HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "auth/refresh"); - - request.Content = new StringContent(JsonConvert.SerializeObject(authAttempt), - Encoding.UTF8, - "application/json"); - - HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(request); - - if (!httpResponseMessage.IsSuccessStatusCode) - throw new Exception($"The authentication API failed, because {httpResponseMessage.ReasonPhrase}"); - - string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(); - - LoginResult loginResult = JsonConvert.DeserializeObject(responseContent); - -#if(DEBUG) + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { isLoginValid = true; - -#endif -#if (!DEBUG) - - bool isIFX = false; - //domainProvider = Membership.Providers["NA_ADMembershipProvider"]; - //isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password); - - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { - isLoginValid = true; - } else { - isLoginValid = loginResult.IsAuthenticated; - if (isLoginValid) isIFX = true; - - } - -#endif - - if (isLoginValid) { - UserAccountDMO userDMO = new UserAccountDMO(); - LoginModel user = userDMO.GetUser(authAttempt.LoginID); - if (user != null) { - Session["JWT"] = loginResult.AuthTokens.JwtToken; - Session["RefreshToken"] = loginResult.AuthTokens.RefreshToken; - - Session[GlobalVars.SESSION_USERID] = user.UserID; - Session[GlobalVars.SESSION_USERNAME] = user.FullName; - Session[GlobalVars.IS_ADMIN] = user.IsAdmin; - Session[GlobalVars.IS_MANAGER] = user.IsManager; - Session[GlobalVars.OOO] = user.OOO; - Session[GlobalVars.CAN_CREATE_PARTS_REQUEST] = user.IsAdmin || PartsRequestController.CanCreatePartsRequest(user.UserID); - - FormsAuthentication.SetAuthCookie(user.LoginID, true); - - return new HttpResponseMessage(HttpStatusCode.OK); - } else { - ModelState.AddModelError("", "The user name does not exist in the DB. Please contact the System Admin"); - - return new HttpResponseMessage(HttpStatusCode.NotFound); - } - } else { - ModelState.AddModelError("", "The user name or password provided is incorrect."); - - return new HttpResponseMessage(HttpStatusCode.Unauthorized); - } - } catch (Exception ex) { - Functions.WriteEvent(@User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message }); - ModelState.AddModelError("", ex.Message); - - return new HttpResponseMessage(HttpStatusCode.InternalServerError); - } - } - - // GET: /Account/Register - [AllowAnonymous] - public ActionResult Register() { - return View(); - } - - // POST: /Account/Disassociate - [HttpPost] - [ValidateAntiForgeryToken] - public async Task Disassociate(string loginProvider, string providerKey) { - ManageMessageId? message = null; - IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey)); - if (result.Succeeded) { - message = ManageMessageId.RemoveLoginSuccess; } else { - message = ManageMessageId.Error; + isLoginValid = loginResult.IsAuthenticated; + if (isLoginValid) + isIFX = true; + } - return RedirectToAction("Manage", new { Message = message }); + +#endif + + if (isLoginValid) { + UserAccountDMO userDMO = new UserAccountDMO(); + LoginModel user = userDMO.GetUser(model.LoginID); + if (user != null) { + SetSessionParameters(loginResult, user); + + return RedirectToLocal(returnUrl); + } else { + ModelState.AddModelError("", "The user name does not exist in the DB. Please contact the System Admin"); + } + } else { + ModelState.AddModelError("", "The user name or password provided is incorrect."); + } + } catch (Exception ex) { + Functions.WriteEvent(GlobalVars.AppSettings, @User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message }); + ModelState.AddModelError("", ex.Message); } - // GET: /Account/Manage -#pragma warning disable IDE0060 // Remove unused parameter - public ActionResult Manage(ManageMessageId? message) { - return View(); + return View(model); + // If we got this far, something failed, redisplay form + } + + [HttpPost] + [AllowAnonymous] + public async Task ExternalAuthSetup(AuthAttempt authAttempt) { + try { + bool isLoginValid; + + HttpClient httpClient = HttpClientFactory.Create(); + httpClient.BaseAddress = new Uri(_apiBaseUrl); + + LoginResult loginResult = await AccountDMO.ExternalAuthSetupAsync(httpClient, authAttempt); + +#if (DEBUG) + isLoginValid = true; + +#endif +#if (!DEBUG) + + bool isIFX = false; + //domainProvider = Membership.Providers["NA_ADMembershipProvider"]; + //isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password); + + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { + isLoginValid = true; + } else { + isLoginValid = loginResult.IsAuthenticated; + if (isLoginValid) + isIFX = true; + + } + +#endif + + if (isLoginValid) { + UserAccountDMO userDMO = new UserAccountDMO(); + LoginModel user = userDMO.GetUser(authAttempt.LoginID); + if (user != null) { + SetSessionParameters(loginResult, user); + + return new HttpResponseMessage(HttpStatusCode.OK); + } else { + ModelState.AddModelError("", "The user name does not exist in the DB. Please contact the System Admin"); + + return new HttpResponseMessage(HttpStatusCode.NotFound); + } + } else { + ModelState.AddModelError("", "The user name or password provided is incorrect."); + + return new HttpResponseMessage(HttpStatusCode.Unauthorized); + } + } catch (Exception ex) { + Functions.WriteEvent(GlobalVars.AppSettings, @User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message }); + ModelState.AddModelError("", ex.Message); + + return new HttpResponseMessage(HttpStatusCode.InternalServerError); } + } + + // GET: /Account/Register + [AllowAnonymous] + public ActionResult Register() { + return View(); + } + + // POST: /Account/Disassociate + [HttpPost] + [ValidateAntiForgeryToken] + public async Task Disassociate(string loginProvider, string providerKey) { + ManageMessageId? message = null; + IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey)); + if (result.Succeeded) { + message = ManageMessageId.RemoveLoginSuccess; + } else { + message = ManageMessageId.Error; + } + return RedirectToAction("Manage", new { Message = message }); + } + + // GET: /Account/Manage +#pragma warning disable IDE0060 // Remove unused parameter + public ActionResult Manage(ManageMessageId? message) { + return View(); + } #pragma warning restore IDE0060 // Remove unused parameter - // POST: /Account/ExternalLogin - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - public ActionResult ExternalLogin(string provider, string returnUrl) { - // Request a redirect to the external login provider - return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl })); - } + // POST: /Account/ExternalLogin + [HttpPost] + [AllowAnonymous] + [ValidateAntiForgeryToken] + public ActionResult ExternalLogin(string provider, string returnUrl) { + // Request a redirect to the external login provider + return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl })); + } - // POST: /Account/LinkLogin - [HttpPost] - [ValidateAntiForgeryToken] - public ActionResult LinkLogin(string provider) { - // Request a redirect to the external login provider to link a login for the current user - return new ChallengeResult(provider, Url.Action("LinkLoginCallback", "Account"), User.Identity.GetUserId()); - } + // POST: /Account/LinkLogin + [HttpPost] + [ValidateAntiForgeryToken] + public ActionResult LinkLogin(string provider) { + // Request a redirect to the external login provider to link a login for the current user + return new ChallengeResult(provider, Url.Action("LinkLoginCallback", "Account"), User.Identity.GetUserId()); + } - // - // GET: /Account/LinkLoginCallback - public async Task LinkLoginCallback() { - ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); - if (loginInfo == null) { - return RedirectToAction("Manage", new { Message = ManageMessageId.Error }); - } - IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login); - if (result.Succeeded) { - return RedirectToAction("Manage"); - } + // + // GET: /Account/LinkLoginCallback + public async Task LinkLoginCallback() { + ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); + if (loginInfo == null) { return RedirectToAction("Manage", new { Message = ManageMessageId.Error }); } - - // POST: /Account/LogOff - [HttpPost] - [ValidateAntiForgeryToken] - public ActionResult LogOff() { - FormsAuthentication.SignOut(); - return RedirectToAction("Login", "Account"); + IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login); + if (result.Succeeded) { + return RedirectToAction("Manage"); } - - // GET: /Account/ExternalLoginFailure - [AllowAnonymous] - public ActionResult ExternalLoginFailure() { - return View(); - } - - [ChildActionOnly] - public ActionResult RemoveAccountList() { - IList linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId()); - ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1; - return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts); - } - - protected override void Dispose(bool disposing) { - if (disposing && UserManager != null) { - UserManager.Dispose(); - UserManager = null; - } - base.Dispose(disposing); - } - - #region Helpers - // Used for XSRF protection when adding external logins - private const string XsrfKey = "XsrfId"; - - private IAuthenticationManager AuthenticationManager { - get { - return HttpContext.GetOwinContext().Authentication; - } - } - - private async Task SignInAsync(ApplicationUser user, bool isPersistent) { - AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); - ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); - AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); - } - - private void AddErrors(IdentityResult result) { - foreach (string error in result.Errors) { - ModelState.AddModelError("", error); - } - } - - private bool HasPassword() { - ApplicationUser user = UserManager.FindById(User.Identity.GetUserId()); - if (user != null) { - return user.PasswordHash != null; - } - return false; - } - - public enum ManageMessageId { - ChangePasswordSuccess, - SetPasswordSuccess, - RemoveLoginSuccess, - Error - } - - private ActionResult RedirectToLocal(string returnUrl) { - if (Url.IsLocalUrl(returnUrl)) { - return Redirect(returnUrl); - } else { - return RedirectToAction("MyTasks", "Home"); - } - } - - private class ChallengeResult : HttpUnauthorizedResult { - public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { - } - - public ChallengeResult(string provider, string redirectUri, string userId) { - LoginProvider = provider; - RedirectUri = redirectUri; - UserId = userId; - } - - public string LoginProvider { get; set; } - public string RedirectUri { get; set; } - public string UserId { get; set; } - - public override void ExecuteResult(ControllerContext context) { - AuthenticationProperties properties = new AuthenticationProperties() { RedirectUri = RedirectUri }; - if (UserId != null) { - properties.Dictionary[XsrfKey] = UserId; - } - context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); - } - } - #endregion + return RedirectToAction("Manage", new { Message = ManageMessageId.Error }); } -} + + // POST: /Account/LogOff + [HttpPost] + [ValidateAntiForgeryToken] + public ActionResult LogOff() { + FormsAuthentication.SignOut(); + return RedirectToAction("Login", "Account"); + } + + // GET: /Account/ExternalLoginFailure + [AllowAnonymous] + public ActionResult ExternalLoginFailure() { + return View(); + } + + [ChildActionOnly] + public ActionResult RemoveAccountList() { + IList linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId()); + ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1; + return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts); + } + + protected override void Dispose(bool disposing) { + if (disposing && UserManager != null) { + UserManager.Dispose(); + UserManager = null; + } + base.Dispose(disposing); + } + + #region Helpers + // Used for XSRF protection when adding external logins + private const string XsrfKey = "XsrfId"; + + private IAuthenticationManager AuthenticationManager { + get { + return HttpContext.GetOwinContext().Authentication; + } + } + + private async Task SignInAsync(ApplicationUser user, bool isPersistent) { + AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); + ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); + AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); + } + + private void AddErrors(IdentityResult result) { + foreach (string error in result.Errors) { + ModelState.AddModelError("", error); + } + } + + private bool HasPassword() { + ApplicationUser user = UserManager.FindById(User.Identity.GetUserId()); + if (user != null) { + return user.PasswordHash != null; + } + return false; + } + + public enum ManageMessageId { + ChangePasswordSuccess, + SetPasswordSuccess, + RemoveLoginSuccess, + Error + } + + private ActionResult RedirectToLocal(string returnUrl) { + if (Url.IsLocalUrl(returnUrl)) { + return Redirect(returnUrl); + } else { + return RedirectToAction("MyTasks", "Home"); + } + } + + private class ChallengeResult : HttpUnauthorizedResult { + public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { + } + + public ChallengeResult(string provider, string redirectUri, string userId) { + LoginProvider = provider; + RedirectUri = redirectUri; + UserId = userId; + } + + public string LoginProvider { get; set; } + public string RedirectUri { get; set; } + public string UserId { get; set; } + + public override void ExecuteResult(ControllerContext context) { + AuthenticationProperties properties = new AuthenticationProperties() { RedirectUri = RedirectUri }; + if (UserId != null) { + properties.Dictionary[XsrfKey] = UserId; + } + context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); + } + } + #endregion +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/AdminController.cs b/Fab2ApprovalSystem/Controllers/AdminController.cs index 818b432..c51d14b 100644 --- a/Fab2ApprovalSystem/Controllers/AdminController.cs +++ b/Fab2ApprovalSystem/Controllers/AdminController.cs @@ -1,758 +1,399 @@ using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.ViewModels; + +using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; + using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; -using Kendo.Mvc.Extensions; -using Fab2ApprovalSystem.Misc; -using Fab2ApprovalSystem.ViewModels; -namespace Fab2ApprovalSystem.Controllers -{ - [Authorize] - [SessionExpireFilter] - public class AdminController : Controller - { - // GET: /Admin/ - UserAccountDMO userDMO = new UserAccountDMO(); - AdminDMO adminDMO = new AdminDMO(); - TrainingDMO trainingDMO = new TrainingDMO(); - LotDispositionDMO ldDMO = new LotDispositionDMO(); - - /// - /// - /// - /// - public ActionResult Index() - { - - if ((bool)Session[GlobalVars.IS_ADMIN]) - { - var model = userDMO.GetAllUsers(); - ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers(); - return View(model); - } - else - return Content("Not Autthorized"); - } - - /// - /// - /// - /// - public ActionResult AssignRoles() - { - if ((bool)Session[GlobalVars.IS_ADMIN]) - { - ViewBag.ToplevelNode = GetRoles_SubRolesList(); - return View(); - } - else - return Content("Not Autthorized"); - } - - - /// - /// - /// - /// - /// - public ActionResult GetAllUserList([DataSourceRequest] DataSourceRequest request) - { - IEnumerable userlist = userDMO.GetAllActiveUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); - - - } - - - /// - /// For the Administration of the Users - /// - /// - /// - public ActionResult GetGridUserList([DataSourceRequest] DataSourceRequest request) - { - return Json(userDMO.GetAllUsers().ToDataSourceResult(request)); - } - - - /// - /// - /// - /// - /// - public JsonResult GetAllUserListBySubRole(int subRole) - { - IEnumerable userlist = adminDMO.GetAllUsersBySubRole(subRole); - return Json(userlist, JsonRequestBehavior.AllowGet); - } - - /// - /// - /// - /// - public JsonResult AllSubRoles(string showInactiveRoles = "") - { - List roles = adminDMO.GetSubRoles(); - - ParentChildModel parent; - ParentChildModel child = new ParentChildModel(); - - List newRoles = new List(); - foreach (Role r in roles) - { - parent = new ParentChildModel(); - parent.id = r.RoleID; - parent.parentid = -1; - parent.text = r.RoleName; - parent.value = r.RoleID.ToString(); - - foreach (SubRole sr in r.SubRoles) - { - if (sr.Inactive) - { - // hide inactive roles unless parameter says otherwise - if (showInactiveRoles.Equals("true") == false) - continue; - } - - child = new ParentChildModel(); - child.id = sr.SubRoleID; - child.parentid = r.RoleID; - child.text = sr.SubRoleCategoryItem + (sr.Inactive ? " (Inactive)" : ""); - child.value = sr.SubRoleID.ToString(); - newRoles.Add(child); - } - - newRoles.Add(parent); - }; - - - return Json(newRoles, JsonRequestBehavior.AllowGet); - - } - - public ActionResult GetSubRoleListByUserId([DataSourceRequest] DataSourceRequest request, string userId) - { - int userIdInt = Convert.ToInt32(userId); - - return Json(adminDMO.GetUserSubRoles(userIdInt).ToDataSourceResult(request)); - } - - // - /// - ///OBSOLETE FUNCTION BELOW FOR THE KENDO TREEVIEW - /// - /// - private IEnumerable GetRoles_SubRolesList() - { - - List roles = adminDMO.GetSubRoles(); - - - List ToplevelNode = new List(); - List parentList = new List(); - List childList = new List(); - - - TreeViewItemModel parent = new TreeViewItemModel(); - TreeViewItemModel child = new TreeViewItemModel(); - - - foreach (Role r in roles) - { - parent = new TreeViewItemModel(); - parent.HasChildren = true; - parent.Text = r.RoleName; - parent.Id = r.RoleID.ToString(); - - - foreach (SubRole sr in r.SubRoles) - { - child = new TreeViewItemModel(); - child.Text = sr.SubRoleCategoryItem; - child.Id = sr.SubRoleID.ToString(); - - parent.Items.Add(child); - } - - ToplevelNode.Add(parent); - }; - - - - return ToplevelNode; - - } - - - /// - /// - /// - /// - /// - /// - public ActionResult AddUserRoles(int subRole, string users) - { - - adminDMO.AddUserRoles(subRole, users); - return View(); - } - public ActionResult ReplaceUserRoles(int subRole, string users) - { - adminDMO.AddUserRoles(subRole, users); - return Content("Success"); - } - /// - /// - /// - /// - /// - /// - public ActionResult DeleteUserRoles(int subRole, string users) - { - - adminDMO.DeleteUserRoles(subRole, users); - return Content(""); - } - - - // - // GET: /Workflow/Details/5 - public ActionResult Details(int id) - { - return View(); - } - - // - // GET: /Workflow/Create - public ActionResult Create() - { - return View(); - } - - // - // POST: /Workflow/Create - [HttpPost] - public ActionResult Create(FormCollection collection) - { - try - { - // TODO: Add insert logic here - - return RedirectToAction("Index"); - } - catch - { - return View(); - } - } - - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult BatchUpdateUser([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable model) - { - //if (model != null && ModelState.IsValid) - //{ - // userDMO.UpdateUser(model); - //} - - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult UpdateUser([DataSourceRequest] DataSourceRequest request, LoginModel model) - { - if (model != null && ModelState.IsValid) - { - userDMO.UpdateUser(model); - } - - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - - ///// - ///// - ///// - ///// - ///// - ///// - //[AcceptVerbs(HttpVerbs.Post)] - //public ActionResult DeleteUser([DataSourceRequest] DataSourceRequest request, LoginModel model) - //{ - // if (model != null && ModelState.IsValid) - // { - // userDMO.DeleteUser(model); - // //Remove open trainings - // //Get a list of all user assigned trainings. - // List trainingAssignments = trainingDMO.GetTrainingAssignmentsByUserID(model.UserID); - - // //Go Through that list. - // foreach(var trainingAssignment in trainingAssignments) - // { - // //Delete Any document acknowledgements. - // trainingDMO.DeleteTrainingDocAck(trainingAssignment.ID); - // //Delete the training assignment itself - // trainingDMO.DeleteTrainingAssignment(trainingAssignment.ID); - // //Check the parent Training task to set to to complete if applicable. - // if (trainingDMO.CheckTrainingStatus(trainingAssignment.ID)) - // { - - // int TrainingID = trainingDMO.GetTrainingIdByAssignment(trainingAssignment.TrainingID); - // //Set Training status to complete - // trainingDMO.UpdateTrainingStatus(TrainingID); - // } - - // } - - // //Remove user from any Training Groups - // adminDMO.DeleteUserFromAllTrainingGroups(model.UserID); - - // //Remove User from training report notifications - // adminDMO.TrainingReportDeleteUser(model.UserID); - // //Remove user from TECN Expiration Notifications - // adminDMO.TECNExpirationDeleteUser(model.UserID); - // //Get user subroles - // List userSubRoles = adminDMO.GetUserSubRoles(model.UserID); - // //Delete user from any subroles - // foreach (var userSubRole in userSubRoles) - // { - // DeleteUserRoles(userSubRole.SubRoleID, model.UserID.ToString()); - // } - - // } - - - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - /// - /// - /// - /// - /// - /// - - public ActionResult DeleteUser(string userId) - { - LoginModel model = userDMO.GetUserByID(Convert.ToInt32(userId)); - if (model != null) - { - userDMO.DeleteUser(model); - //Remove open trainings - //Get a list of all user assigned trainings. - List trainingAssignments = trainingDMO.GetTrainingAssignmentsByUserID(model.UserID); - - //Go Through that list. - foreach (var trainingAssignment in trainingAssignments) - { - //Delete Any document acknowledgements. - trainingDMO.DeleteTrainingDocAck(trainingAssignment.ID); - //Delete the training assignment itself - trainingDMO.DeleteTrainingAssignment(trainingAssignment.ID); - //Check the parent Training task to set to to complete if applicable. - if (trainingDMO.CheckTrainingStatus(trainingAssignment.ID)) - { - - int TrainingID = trainingAssignment.TrainingID; - //Set Training status to complete - trainingDMO.UpdateTrainingStatus(TrainingID); - } - - } - - //Remove user from any Training Groups - adminDMO.DeleteUserFromAllTrainingGroups(model.UserID); - - //Remove User from training report notifications - adminDMO.TrainingReportDeleteUser(model.UserID); - //Remove user from TECN Expiration Notifications - adminDMO.TECNExpirationDeleteUser(model.UserID); - //Get user subroles - List userSubRoles = adminDMO.GetUserSubRoles(model.UserID); - //Delete user from any subroles - foreach (var userSubRole in userSubRoles) - { - DeleteUserRoles(userSubRole.SubRoleID, model.UserID.ToString()); - } - - } - - - return Content("Success"); - } - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult InsertUser([DataSourceRequest] DataSourceRequest request, LoginModel model) - { - - try - { - if (model != null && ModelState.IsValid) - { - userDMO.InsertUser(model); - } - } - catch (Exception ex) - { - // TODO - throw new Exception(ex.Message); - } - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - - } - - - /// - /// - /// - /// - public ActionResult EnableOOOStatus(int oooUserID, int delegatedTo, DateTime startDate, DateTime endDate) - { - int returnValue = MiscDMO.EnableOOOStatus(oooUserID, delegatedTo, startDate, endDate); - if (returnValue == 3) // the delegator is already a delegator to someone else - { - return Content("3"); - } - else - return Content(""); - - // TODO - Send an email to the OOO person and to the Delegated person - //return View(); - } - - - /// - /// - /// - /// - public void ExpireOOOStatus(int oooUserID) - { - MiscDMO.ExpireOOOStatus(oooUserID); - // TODO - Does it need to send an email - } - public ActionResult ManageTrainingGroups() - { - //List allGroups = GetTrainingGroups(); - //return View(allGroups); - if ((bool)Session[GlobalVars.IS_ADMIN]) - { - ViewBag.AllGroups = GetTrainingGroups(); - return View(); - } - else - return Content("Not Autthorized"); - } - public void RefreshGroups() - { - ViewBag.AllGroups = GetTrainingGroups(); - } - public ActionResult TrainingGroups() - { - List trainingGroups = adminDMO.GetTrainingGroups(); - return PartialView(trainingGroups); - } - public List GetTrainingGroups() - { - - List TrainingGroups = adminDMO.GetTrainingGroups(); - - - //List ToplevelNode = new List(); - //List parentList = new List(); - //List childList = new List(); - - - //TreeViewItemModel parent = new TreeViewItemModel(); - //TreeViewItemModel child = new TreeViewItemModel(); - //parent = new TreeViewItemModel(); - //parent.HasChildren = true; - //parent.Text = "Training Groups"; - - //foreach (TrainingGroup group in TrainingGroups) - //{ - - - // child = new TreeViewItemModel(); - // child.Text = group.TrainingGroupName; - // child.Id = group.TrainingGroupID.ToString(); - // parent.Items.Add(child); - //} - //ToplevelNode.Add(parent); - ////foreach (Role r in roles) - ////{ - //// parent = new TreeViewItemModel(); - //// parent.HasChildren = true; - //// parent.Text = r.RoleName; - //// parent.Id = r.RoleID.ToString(); - - - //// foreach (SubRole sr in r.SubRoles) - //// { - //// child = new TreeViewItemModel(); - //// child.Text = sr.SubRoleCategoryItem; - //// child.Id = sr.SubRoleID.ToString(); - - //// parent.Items.Add(child); - //// } - - //// ToplevelNode.Add(parent); - ////}; - - - - return TrainingGroups; - - } - public ActionResult GetTaskListByUser([DataSourceRequest]DataSourceRequest request, string userId) - { - IEnumerable data = ldDMO.GetTaskList(Convert.ToInt32(userId)); - data = from a in data where a.PendingApprovers != null select a; - return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - public ActionResult GetOpenActionItemsByUser([DataSourceRequest]DataSourceRequest request, string userId) - { - IEnumerable data = ldDMO.GetMyOpenActionItems(Convert.ToInt32(userId)); - return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - public ActionResult AddNewTrainingGroup(string groupName) - { - try - { - adminDMO.AddNewTrainingGroup(groupName); - return Json(new {test = "Succesfully saved" }); - } - catch - { - return Content("Unable to Save Group", "application/json"); - } - - } - public ActionResult DeleteTrainingGroup(int groupID) - { - try - { - adminDMO.DeleteTrainingGroup(groupID); - return Json(new { response = "Successfully Deleted" }); - } - catch - { - return Json(new { response = "Unsuccessfully Deleted" }); - } - } - public ActionResult ViewTrainingGroup(int TrainingGroupID) - { - ViewBag.GroupID = TrainingGroupID; - return View(); - } - public ActionResult TrainingGroupPartial(int TrainingGroupID) - { - ViewBag.AllUsers = userDMO.GetAllActiveUsers(); - ViewBag.TrainingGroupId = TrainingGroupID; - List trainingGroupMembers = adminDMO.GetTrainingGroupMembers(TrainingGroupID); - return PartialView(trainingGroupMembers); - } - public ActionResult AddToGroup(int userId, int groupId) - { - try - { - adminDMO.AddUserToGroup(userId, groupId); - } - catch(Exception e) - { - return Json(new { test = e.Message }); - } - - return Json(new { test = "Succesfully saved" }); - } - public ActionResult DeleteFromGroup(int userId, int groupId) - { - try - { - adminDMO.DeleteFromGroup(userId, groupId); - } - catch (Exception e) - { - return Json(new { test = e.Message }); - } - - return Json(new { test = "Succesfully removed" }); - } - public ActionResult JobSchedulerConfiguration() - { - if ((bool)Session[GlobalVars.IS_ADMIN]) - { - - return View(); - } - else - return Content("Not Autthorized"); - } - public ActionResult TrainingReportConfig() - { - ViewBag.AllUsers = userDMO.GetAllActiveUsers(); - List currentTrainingReportUsersIds = adminDMO.GetTrainingReportUsers(); - List currentTrainingReportUsers = new List(); - - foreach (TrainingReportUser id in currentTrainingReportUsersIds) - { - currentTrainingReportUsers.Add(userDMO.GetUserByID(id.UserId)); - } - ViewBag.CurrentReportUsers = currentTrainingReportUsers; - return PartialView(); - } - public ActionResult TECNNotificationConfig() - { - ViewBag.AllUsers = userDMO.GetAllActiveUsers(); - List currentTECNNotificationUsersIds = adminDMO.GetTECNNotificationUsers(); - List currentTECNNotificationUsers = new List(); - - foreach (TECNNotificationsUser id in currentTECNNotificationUsersIds) - { - currentTECNNotificationUsers.Add(userDMO.GetUserByID(id.UserId)); - } - ViewBag.CurrentReportUsers = currentTECNNotificationUsers; - return PartialView(); - } - public ActionResult AddToTrainingReport(int userId) - { - if ((bool)Session[GlobalVars.IS_ADMIN]) - { - //Check to make sure user is not apart of the group already - bool userExists = false; - //bool userValid = true; - List existingUsers = adminDMO.GetTrainingReportUsers(); - foreach (var item in existingUsers) - { - if (item.UserId == userId) - { - userExists = true; - } - } - //Check if user is valid - var validUser = userDMO.GetUserByID(userId); - - //Add to group - if (!userExists && validUser != null) - { - adminDMO.TrainingReportAddUser(userId); - return Json("Success Added"); - } - else - { - return Content("User either doesn't exist OR is already added"); - } - } - else - { - return Content("Not Autthorized"); - } - } - public ActionResult AddToTECNNotification(int userId) - { - if ((bool)Session[GlobalVars.IS_ADMIN]) - { - //Check to make sure user is not apart of the group already - bool userExists = false; - //bool userValid = true; - List existingUsers = adminDMO.GetTECNNotificationUsers(); - foreach (var item in existingUsers) - { - if (item.UserId == userId) - { - userExists = true; - } - } - //Check if user is valid - var validUser = userDMO.GetUserByID(userId); - - //Add to group - if (!userExists && validUser != null) - { - try - { - adminDMO.TECNExpirationAddUser(userId); - } - - catch (Exception e) - { - string exception = e.Message; - return Content(exception); - } - - - return Json("Success Added"); - } - else - { - return Content("User either doesn't exist OR is already added"); - } - } - else - { - return Content("Not Autthorized"); - } - } - public ActionResult DeleteFromTrainingReport(int userId) - { - if ((bool)Session[GlobalVars.IS_ADMIN]) - { - try - { - adminDMO.TrainingReportDeleteUser(userId); - return Content("Successfully Deleted"); - } - catch - { - return Content("Error while trying to delete"); - } - } - else - { - return Content("Not Autthorized"); - } - } - public ActionResult DeleteFromTECNNotification(int userId) - { - if ((bool)Session[GlobalVars.IS_ADMIN]) - { - try - { - adminDMO.TECNExpirationDeleteUser(userId); - return Content("Successfully Deleted"); - } - catch - { - return Content("Error while trying to delete"); - } - } - else - { - return Content("Not Autthorized"); - } - } - +namespace Fab2ApprovalSystem.Controllers; + +[Authorize] +[SessionExpireFilter] +public class AdminController : Controller { + // GET: /Admin/ + UserAccountDMO userDMO = new UserAccountDMO(); + AdminDMO adminDMO = new AdminDMO(); + TrainingDMO trainingDMO = new TrainingDMO(); + LotDispositionDMO ldDMO; + private readonly AppSettings _AppSettings; + + public AdminController(AppSettings appSettings) { + _AppSettings = appSettings; + ldDMO = new LotDispositionDMO(appSettings); } + public ActionResult Index() { + if ((bool)Session[GlobalVars.IS_ADMIN]) { + var model = userDMO.GetAllUsers(); + ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers(); + return View(model); + } else + return Content("Not Autthorized"); + } - -} + public ActionResult AssignRoles() { + if ((bool)Session[GlobalVars.IS_ADMIN]) { + ViewBag.ToplevelNode = GetRoles_SubRolesList(); + return View(); + } else + return Content("Not Autthorized"); + } + + public ActionResult GetAllUserList([DataSourceRequest] DataSourceRequest request) { + IEnumerable userlist = userDMO.GetAllActiveUsers(); + return Json(userlist, JsonRequestBehavior.AllowGet); + } + + /// + /// For the Administration of the Users + /// + public ActionResult GetGridUserList([DataSourceRequest] DataSourceRequest request) { + return Json(userDMO.GetAllUsers().ToDataSourceResult(request)); + } + + public JsonResult GetAllUserListBySubRole(int subRole) { + IEnumerable userlist = adminDMO.GetAllUsersBySubRole(subRole); + return Json(userlist, JsonRequestBehavior.AllowGet); + } + + public JsonResult AllSubRoles(string showInactiveRoles = "") { + List newRoles = adminDMO.GetAllSubRoles(showInactiveRoles); + + return Json(newRoles, JsonRequestBehavior.AllowGet); + } + + public ActionResult GetSubRoleListByUserId([DataSourceRequest] DataSourceRequest request, string userId) { + int userIdInt = Convert.ToInt32(userId); + + return Json(adminDMO.GetUserSubRoles(userIdInt).ToDataSourceResult(request)); + } + + /// + ///OBSOLETE FUNCTION BELOW FOR THE KENDO TREEVIEW + /// + private IEnumerable GetRoles_SubRolesList() { + List roles = adminDMO.GetSubRoles(); + + List ToplevelNode = new List(); + List parentList = new List(); + List childList = new List(); + + TreeViewItemModel parent = new TreeViewItemModel(); + TreeViewItemModel child = new TreeViewItemModel(); + + foreach (Role r in roles) { + parent = new TreeViewItemModel(); + parent.HasChildren = true; + parent.Text = r.RoleName; + parent.Id = r.RoleID.ToString(); + + foreach (SubRole sr in r.SubRoles) { + child = new TreeViewItemModel(); + child.Text = sr.SubRoleCategoryItem; + child.Id = sr.SubRoleID.ToString(); + + parent.Items.Add(child); + } + + ToplevelNode.Add(parent); + }; + + return ToplevelNode; + } + + public ActionResult AddUserRoles(int subRole, string users) { + adminDMO.AddUserRoles(subRole, users); + return View(); + } + + public ActionResult ReplaceUserRoles(int subRole, string users) { + adminDMO.AddUserRoles(subRole, users); + return Content("Success"); + } + + public ActionResult DeleteUserRoles(int subRole, string users) { + adminDMO.DeleteUserRoles(subRole, users); + return Content(""); + } + + // GET: /Workflow/Details/5 + public ActionResult Details(int id) { + return View(); + } + + // GET: /Workflow/Create + public ActionResult Create() { + return View(); + } + + // POST: /Workflow/Create + [HttpPost] + public ActionResult Create(FormCollection collection) { + try { + // TODO: Add insert logic here + + return RedirectToAction("Index"); + } catch { + return View(); + } + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult BatchUpdateUser([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable model) { + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult UpdateUser([DataSourceRequest] DataSourceRequest request, LoginModel model) { + if (model != null && ModelState.IsValid) { + userDMO.UpdateUser(model); + } + + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult DeleteUser(string userId) { + LoginModel loginModel = userDMO.GetUserByID(Convert.ToInt32(userId)); + adminDMO.DeleteUser(userDMO, trainingDMO, loginModel); + return Content("Success"); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult InsertUser([DataSourceRequest] DataSourceRequest request, LoginModel model) { + try { + if (model != null && ModelState.IsValid) { + userDMO.InsertUser(model); + } + } catch (Exception ex) { + // TODO + throw new Exception(ex.Message); + } + + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult EnableOOOStatus(int oooUserID, int delegatedTo, DateTime startDate, DateTime endDate) { + int returnValue = MiscDMO.EnableOOOStatus(oooUserID, delegatedTo, startDate, endDate); + if (returnValue == 3) // the delegator is already a delegator to someone else + { + return Content("3"); + } else + return Content(""); + + // TODO - Send an email to the OOO person and to the Delegated person + //return View(); + } + + public void ExpireOOOStatus(int oooUserID) { + MiscDMO.ExpireOOOStatus(oooUserID); + // TODO - Does it need to send an email + } + + public ActionResult ManageTrainingGroups() { + //List allGroups = GetTrainingGroups(); + //return View(allGroups); + if ((bool)Session[GlobalVars.IS_ADMIN]) { + ViewBag.AllGroups = GetTrainingGroups(); + return View(); + } else + return Content("Not Autthorized"); + } + + public void RefreshGroups() { + ViewBag.AllGroups = GetTrainingGroups(); + } + + public ActionResult TrainingGroups() { + List trainingGroups = adminDMO.GetTrainingGroups(); + return PartialView(trainingGroups); + } + + public List GetTrainingGroups() { + List TrainingGroups = adminDMO.GetTrainingGroups(); + return TrainingGroups; + } + + public ActionResult GetTaskListByUser([DataSourceRequest] DataSourceRequest request, string userId) { + IEnumerable data = ldDMO.GetTaskList(Convert.ToInt32(userId)); + data = from a in data where a.PendingApprovers != null select a; + return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } + + public ActionResult GetOpenActionItemsByUser([DataSourceRequest] DataSourceRequest request, string userId) { + IEnumerable data = ldDMO.GetMyOpenActionItems(Convert.ToInt32(userId)); + return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } + + public ActionResult AddNewTrainingGroup(string groupName) { + try { + adminDMO.AddNewTrainingGroup(groupName); + return Json(new { test = "Succesfully saved" }); + } catch { + return Content("Unable to Save Group", "application/json"); + } + } + + public ActionResult DeleteTrainingGroup(int groupID) { + try { + adminDMO.DeleteTrainingGroup(groupID); + return Json(new { response = "Successfully Deleted" }); + } catch { + return Json(new { response = "Unsuccessfully Deleted" }); + } + } + + public ActionResult ViewTrainingGroup(int TrainingGroupID) { + ViewBag.GroupID = TrainingGroupID; + return View(); + } + + public ActionResult TrainingGroupPartial(int TrainingGroupID) { + ViewBag.AllUsers = userDMO.GetAllActiveUsers(); + ViewBag.TrainingGroupId = TrainingGroupID; + List trainingGroupMembers = adminDMO.GetTrainingGroupMembers(TrainingGroupID); + return PartialView(trainingGroupMembers); + } + + public ActionResult AddToGroup(int userId, int groupId) { + try { + adminDMO.AddUserToGroup(userId, groupId); + } catch (Exception e) { + return Json(new { test = e.Message }); + } + + return Json(new { test = "Succesfully saved" }); + } + + public ActionResult DeleteFromGroup(int userId, int groupId) { + try { + adminDMO.DeleteFromGroup(userId, groupId); + } catch (Exception e) { + return Json(new { test = e.Message }); + } + + return Json(new { test = "Succesfully removed" }); + } + + public ActionResult JobSchedulerConfiguration() { + if ((bool)Session[GlobalVars.IS_ADMIN]) { + return View(); + } else + return Content("Not Autthorized"); + } + + public ActionResult TrainingReportConfig() { + ViewBag.AllUsers = userDMO.GetAllActiveUsers(); + List currentTrainingReportUsersIds = adminDMO.GetTrainingReportUsers(); + List currentTrainingReportUsers = new List(); + + foreach (TrainingReportUser id in currentTrainingReportUsersIds) { + currentTrainingReportUsers.Add(userDMO.GetUserByID(id.UserId)); + } + ViewBag.CurrentReportUsers = currentTrainingReportUsers; + return PartialView(); + } + + public ActionResult TECNNotificationConfig() { + ViewBag.AllUsers = userDMO.GetAllActiveUsers(); + List currentTECNNotificationUsersIds = adminDMO.GetTECNNotificationUsers(); + List currentTECNNotificationUsers = new List(); + + foreach (TECNNotificationsUser id in currentTECNNotificationUsersIds) { + currentTECNNotificationUsers.Add(userDMO.GetUserByID(id.UserId)); + } + ViewBag.CurrentReportUsers = currentTECNNotificationUsers; + return PartialView(); + } + + public ActionResult AddToTrainingReport(int userId) { + if ((bool)Session[GlobalVars.IS_ADMIN]) { + //Check to make sure user is not apart of the group already + bool userExists = false; + //bool userValid = true; + List existingUsers = adminDMO.GetTrainingReportUsers(); + foreach (var item in existingUsers) { + if (item.UserId == userId) { + userExists = true; + } + } + //Check if user is valid + var validUser = userDMO.GetUserByID(userId); + + //Add to group + if (!userExists && validUser != null) { + adminDMO.TrainingReportAddUser(userId); + return Json("Success Added"); + } else { + return Content("User either doesn't exist OR is already added"); + } + } else { + return Content("Not Autthorized"); + } + } + + public ActionResult AddToTECNNotification(int userId) { + if ((bool)Session[GlobalVars.IS_ADMIN]) { + //Check to make sure user is not apart of the group already + bool userExists = false; + //bool userValid = true; + List existingUsers = adminDMO.GetTECNNotificationUsers(); + foreach (var item in existingUsers) { + if (item.UserId == userId) { + userExists = true; + } + } + //Check if user is valid + var validUser = userDMO.GetUserByID(userId); + + //Add to group + if (!userExists && validUser != null) { + try { + adminDMO.TECNExpirationAddUser(userId); + } catch (Exception e) { + string exception = e.Message; + return Content(exception); + } + + return Json("Success Added"); + } else { + return Content("User either doesn't exist OR is already added"); + } + } else { + return Content("Not Autthorized"); + } + } + + public ActionResult DeleteFromTrainingReport(int userId) { + if ((bool)Session[GlobalVars.IS_ADMIN]) { + try { + adminDMO.TrainingReportDeleteUser(userId); + return Content("Successfully Deleted"); + } catch { + return Content("Error while trying to delete"); + } + } else { + return Content("Not Autthorized"); + } + } + + public ActionResult DeleteFromTECNNotification(int userId) { + if ((bool)Session[GlobalVars.IS_ADMIN]) { + try { + adminDMO.TECNExpirationDeleteUser(userId); + return Content("Successfully Deleted"); + } catch { + return Content("Error while trying to delete"); + } + } else { + return Content("Not Autthorized"); + } + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/AuditController.cs b/Fab2ApprovalSystem/Controllers/AuditController.cs index 671cb0c..69469c8 100644 --- a/Fab2ApprovalSystem/Controllers/AuditController.cs +++ b/Fab2ApprovalSystem/Controllers/AuditController.cs @@ -1,669 +1,310 @@ using System; using System.Collections.Generic; +using System.Configuration; +using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; -using Kendo.Mvc.Extensions; -using Kendo.Mvc.UI; -using Fab2ApprovalSystem.Models; + using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Misc; -using System.IO; -using System.Configuration; +using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Utilities; -namespace Fab2ApprovalSystem.Controllers -{ - [Authorize] - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - [SessionExpireFilter] - public class AuditController : Controller - { - AuditDMO auditDMO = new AuditDMO(); - CorrectiveActionDMO caDMO = new CorrectiveActionDMO(); - UserUtilities adUsers = new UserUtilities(); - // GET: Audit - public ActionResult Index() - { - return View(); +using Kendo.Mvc.Extensions; +using Kendo.Mvc.UI; + +namespace Fab2ApprovalSystem.Controllers; + +[Authorize] +[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +[SessionExpireFilter] +public class AuditController : Controller { + + AuditDMO auditDMO; + CorrectiveActionDMO caDMO; + private readonly AppSettings _AppSettings; + + public AuditController(AppSettings appSettings) { + _AppSettings = appSettings; + auditDMO = new AuditDMO(appSettings); + caDMO = new CorrectiveActionDMO(appSettings); + } + + // GET: Audit + public ActionResult Index() { + return View(); + } + + public ActionResult Create() { + Audit audit = new Audit(); + try { + // TODO: Add insert logic here + + audit.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + auditDMO.InsertAudit(audit); + return RedirectToAction("Edit", new { issueID = audit.AuditNo }); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public ActionResult Edit(int issueID) { + int isITARCompliant = 1; + Audit audit = new Audit(); + + try { + bool isAdmin = (bool)Session[GlobalVars.IS_ADMIN]; + int userId = (int)Session[GlobalVars.SESSION_USERID]; + AuditEdit auditEdit = auditDMO.GetAuditEdit(issueID, audit, isAdmin, userId); + if (auditEdit.RedirectToAction) + return RedirectToAction("ReadOnlyAudit", new { auditNo = audit.AuditNo }); + ViewBag.AuditAreaList = auditEdit.AuditAreaList; + ViewBag.AuditeeNames = auditEdit.AuditeeNames; + ViewBag.AuditFindingCategoryList = auditEdit.AuditFindingCategoryList; + ViewBag.AuditorList = auditEdit.AuditorList; + ViewBag.AuditTypeList = auditEdit.AuditTypeList; + ViewBag.CANoList = auditEdit.CANoList; + ViewBag.Is8DQA = auditEdit.Is8DQA; + ViewBag.IsAdmin = auditEdit.IsAdmin; + ViewBag.IsSubmitter = auditEdit.IsSubmitter; + ViewBag.MesaUsers = auditEdit.MesaUsers; + ViewBag.UserList = auditEdit.UserList; + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Edit - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString }); + throw new Exception(e.Message); } - /// - /// - /// - /// - public ActionResult Create() - { + return View(audit); + } - - Audit audit = new Audit(); - try - { - // TODO: Add insert logic here - - - audit.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; - auditDMO.InsertAudit(audit); - return RedirectToAction("Edit", new { issueID = audit.AuditNo }); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); - throw new Exception(e.Message); - - } + [HttpPost] + public ActionResult Edit(Audit model) { + try { + var data = model; + auditDMO.UpdateAudit(model, (int)Session[GlobalVars.SESSION_USERID]); + } catch (Exception ex) { + return Content(ex.Message); } + return Content("Successfully Saved"); + } - /// - /// - /// - /// - /// - public ActionResult Edit(int issueID) - { - int isITARCompliant = 1; - Audit audit = new Audit(); - - try - { - List userList = auditDMO.Get8DQA(); - ViewBag.MesaUsers = adUsers.GetMesaUsers(); - int QAs = userList.Find(delegate(int al) { return al == (int)Session[GlobalVars.SESSION_USERID]; }); - ViewBag.Is8DQA = "false"; - if (QAs != 0) - { - ViewBag.Is8DQA = "true"; - } - - audit = auditDMO.GetAuditItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); - //transform audit users from string to list, delimited by a comma. - if(audit.Auditees == null || !audit.Auditees.Contains(",")) - { - ViewBag.AuditeeNames = audit.Auditees; - } - else - { - string[] auditeeNames = audit.Auditees.Split(','); - ViewBag.AuditeeNames = auditeeNames.ToList(); - - } - - - - ViewBag.IsSubmitter = false; - if(audit.OriginatorID == (int)Session[GlobalVars.SESSION_USERID]) - { - ViewBag.IsSubmitter = true; - } - if((bool)Session[GlobalVars.IS_ADMIN] != true) - { - ViewBag.IsAdmin = false; - } - else - { - ViewBag.IsAdmin = true; - } - if ((audit.RecordLockIndicator && audit.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) - || audit.AuditStatus != 0 ) //open - { - return RedirectToAction("ReadOnlyAudit", new { auditNo = audit.AuditNo }); - } - if (ViewBag.IsAdmin == false && ViewBag.IsSubmitter == false) - { - return RedirectToAction("ReadOnlyAudit", new { auditNo = audit.AuditNo }); - } - else - { - ViewBag.UserList = auditDMO.GetUserList(); - ViewBag.AuditTypeList = auditDMO.GetAuditTypeList(); - //ViewBag.AuditStandardList = auditDMO.GetAuditStandardList(); - ViewBag.AuditorList = auditDMO.GetAuditorList(); - ViewBag.AuditAreaList = auditDMO.GetAuditAreaList(); - ViewBag.AuditFindingCategoryList = auditDMO.GetAuditFindingCategories(); - ViewBag.CANoList = auditDMO.GetCorrectiveActionNoList(); - } - - - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Edit - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString }); - throw new Exception(e.Message); - - } - - - return View(audit); - + public ActionResult CheckCAStatus(int auditNo) { + int dataCount = -1; + try { + dataCount = auditDMO.GetOpenCACountByAuditNo(auditNo); + } catch (Exception ex) { + throw; } - /// - /// - /// - /// - /// - [HttpPost] - public ActionResult Edit(Audit model) - { - try - { + return Content(dataCount.ToString()); + } - var data = model; - auditDMO.UpdateAudit(model, (int)Session[GlobalVars.SESSION_USERID]); - } - catch (Exception ex) - { - return Content(ex.Message); - } + public ActionResult ReadOnlyAudit(int auditNo) { + Audit audit = new Audit(); + audit = auditDMO.GetAuditItemReadOnly(auditNo, (int)Session[GlobalVars.SESSION_USERID]); - return Content("Successfully Saved"); - } + ViewBag.AuditTypeList = auditDMO.GetAuditTypeList(); + ViewBag.AuditorList = auditDMO.GetAuditorList(); + ViewBag.AuditAreaList = auditDMO.GetAuditAreaList(); + ViewBag.AuditFindingCategoryList = auditDMO.GetAuditFindingCategories(); - /// - /// - /// - /// - /// - public ActionResult CheckCAStatus(int auditNo) - { - int dataCount = -1; - try - { - dataCount = auditDMO.GetOpenCACountByAuditNo(auditNo); - } - catch (Exception ex) - { - throw; - } + return View(audit); + } - return Content(dataCount.ToString()); - - } - - /// - /// - /// - /// - /// - public ActionResult ReadOnlyAudit(int auditNo) - { - Audit audit = new Audit(); - audit = auditDMO.GetAuditItemReadOnly(auditNo, (int)Session[GlobalVars.SESSION_USERID]); - - ViewBag.AuditTypeList = auditDMO.GetAuditTypeList(); - ViewBag.AuditorList = auditDMO.GetAuditorList(); - ViewBag.AuditAreaList = auditDMO.GetAuditAreaList(); - ViewBag.AuditFindingCategoryList = auditDMO.GetAuditFindingCategories(); - - - return View(audit); - } - /// - /// - /// - /// - /// - /// - public ActionResult AuditReportAttachSave(IEnumerable AuditReportFiles, int auditNo) - { - try - { - // The Name of the Upload component is "files" - if (AuditReportFiles != null) - { - foreach (var file in AuditReportFiles) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var ccPhysicalPath = Functions.GetAttachmentFolder() + @"Audit\" + auditNo; - di = new DirectoryInfo(ccPhysicalPath); - if (!di.Exists) - di.Create(); - - - var guid = Guid.NewGuid().ToString(); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"Audit\" + auditNo + @"\", guid + fileExtension); - - - file.SaveAs(physicalPath); - AuditReportAttachment attach = new AuditReportAttachment() - { - AuditNo = auditNo, - FileGUID = guid, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID] - - }; - - - //ccDMO.InsertCCAttachment(attach); - auditDMO.InsertAuditReportAttachment(attach); - } + public ActionResult AuditReportAttachSave(IEnumerable AuditReportFiles, int auditNo) { + try { + // The Name of the Upload component is "files" + if (AuditReportFiles != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in AuditReportFiles) { + auditDMO.AuditReportAttachSave(auditNo, userId, file.FileName, file.InputStream); } } - catch - { - throw; - } - - - return Content(""); + } catch { + throw; } - /// - /// - /// - /// - /// - /// - public ActionResult AuditReportAttachment_Read([DataSourceRequest] DataSourceRequest request, int auditNo) - { - - return Json(auditDMO.GetAuditReportAttachments(auditNo).ToDataSourceResult(request)); - } + return Content(""); + } - + public ActionResult AuditReportAttachment_Read([DataSourceRequest] DataSourceRequest request, int auditNo) { - /// - /// - /// - /// - [HttpPost] - public void DeleteAuditReportAttachment(int attachID) - { - auditDMO.DeleteAuditReportAttachment(attachID); + return Json(auditDMO.GetAuditReportAttachments(auditNo).ToDataSourceResult(request)); + } - - } - /// - /// - /// - /// - /// - /// - public FileResult DownloadAuditReportAttachment(string fileGuid, int auditNo) - { - try - { - string fileName = auditDMO.GetAuditReportAttachmentFileName(fileGuid); + [HttpPost] + public void DeleteAuditReportAttachment(int attachID) { + auditDMO.DeleteAuditReportAttachment(attachID); + } - string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); - - string ecnFolderPath = Functions.GetAttachmentFolder() + "Audit\\" + auditNo.ToString(); - var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); - - var FDir_AppData = Functions.GetAttachmentFolder(); - if (!sDocument.StartsWith(FDir_AppData)) - { - // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder - // and block requests outside like "../web.config" - throw new HttpException(403, "Forbidden"); - } - - if (!System.IO.File.Exists(sDocument)) - { - return null; - //throw new Exception("File not found"); - } - - return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + public FileResult DownloadAuditReportAttachment(string fileGuid, int auditNo) { + try { + string fileName, sDocument; + List results = auditDMO.GetFileNameAndDocument(fileGuid, auditNo); + fileName = results[0]; + sDocument = results[1]; + if (string.IsNullOrEmpty(sDocument)) { + // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder + // and block requests outside like "../web.config" + throw new HttpException(403, "Forbidden"); } - catch - { - // TODO - proces the error - throw; + if (!System.IO.File.Exists(sDocument)) { + return null; + //throw new Exception("File not found"); } + + return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + } catch { + // TODO - proces the error + throw; } + } + public ActionResult GetAuditFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) { + return Json(auditDMO.GetAuditFindingsList(auditNo).ToDataSourceResult(request)); + } - /// - /// - /// - /// - /// - /// - public ActionResult GetAuditFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) - { + public ActionResult InsertAuditFindingsItem(AuditFindings data) { + if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0) { + throw new ArgumentException("You must select add a CA for a Major or Minor finding."); + } else { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + Audit audit = auditDMO.InsertAndGetAudit(caDMO, data, userId); - return Json(auditDMO.GetAuditFindingsList(auditNo).ToDataSourceResult(request)); - } - - - /// - /// - /// - /// - public ActionResult InsertAuditFindingsItem(AuditFindings data) - { - if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0) - { - throw new ArgumentException("You must select add a CA for a Major or Minor finding."); - } - else - { - - Audit audit = new Audit(); - auditDMO.InsertAuditFindingsItem(data); - audit = auditDMO.GetAuditItem(data.AuditNo, (int)Session[GlobalVars.SESSION_USERID]); - - //Transfer Finding Details to CA - if(data.CANo != 0) - { - CorrectiveAction ca = caDMO.GetCAItem(data.CANo, (int)Session[GlobalVars.SESSION_USERID]); - ca.CATitle = data.Title; - ca.CASourceID = 1;//Audit - caDMO.UpdateCorrectiveAction(ca); - } - - - return Json(audit, JsonRequestBehavior.AllowGet); - } - - } - - - /// - /// - /// - /// - public ActionResult UpdateAuditFindingsItem(AuditFindings data) - { - if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0) - { - throw new ArgumentException("You must select add a CA for a Major or Minor finding."); - } - else - { - Audit audit = new Audit(); - auditDMO.UpdateAuditFindingsItem(data); - audit = auditDMO.GetAuditItem(data.AuditNo, (int)Session[GlobalVars.SESSION_USERID]); - - //Transfer Finding Details to CA - if (data.CANo != 0) - { - CorrectiveAction ca = caDMO.GetCAItem(data.CANo, (int)Session[GlobalVars.SESSION_USERID]); - ca.CATitle = data.Title; - ca.CASourceID = 1;//Audit - caDMO.UpdateCorrectiveAction(ca); - } - - return Json(audit, JsonRequestBehavior.AllowGet); - } - } - - - public ActionResult DeleteAuditFindingsItem(int auditFindingsID) - { - var af = auditDMO.GetAuditFindingsByID(auditFindingsID); - auditDMO.DeleteAuditFindingsItem(auditFindingsID); - var audit = auditDMO.GetAuditItem(af.AuditNo, (int)Session[GlobalVars.SESSION_USERID]); return Json(audit, JsonRequestBehavior.AllowGet); } - - /// - /// - /// - /// - public void ReleaseLockOnDocument(int issueID) - { - try - { - auditDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); - } - catch (Exception e) - { - try - { - Functions.WriteEvent(@User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); - } - catch { } - auditDMO.ReleaseLockOnDocument(-1, issueID); - - } - - - } - - - // CA Findings ====================================================================================================================== - - /// - /// - /// - /// - /// - public ActionResult InsertCAFindingsItem(CAFindings data) - { - auditDMO.InsertCAFindings(data); - if (data.ResponsibilityOwnerID != null) - { - // send an email notification - NotifyActionItemOwner(data.AuditNo, data.ECD, data.ResponsibilityOwnerID); - } - - return Content(""); - } - - /// - /// - /// - /// - /// - public ActionResult UpdateCAFindingsItem(CAFindings data) - { - auditDMO.UpdateCAFindings(data); - if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID) - { - NotifyActionItemOwner(data.AuditNo, data.ECD, data.ResponsibilityOwnerID); - } - - return Content(""); - } - - /// - /// - /// - /// - /// - /// - public ActionResult GetCAFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) - { - - return Json(auditDMO.GetCAFindingsList(auditNo).ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - /// - public ActionResult GetCAFindingsItemAttachments([DataSourceRequest] DataSourceRequest request, int caFindingsID) - { - - return Json(auditDMO.GetCAFindingsItemAttachments(caFindingsID).ToDataSourceResult(request)); - } - - - - /// - /// - /// - /// - /// - public ActionResult GetCAFindingsItem(int caFindingsID) - { - var model = new CAFindings(); - model = auditDMO.GetCAFindingsItem(caFindingsID); - - return PartialView("_CAFindingsAttachment", model); - } - - - /// - /// - /// - /// - [HttpPost] - public void DeleteCAFindingsItem(int caFindingsID) - { - auditDMO.DeleteCAFindingsItem(caFindingsID); - } - - /// - /// - /// - /// - /// - /// - /// - public ActionResult SaveCAFindings_Attachemnt(IEnumerable CAFindings_Attachemnt, int caFindingsID, int auditNo) - { - try - { - // The Name of the Upload component is "files" - if (CAFindings_Attachemnt != null) - { - foreach (var file in CAFindings_Attachemnt) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var ccPhysicalPath = Functions.GetAttachmentFolder() + @"Audit\" + auditNo; - di = new DirectoryInfo(ccPhysicalPath); - if (!di.Exists) - di.Create(); - - - var guid = Guid.NewGuid().ToString(); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"Audit\" + auditNo + @"\", guid + fileExtension); - - - file.SaveAs(physicalPath); - AuditReportAttachment attach = new AuditReportAttachment() - { - CAFindingsID = caFindingsID, - AuditNo = auditNo, - FileGUID = guid, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID] - - }; - - - auditDMO.InsertAuditReportAttachment(attach); - } - } - } - catch - { - throw; - } - - - return Content(""); - } - - - /// - /// - /// - /// - /// - public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID) - { - try - { - string emailSentList = ""; - - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - string email = MiscDMO.GetEmail(responsibleOwnerID); - - string emailTemplate = "CorrectiveActionFindingAssigned.txt"; - string userEmail = string.Empty; - string subject = "5s/CA Findings"; - string senderName = "CorrectiveAction"; - - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = Functions.ReturnAuditNoStringFormat(issueID); - emailparams[1] = dueDate.ToString(); - emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.Audit); - emailparams[3] = GlobalVars.hostURL; - emailparams[4] = issueID.ToString(); - userEmail = email; - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - emailSentList += email + ","; - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 5S/CA Findings" + ":" + email }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 5s/CAFindings:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n 5s/CAFindings - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "5s/CAFindings Notification - " + exceptionString }); - //throw e; - - - } - - } - public ActionResult IsCAAssignedToAudit(int caNo, int auditNo) - { - return Content(auditDMO.IsCAAssignedToAudit(caNo, auditNo).ToString()); - } - - } -} + + public ActionResult UpdateAuditFindingsItem(AuditFindings data) { + if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0) { + throw new ArgumentException("You must select add a CA for a Major or Minor finding."); + } else { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + Audit audit = auditDMO.UpdateAndGetAudit(caDMO, data, userId); + + return Json(audit, JsonRequestBehavior.AllowGet); + } + } + + public ActionResult DeleteAuditFindingsItem(int auditFindingsID) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + Audit audit = auditDMO.DeleteAndGetAudit(auditFindingsID, userId); + return Json(audit, JsonRequestBehavior.AllowGet); + } + + public void ReleaseLockOnDocument(int issueID) { + try { + auditDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); + } catch (Exception e) { + try { + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + } catch { } + auditDMO.ReleaseLockOnDocument(-1, issueID); + } + } + + // CA Findings ====================================================================================================================== + + public ActionResult InsertCAFindingsItem(CAFindings data) { + auditDMO.InsertCAFindings(data); + if (data.ResponsibilityOwnerID != null) { + // send an email notification + NotifyActionItemOwner(data.AuditNo, data.ECD, data.ResponsibilityOwnerID); + } + + return Content(""); + } + + public ActionResult UpdateCAFindingsItem(CAFindings data) { + auditDMO.UpdateCAFindings(data); + if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID) { + NotifyActionItemOwner(data.AuditNo, data.ECD, data.ResponsibilityOwnerID); + } + + return Content(""); + } + + public ActionResult GetCAFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) { + return Json(auditDMO.GetCAFindingsList(auditNo).ToDataSourceResult(request)); + } + + public ActionResult GetCAFindingsItemAttachments([DataSourceRequest] DataSourceRequest request, int caFindingsID) { + return Json(auditDMO.GetCAFindingsItemAttachments(caFindingsID).ToDataSourceResult(request)); + } + + public ActionResult GetCAFindingsItem(int caFindingsID) { + var model = new CAFindings(); + model = auditDMO.GetCAFindingsItem(caFindingsID); + + return PartialView("_CAFindingsAttachment", model); + } + + [HttpPost] + public void DeleteCAFindingsItem(int caFindingsID) { + auditDMO.DeleteCAFindingsItem(caFindingsID); + } + + public ActionResult SaveCAFindings_Attachemnt(IEnumerable CAFindings_Attachemnt, int caFindingsID, int auditNo) { + try { + // The Name of the Upload component is "files" + if (CAFindings_Attachemnt != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in CAFindings_Attachemnt) { + auditDMO.SaveAndInsert(caFindingsID, auditNo, userId, file.FileName, file.InputStream); + } + } + } catch { + throw; + } + + return Content(""); + } + + public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID) { + try { + string emailTemplatesPath = ConfigurationManager.AppSettings["EmailTemplatesPath"]; + string email = auditDMO.NotifyActionItemOwner(issueID, dueDate, responsibleOwnerID, emailTemplatesPath); + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 5S/CA Findings" + ":" + email }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 5s/CAFindings:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 5s/CAFindings - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "5s/CAFindings Notification - " + exceptionString }); + //throw e; + } + } + + public ActionResult IsCAAssignedToAudit(int caNo, int auditNo) { + return Content(auditDMO.IsCAAssignedToAudit(caNo, auditNo).ToString()); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/ChangeControlController.cs b/Fab2ApprovalSystem/Controllers/ChangeControlController.cs index 7996fc8..cd2c719 100644 --- a/Fab2ApprovalSystem/Controllers/ChangeControlController.cs +++ b/Fab2ApprovalSystem/Controllers/ChangeControlController.cs @@ -1,1406 +1,806 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using Fab2ApprovalSystem.ViewModels; using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; -using System.IO; +using Fab2ApprovalSystem.ViewModels; + using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Web; +using System.Web.Mvc; using System.Web.Services; -namespace Fab2ApprovalSystem.Controllers -{ - [Authorize] - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - [SessionExpireFilter] - public class ChangeControlController : Controller - { - // - // GET: /ChangeControl/ - ChangeControlDMO ccDMO = new ChangeControlDMO(); - public ActionResult Index() - { - return View(); +namespace Fab2ApprovalSystem.Controllers; + +[Authorize] +[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +[SessionExpireFilter] +public class ChangeControlController : Controller { + + ChangeControlDMO ccDMO; + private readonly AppSettings _AppSettings; + + public ChangeControlController(AppSettings appSettings) { + _AppSettings = appSettings; + ccDMO = new ChangeControlDMO(appSettings); + } + + public ActionResult Index() { + return View(); + } + + public ActionResult Create() { + ChangeControlViewModel cc = new ChangeControlViewModel(); + try { + cc.OwnerID = (int)Session[GlobalVars.SESSION_USERID]; + ccDMO.InsertChangeControl(cc); + return RedirectToAction("Edit", new { issueID = cc.PlanNumber }); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + cc.PlanNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Create - Change Control\r\n" + cc.PlanNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = cc.PlanNumber, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "Create - " + exceptionString }); + throw new Exception(e.Message); } + } + public ActionResult Edit(int issueID) { + int isITARCompliant = 1; + ChangeControlViewModel cc = new ChangeControlViewModel(); + cc = ccDMO.GetChangeControlRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - public ActionResult Create() - { - - - ChangeControlViewModel cc = new ChangeControlViewModel(); - try - { - cc.OwnerID = (int)Session[GlobalVars.SESSION_USERID]; - ccDMO.InsertChangeControl(cc); - return RedirectToAction("Edit", new { issueID = cc.PlanNumber }); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + cc.PlanNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Create - Change Control\r\n" + cc.PlanNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = cc.PlanNumber, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "Create - " + exceptionString }); - throw new Exception(e.Message); - - } + List userList = MiscDMO.GetApproversListByDocument(cc.PlanNumber, cc.CurrentStep, (int)GlobalVars.DocumentType.ChangeControl); + ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (appUser != null) { + ViewBag.IsApprover = "true"; } + //TODO locked functionality - - /// - /// - /// - /// - /// - public ActionResult Edit(int issueID) + if (isITARCompliant == 0) // not ITAR Compliant { - int isITARCompliant = 1; - ChangeControlViewModel cc = new ChangeControlViewModel(); - cc = ccDMO.GetChangeControlRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - List userList = MiscDMO.GetApproversListByDocument(cc.PlanNumber, cc.CurrentStep, (int)GlobalVars.DocumentType.ChangeControl); - ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (appUser != null) - { - ViewBag.IsApprover = "true"; - } - //TODO locked functionality - - - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); - } + return View("UnAuthorizedAccess"); + } else { + if ((int)Session[GlobalVars.SESSION_USERID] == cc.OwnerID) + ViewBag.IsOriginator = "true"; else - { + ViewBag.IsOriginator = "false"; - if ((int)Session[GlobalVars.SESSION_USERID] == cc.OwnerID) - ViewBag.IsOriginator = "true"; - else - ViewBag.IsOriginator = "false"; - - - if ((cc.RecordLockIndicator && cc.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || - cc.ClosedDate != null) - { - return RedirectToAction("ReadOnlyCC", new { issueID = issueID }); - } - else - { - cc = ccDMO.GetChangeControl(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - ViewBag.Attendees = ccDMO.GetUsers(); - ViewBag.Generations = ccDMO.GetGenerations(); - ViewBag.PartNumbers = ccDMO.GetPartNumbers(); - //ViewBag.ToolTypes = ccDMO.GetToolTypes(); - //ViewBag.MeetingList = ccDMO.GetMeetingList(issueID); - ViewBag.Processes = ccDMO.GetProcesses(); - ViewBag.Logistics = ccDMO.GetLogistics(); - ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible(); - ViewBag.Sites = ccDMO.GetSites(); - return View(cc); - } - } - } - - - /// - /// - /// - /// - /// - public ActionResult ReadOnlyCC(int issueID) - { - int isITARCompliant = 1; - ChangeControlViewModel cc = new ChangeControlViewModel(); - cc = ccDMO.GetChangeControlRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - //TODO locked functionality - - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); - } - else - { - ViewBag.MeetingList = ccDMO.GetMeetingList(issueID); + if ((cc.RecordLockIndicator && cc.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || + cc.ClosedDate != null) { + return RedirectToAction("ReadOnlyCC", new { issueID = issueID }); + } else { + cc = ccDMO.GetChangeControl(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ViewBag.Attendees = ccDMO.GetUsers(); ViewBag.Generations = ccDMO.GetGenerations(); ViewBag.PartNumbers = ccDMO.GetPartNumbers(); //ViewBag.ToolTypes = ccDMO.GetToolTypes(); + //ViewBag.MeetingList = ccDMO.GetMeetingList(issueID); ViewBag.Processes = ccDMO.GetProcesses(); ViewBag.Logistics = ccDMO.GetLogistics(); - return View(cc); - - } - } - - - - /// - /// - /// - /// - /// - [HttpPost] - public ActionResult Edit(ChangeControlViewModel model) - { - try - { - - var data = model; - ccDMO.UpdateChangeControl(model, (int)Session[GlobalVars.SESSION_USERID]); ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible(); + ViewBag.Sites = ccDMO.GetSites(); + return View(cc); } - catch (Exception ex) - { - return Content(ex.Message); - } + } + } - return Content("Successfully Saved"); + public ActionResult ReadOnlyCC(int issueID) { + int isITARCompliant = 1; + ChangeControlViewModel cc = new ChangeControlViewModel(); + cc = ccDMO.GetChangeControlRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + //TODO locked functionality + + if (isITARCompliant == 0) // not ITAR Compliant + { + return View("UnAuthorizedAccess"); + } else { + ViewBag.MeetingList = ccDMO.GetMeetingList(issueID); + ViewBag.Generations = ccDMO.GetGenerations(); + ViewBag.PartNumbers = ccDMO.GetPartNumbers(); + //ViewBag.ToolTypes = ccDMO.GetToolTypes(); + ViewBag.Processes = ccDMO.GetProcesses(); + ViewBag.Logistics = ccDMO.GetLogistics(); + return View(cc); + } + } + + [HttpPost] + public ActionResult Edit(ChangeControlViewModel model) { + try { + var data = model; + ccDMO.UpdateChangeControl(model, (int)Session[GlobalVars.SESSION_USERID]); + ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible(); + } catch (Exception ex) { + return Content(ex.Message); } - public int GetUserIDByDisplayName(string displayName) - { - try - { + return Content("Successfully Saved"); + } - var UserList = ccDMO.GetUsers(); + public int GetUserIDByDisplayName(string displayName) { + try { + var UserList = ccDMO.GetUsers(); - int UserID = (from a in UserList where a.AttendeeName.Equals(displayName) select a.AttendeeID).First(); + int UserID = (from a in UserList where a.AttendeeName.Equals(displayName) select a.AttendeeID).First(); - return UserID; - } - catch (Exception ex) - { - return 0; - } + return UserID; + } catch (Exception ex) { + return 0; + } + } + public JsonResult SearchParts(string searchText) { + List partList = MiscDMO.SearchLTParts(searchText.Trim()).Select(x => x.WIPPartData).ToList(); + return Json(partList, JsonRequestBehavior.AllowGet); + } + + public ActionResult GetCCAttachments([DataSourceRequest] DataSourceRequest request, int planNumber) { + return Json(ccDMO.GetCCAttachment(planNumber).ToDataSourceResult(request)); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult UpdateCCAttachment([DataSourceRequest] DataSourceRequest request, CCAttachment model) { + if (model != null && ModelState.IsValid) { + ccDMO.UpdateCCAttachemnt(model); } - /// - /// - /// - /// - /// - public JsonResult SearchParts(string searchText) - { - List partList = MiscDMO.SearchLTParts(searchText.Trim()).Select(x => x.WIPPartData).ToList(); - return Json(partList, JsonRequestBehavior.AllowGet); + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteCCAttachment([DataSourceRequest] DataSourceRequest request, CCAttachment model) { + if (model != null && ModelState.IsValid) { + ccDMO.DeleteCCAttachemnt(model); } + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } - /// - /// - /// - /// - /// - /// - public ActionResult GetCCAttachments([DataSourceRequest] DataSourceRequest request, int planNumber) - { - return Json(ccDMO.GetCCAttachment(planNumber).ToDataSourceResult(request)); + public ActionResult InsertCCAttachmentItem([DataSourceRequest] DataSourceRequest request, CCAttachment model) { + if (model != null && ModelState.IsValid) { + model = ccDMO.InsertCCAttachment(model); } + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult UpdateCCAttachment([DataSourceRequest] DataSourceRequest request, CCAttachment model) - { - - if (model != null && ModelState.IsValid) - { - ccDMO.UpdateCCAttachemnt(model); + public ActionResult AttachSaveCC(IEnumerable files, int planNumber, int attachID) { + // The Name of the Upload component is "files" + if (files != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in files) { + ccDMO.AttachSaveCC(planNumber, attachID, userId, file.FileName, file.InputStream); } + } + return Content(""); + } - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + public ActionResult GetMeetingDecisionSummaryList([DataSourceRequest] DataSourceRequest request, int planNumber) { + return Json(ccDMO.GetMeetingDecisionSummaryList(planNumber).ToDataSourceResult(request)); + } + + public ActionResult GetMeetingAttachments([DataSourceRequest] DataSourceRequest request, int meetingID) { + return Json(ccDMO.GetMeetingAttachments(meetingID).ToDataSourceResult(request)); + } + public ActionResult GetPCRB([DataSourceRequest] DataSourceRequest request, int PlanNumber, string PCRB) { + return Json(ccDMO.GetPCRB(PlanNumber, PCRB).ToDataSourceResult(request)); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult UpdateMeetingAttachmentAttrib([DataSourceRequest] DataSourceRequest request, CCMeetingAttachment model) { + if (model != null && ModelState.IsValid) { + ccDMO.UpdateMeetingAttachmentAttrib(model); } + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteCCAttachment([DataSourceRequest] DataSourceRequest request, CCAttachment model) - { - - if (model != null && ModelState.IsValid) - { - ccDMO.DeleteCCAttachemnt(model); - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteMeetingAttachment([DataSourceRequest] DataSourceRequest request, CCMeetingAttachment model) { + if (model != null && ModelState.IsValid) { + ccDMO.DeleteMeetingAttachemnt(model); } + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } - public ActionResult InsertCCAttachmentItem([DataSourceRequest] DataSourceRequest request, CCAttachment model) - { - - if (model != null && ModelState.IsValid) - { - model = ccDMO.InsertCCAttachment(model); - } - - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult InsertMeetingAttachmentItemAttrib([DataSourceRequest] DataSourceRequest request, CCMeetingAttachment model) { + if (model != null && ModelState.IsValid) { + model = ccDMO.InsertMeetingAttachmentAttrib(model); } + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } - - /// - /// - /// - /// - /// - /// - /// - - public ActionResult AttachSaveCC(IEnumerable files, int planNumber, int attachID) - { - // The Name of the Upload component is "files" - if (files != null) - { - foreach (var file in files) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var ccPhysicalPath = Functions.GetAttachmentFolder() + @"ChangeControl\" + planNumber; - di = new DirectoryInfo(ccPhysicalPath); - if (!di.Exists) - di.Create(); - - - var guid = Guid.NewGuid().ToString(); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"ChangeControl\" + planNumber + @"\", guid + fileExtension); - - - file.SaveAs(physicalPath); - CCAttachment attach = new CCAttachment() - { - ID = attachID, - FileGUID = guid, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID] - //Title = title, - //RequirementsNotes = requirementsNotes - }; - - - //ccDMO.InsertCCAttachment(attach); - ccDMO.UpdateCCAttachmentDocument(attach); - } + public ActionResult AttachSaveMeeting(IEnumerable files, int planNumber, int meetingID, int attachID) { + // The Name of the Upload component is "files" + if (files != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in files) { + ccDMO.AttachSaveMeeting(planNumber, attachID, userId, file.FileName, file.InputStream); } - return Content(""); + } + return Content(""); + } + + public FileResult DownloadCCFile(string fileGuid, int planNumber) { + string fileName = ccDMO.GetCCFileName(fileGuid); + + string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); + + string ecnFolderPath = _AppSettings.AttachmentFolder + "ChangeControl\\" + planNumber.ToString(); + var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); + + var FDir_AppData = _AppSettings.AttachmentFolder; + if (!sDocument.StartsWith(FDir_AppData)) { + // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder + // and block requests outside like "../web.config" + throw new HttpException(403, "Forbidden"); } - - /// - /// - /// - /// - /// - /// - public ActionResult GetMeetingDecisionSummaryList([DataSourceRequest] DataSourceRequest request, int planNumber) - { - return Json(ccDMO.GetMeetingDecisionSummaryList(planNumber).ToDataSourceResult(request)); + if (!System.IO.File.Exists(sDocument)) { + return null; + //throw new Exception("File not found"); } + return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + } - /// - /// - /// - /// - /// - /// - public ActionResult GetMeetingAttachments([DataSourceRequest] DataSourceRequest request, int meetingID) - { - return Json(ccDMO.GetMeetingAttachments(meetingID).ToDataSourceResult(request)); + public ActionResult CreateMeeting(int planNumber) { + try { + int meetingID = ccDMO.InsertMeeting(planNumber); + //return RedirectToAction("EditMeeting", new { meetingID = meetingID }); + return Content(meetingID.ToString()); + //return null; + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + planNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Create - Meeting\r\n" + planNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = planNumber, UserID = @User.Identity.Name, DocumentType = "Meeting", OperationType = "Error", Comments = "Create - " + exceptionString }); + throw new Exception("Error: " + e.Message); } - public ActionResult GetPCRB([DataSourceRequest] DataSourceRequest request, int PlanNumber, string PCRB) - { - return Json(ccDMO.GetPCRB(PlanNumber, PCRB).ToDataSourceResult(request)); + } + + public ActionResult EditMeeting(int meetingID) { + int isITARCompliant = 1; + CCMeeting meeting = new CCMeeting(); + meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); + //TODO locked functionality + List userList = MiscDMO.GetApproversListByDocument(meeting.PlanNumber, meeting.CurrentStep, (int)GlobalVars.DocumentType.ChangeControl); + ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (appUser != null) { + ViewBag.IsApprover = "true"; } - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult UpdateMeetingAttachmentAttrib([DataSourceRequest] DataSourceRequest request, CCMeetingAttachment model) + if (isITARCompliant == 0) // not ITAR Compliant { + return View("UnAuthorizedAccess"); + } else { + if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) + || (meeting.PCRBClosed)) { + return RedirectToAction("ReadOnlyMeeting", new { meetingID = meetingID }); + } else if (meeting.Decision != -1) { + return RedirectToAction("EditMeetingUpdate", new { meetingID = meetingID }); + } else { + ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible(); + ViewBag.Attendees = ccDMO.GetUsers(); + ViewBag.Sites = ccDMO.GetSites(); + ViewBag.PCRValues = ccDMO.GetPCRValues(); + meeting = ccDMO.GetMeeting(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - if (model != null && ModelState.IsValid) - { - ccDMO.UpdateMeetingAttachmentAttrib(model); - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteMeetingAttachment([DataSourceRequest] DataSourceRequest request, CCMeetingAttachment model) - { - - if (model != null && ModelState.IsValid) - { - ccDMO.DeleteMeetingAttachemnt(model); - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult InsertMeetingAttachmentItemAttrib([DataSourceRequest] DataSourceRequest request, CCMeetingAttachment model) - { - - if (model != null && ModelState.IsValid) - { - model = ccDMO.InsertMeetingAttachmentAttrib(model); - } - - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - - - /// - /// - /// - /// - /// - /// - /// - /// - public ActionResult AttachSaveMeeting(IEnumerable files, int planNumber, int meetingID, int attachID) - { - // The Name of the Upload component is "files" - if (files != null) - { - foreach (var file in files) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var ccPhysicalPath = Functions.GetAttachmentFolder() + @"ChangeControl\" + planNumber; - di = new DirectoryInfo(ccPhysicalPath); - if (!di.Exists) - di.Create(); - - - var guid = Guid.NewGuid().ToString(); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"ChangeControl\" + planNumber + @"\", guid + fileExtension); - - - file.SaveAs(physicalPath); - CCMeetingAttachment attach = new CCMeetingAttachment() - { - ID = attachID, - FileGUID = guid, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID] - }; - - - //ccDMO.InsertCCAttachment(attach); - ccDMO.UpdateMeetingAttachmentDocument(attach); - } - } - return Content(""); - } - - /// - /// - /// - /// - /// - /// - public FileResult DownloadCCFile(string fileGuid, int planNumber) - { - - string fileName = ccDMO.GetCCFileName(fileGuid); - - string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); - - string ecnFolderPath = Functions.GetAttachmentFolder() + "ChangeControl\\" + planNumber.ToString(); - var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); - - var FDir_AppData = Functions.GetAttachmentFolder(); - if (!sDocument.StartsWith(FDir_AppData)) - { - // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder - // and block requests outside like "../web.config" - throw new HttpException(403, "Forbidden"); - } - - if (!System.IO.File.Exists(sDocument)) - { - return null; - //throw new Exception("File not found"); - } - - return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); - } - - - /// - /// - /// - /// - /// - public ActionResult CreateMeeting(int planNumber) - { - - try - { - - int meetingID = ccDMO.InsertMeeting(planNumber); - //return RedirectToAction("EditMeeting", new { meetingID = meetingID }); - return Content(meetingID.ToString()); - //return null; - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + planNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Create - Meeting\r\n" + planNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = planNumber, UserID = @User.Identity.Name, DocumentType = "Meeting", OperationType = "Error", Comments = "Create - " + exceptionString }); - throw new Exception("Error: " + e.Message); - - } - - } - - - /// - /// - /// - /// - /// - public ActionResult EditMeeting(int meetingID) - { - - - int isITARCompliant = 1; - CCMeeting meeting = new CCMeeting(); - meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); - //TODO locked functionality - List userList = MiscDMO.GetApproversListByDocument(meeting.PlanNumber, meeting.CurrentStep, (int)GlobalVars.DocumentType.ChangeControl); - ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (appUser != null) - { - ViewBag.IsApprover = "true"; - } - - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); - } - else - { - - if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) - || (meeting.PCRBClosed)) - { - return RedirectToAction("ReadOnlyMeeting", new { meetingID = meetingID }); - } - else if (meeting.Decision != -1) - { - return RedirectToAction("EditMeetingUpdate", new { meetingID = meetingID }); - } - else - { - ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible(); - ViewBag.Attendees = ccDMO.GetUsers(); - ViewBag.Sites = ccDMO.GetSites(); - ViewBag.PCRValues = ccDMO.GetPCRValues(); - meeting = ccDMO.GetMeeting(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - return View(meeting); - } - } - - } - - /// - /// - /// - /// - /// - public ActionResult ReadOnlyMeeting(int meetingID) - { - - - int isITARCompliant = 1; - CCMeeting meeting = new CCMeeting(); - meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); - ViewBag.PCRValues = ccDMO.GetPCRValues(); - - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); - } - else - { return View(meeting); } - } - - - /// - /// - /// - /// - /// - [HttpPost] - public ActionResult EditMeeting(CCMeeting meeting) - { - try - { - ccDMO.UpdateMeeting(meeting); - } - catch (Exception ex) - { - return Content(ex.Message); - } - - return Content("Successfully Saved"); - - - } - - /// - /// - /// - /// - /// - public ActionResult EditMeetingUpdate(int meetingID) - { - - - int isITARCompliant = 1; - CCMeeting meeting = new CCMeeting(); - meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); - ViewBag.PCRValues = ccDMO.GetPCRValues(); - //TODO locked functionality - List userList = MiscDMO.GetApproversListByDocument(meeting.PlanNumber, meeting.CurrentStep, (int)GlobalVars.DocumentType.ChangeControl); - ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (appUser != null) - { - ViewBag.IsApprover = "true"; - } - - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); - } - else - { - - if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) - || (meeting.PCRBClosed)) - { - return RedirectToAction("ReadOnlyMeeting", new { meetingID = meetingID }); - } - else - { - meeting = ccDMO.GetMeeting(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible(); - - return View(meeting); - } - } - - } - - /// - /// - /// - /// - /// - /// - public FileResult DownloadMeetingFile(string fileGuid, int planNumber) - { - - string fileName = ccDMO.GetMeetingFileName(fileGuid); - - string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); - - string ecnFolderPath = Functions.GetAttachmentFolder() + "ChangeControl\\" + planNumber.ToString(); - var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); - - var FDir_AppData = Functions.GetAttachmentFolder(); - if (!sDocument.StartsWith(FDir_AppData)) - { - // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder - // and block requests outside like "../web.config" - throw new HttpException(403, "Forbidden"); - } - - if (!System.IO.File.Exists(sDocument)) - { - return null; - //throw new Exception("File not found"); - } - - return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); - } - - /// - /// - /// - /// - /// - /// - public ActionResult GetDecisionsSummaryList([DataSourceRequest] DataSourceRequest request, int meetingID) - { - return Json(ccDMO.GetDecisionsSummaryList(meetingID).ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - /// - //[AcceptVerbs(HttpVerbs.Post)] - //public ActionResult UpdateDecisionsSummary([DataSourceRequest] DataSourceRequest request, CCDecisionSummary model) - //{ - - // if (model != null && ModelState.IsValid) - // { - // ccDMO.UpdateDecisionSummary(model); - // } - - // //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - - - - /// - /// - /// - /// - /// - /// - public ActionResult UpdateMeetingDecisionNotes(CCDecisionSummary model) - { - try - { - ccDMO.UpdateDecisionSummary(model); - - } - catch (Exception ex) - { - return Content(ex.Message); - } - return Content("Saved Succesfully"); - } - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteDecisionsSummary([DataSourceRequest] DataSourceRequest request, CCDecisionSummary model) - { - - if (model != null && ModelState.IsValid) - { - ccDMO.DeleteDecisionSummary(model); - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - /// - /// - /// - /// - /// - /// - //[AcceptVerbs(HttpVerbs.Post)] - //public ActionResult InsertDecisionsSummary([DataSourceRequest] DataSourceRequest request, CCDecisionSummary model) - //{ - - // if (model != null && ModelState.IsValid) - // { - // model = ccDMO.InsertDecisionSummary(model); - // } - - - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - - - public ActionResult InsertDecisionsSummary(CCDecisionSummary model) - { - try - { - ccDMO.InsertDecisionSummary(model); - - } - catch (Exception ex) - { - return Content(ex.Message); - } - return Content("Saved Succesfully"); - } - - - /// - /// - /// - /// - /// - /// - - public ActionResult UpdateECN_LotDispoLinks(int id, string ecnLinks, string lotDispoLinks) - { - try - { - ccDMO.UpdateDecisionSummaryLinks(id, ecnLinks, lotDispoLinks); - - } - catch (Exception ex) - { - return Content(ex.Message); - } - return Content("Saved Succesfully", "application/json"); - } - public ActionResult GetMeetingList([DataSourceRequest] DataSourceRequest request, int planNumber) - { - var meetingList = ccDMO.GetMeetingList(planNumber); - return Json(meetingList.ToDataSourceResult(request)); - } - /// - /// - /// - /// - /// - /// - /// - public ActionResult GetMeetingAttendees([DataSourceRequest] DataSourceRequest request, int meetingID) - { - return Json(ccDMO.GetMeetingAttendees(meetingID).ToDataSourceResult(request)); - } - public ActionResult GetPCRBAttendees([DataSourceRequest] DataSourceRequest request, int PCRBID) - { - return Json(ccDMO.GetPCRBAttendees(PCRBID).ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - /// - //[AcceptVerbs(HttpVerbs.Post)] - //public ActionResult UpdateMeetingAttendee([DataSourceRequest] DataSourceRequest request, CCMeetingAttendee model) - //{ - - // if (model != null && ModelState.IsValid) - // { - // ccDMO.UpdateMeetingAttendee(model); - // } - - // //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - public void InsertNewMeetingAttendee(string attendeeName, string jobTitle, string siteName) - { - try - { - //ccDMO.InsertNewMeetingAttendee(meetingId, attendeeName, jobTitle, siteName); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - //string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - //Functions.WriteEvent(@User.Identity.Name + "\r\n UpdateMeetingAttendee - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - //EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); - //throw new Exception(e.Message); - } - } - - public void UpdateMeetingAttendee(int id, string attendeeName, string jobTitle, string siteName) - { - int docid = id; - try - { - ccDMO.UpdateMeetingAttendee(id, attendeeName, jobTitle, siteName); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n UpdateMeetingAttendee - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); - throw new Exception(e.Message); - - } - - //return Content(""); - } - [HttpPost] - public void UpdatePCRBAttendee(int id, int attendeeId, string jobTitle, string siteName) - { - int docid = id; - - try - { - ccDMO.UpdatePCRBAttendee(id, attendeeId, jobTitle, siteName); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n UpdateMeetingAttendee - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); - throw new Exception(e.Message); - - } - - //return Content(""); - } - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteMeetingAttendee([DataSourceRequest] DataSourceRequest request, CCMeetingAttendee model) - { - - if (model != null && ModelState.IsValid) - { - ccDMO.DeleteMeetingAttendee(model); - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult InsertMeetingAttendee([DataSourceRequest] DataSourceRequest request,int pcrId, int attendeeId, string jobTitle, string siteName) - { - CCPCRBAttendee newAttendee = new CCPCRBAttendee(); - newAttendee.AttendeeID = attendeeId; - newAttendee.PCRBID = pcrId; - newAttendee.JobTitle = jobTitle; - newAttendee.Location = siteName; - - try - { - - ccDMO.InsertMeetingAttendee(newAttendee); - - - } - catch (Exception ex) - { - return Content(ex.Message.ToString()); - } - - return Content("1"); - - - //return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - - - - - public ActionResult GetMeetingActionItems([DataSourceRequest] DataSourceRequest request, int meetingID) - { - return Json(ccDMO.GetMeetingActionItems(meetingID).ToDataSourceResult(request)); - } - public ActionResult GetPCRBActionItems([DataSourceRequest] DataSourceRequest request, int pcrbID) - { - return Json(ccDMO.GetPCRBActionItems(pcrbID).ToDataSourceResult(request)); - } - - - public ActionResult GetMeetingActionItems_All([DataSourceRequest] DataSourceRequest request, int planNumber) - { - return Json(ccDMO.GetMeetingActionItems_All(planNumber).ToDataSourceResult(request)); - } - - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - //public ActionResult InsertMeetingActionItem([DataSourceRequest] DataSourceRequest request, CCMeetingActionItem model) - //{ - - // if (model != null && ModelState.IsValid) - // { - // ccDMO.InsertMeetingActionItem(model); - // } - - - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - - public ActionResult InsertPCRBActionItem(CCPCRBActionItem model) - { - try - { - if (model != null) - { - ccDMO.InsertPCRBActionItem(model); - } - - - } - catch (Exception ex) - { - return Content(ex.Message.ToString()); - } - - return Content("1"); - } - public ActionResult InsertMeetingActionItem(CCMeetingActionItem model) - { - try - { - if (model != null) - { - ccDMO.InsertMeetingActionItem(model); - } - - - } - catch (Exception ex) - { - return Content(ex.Message.ToString()); - } - - return Content("1"); - } - public ActionResult InsertPCRBAttendee([DataSourceRequest] DataSourceRequest request, int pcrId, int attendeeId, string jobTitle, string siteName) - { - CCPCRBAttendee newAttendee = new CCPCRBAttendee(); - newAttendee.AttendeeID = attendeeId; - newAttendee.PCRBID = pcrId; - newAttendee.JobTitle = jobTitle; - newAttendee.Location = siteName; - - try - { - - ccDMO.InsertPCRBAttendee(newAttendee); - - - } - catch (Exception ex) - { - return Content(ex.Message.ToString()); - } - - return Content("1"); - - - //return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - public ActionResult UpdatePCRBActionItem(CCPCRBActionItem model) - { - try - { - if (model != null) - { - ccDMO.UpdatePCRBActionItem(model); - } - } - catch (Exception ex) - { - return Content(ex.Message.ToString()); - } - - return Content("1"); - } - - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult UpdateMeetingActionItemAll([DataSourceRequest] DataSourceRequest request, CCMeetingActionItemAll model) - { - if (model != null && ModelState.IsValid) - { - model.ClosedBy = (int)Session[GlobalVars.SESSION_USERID]; - ccDMO.UpdateMeetingActionItem_All(model); - } - if (model.ClosedStatus) - model.ClosedDate = DateTime.Now; - else - model.ClosedDate = null; - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - - - public ActionResult UpdateMeetingActionItem(CCMeetingActionItem model) - { - try - { - if (model != null) - { - ccDMO.UpdateMeetingActionItem(model); - } - } - catch (Exception ex) - { - return Content(ex.Message.ToString()); - } - - return Content("1"); - } - - [HttpPost] - public ActionResult ReassignMeetingActionItemResponsiblePersons(int meetingActionItemId, string newResponsiblePersonIDs, string comments) - { - if (Session[GlobalVars.IS_ADMIN] == null) - throw new Exception("Permission denied"); - - try - { - ccDMO.ReassignMeetingActionItemResponsiblePersons(meetingActionItemId, newResponsiblePersonIDs, comments, (int)Session[GlobalVars.SESSION_USERID]); - } - catch (Exception ex) - { - return Content(ex.Message.ToString()); - } - - return Content("1"); - } - - /// - /// - /// - /// - /// - - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteMeetingActionItem([DataSourceRequest] DataSourceRequest request, CCMeetingActionItem model) - { - - if (model != null && ModelState.IsValid) - { - ccDMO.DeleteMeetingActionItem(model); - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - public ActionResult DeletePCRBActionItem([DataSourceRequest] DataSourceRequest request, CCPCRBActionItem model) - { - - if (model != null && ModelState.IsValid) - { - ccDMO.DeletePCRBActionItem(model); - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - /// - /// - /// - /// - public void CompleteCC(int planNumber) - { - int docid = planNumber; - try - { - ccDMO.CompleteCC(planNumber); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n CompleteCC - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "CompleteCC - " + exceptionString }); - throw new Exception(e.Message); - - } - } - - /// - /// - /// - /// - public void CancelCC(int planNumber) - { - int docid = planNumber; - try - { - ccDMO.CancelCC(planNumber); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n CompleteCC - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "CancelCC - " + exceptionString }); - throw new Exception(e.Message); - - } - } - - - public ActionResult AttachSaveActionItem(IEnumerable AIfiles, int planNumber, int attachID) - { - // The Name of the Upload component is "files" - if (AIfiles != null) - { - foreach (var file in AIfiles) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var ccPhysicalPath = Functions.GetAttachmentFolder() + @"ChangeControl\" + planNumber; - di = new DirectoryInfo(ccPhysicalPath); - if (!di.Exists) - di.Create(); - - - var guid = Guid.NewGuid().ToString(); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"ChangeControl\" + planNumber + @"\", guid + fileExtension); - - - file.SaveAs(physicalPath); - CCMeetingActionItemAll attach = new CCMeetingActionItemAll() - { - ID = attachID, - FileGUID = guid, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID] - - }; - - - //ccDMO.InsertCCAttachment(attach); - ccDMO.UpdateActionItemAttachment(attach); - } - } - return Content(""); - } - - - /// - /// - /// - /// - /// - /// - public FileResult DownloadActionItemFile(string fileGuid, int planNumber) - { - - string fileName = ccDMO.GetActionItemFileName(fileGuid); - - string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); - - string ecnFolderPath = Functions.GetAttachmentFolder() + "ChangeControl\\" + planNumber.ToString(); - var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); - - var FDir_AppData = Functions.GetAttachmentFolder(); - if (!sDocument.StartsWith(FDir_AppData)) - { - // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder - // and block requests outside like "../web.config" - throw new HttpException(403, "Forbidden"); - } - - if (!System.IO.File.Exists(sDocument)) - { - return null; - //throw new Exception("File not found"); - } - - return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); - } - - - public void UpdateMeetingNotes(int meetingID, string notes) - { - ccDMO.UpdateMeetingNotes(meetingID, notes); - } - - /// - /// - /// - /// - public void ReleaseLockOnDocument(int planNumber) - { - ccDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], planNumber); - - try - { - ccDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], planNumber); - } - catch (Exception e) - { - - try - { - Functions.WriteEvent(@User.Identity.Name + "\r\n ReleaseLockOnDocument LD\r\n" + planNumber.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); - } - catch { } - ccDMO.ReleaseLockOnDocument(-1, planNumber); - - } - - } - - public JsonResult GetAllUsersList() - { - //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep); - //return Json(userList, JsonRequestBehavior.AllowGet); - - UserAccountDMO userDMO = new UserAccountDMO(); - IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); - - } - - [HttpPost] - public void ReAssignOwnerByAdmin(string planNumber, string comments, int newOwnerId) - { - if (Session[GlobalVars.IS_ADMIN] == null) - throw new Exception("Permission denied"); - - int planNumberInt = 0; - - try - { - // remove non-numeric characters from Plan # then convert to int - planNumberInt = Int32.Parse(new String(planNumber.Where(c => char.IsNumber(c)).ToArray())); - - ccDMO.ReassignOwner(planNumberInt, newOwnerId, comments, (int)Session[GlobalVars.SESSION_USERID]); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim(); - if (exceptionString.Length > 450) exceptionString = exceptionString.Substring(0, 450); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignOwnerByAdmin\r\n" + planNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = planNumberInt, UserID = @User.Identity.Name, DocumentType = "ChangeControl", OperationType = "Error", Comments = "ReAssignOwnerByAdmin - " + exceptionString }); - throw new Exception(e.Message); - } - } - public ActionResult GetPCRBMesaTitle(int issueID) - { - int isItarCompliant = 1; - ChangeControlViewModel cc = ccDMO.GetChangeControlRead(issueID, out isItarCompliant, (int)Session[GlobalVars.SESSION_USERID]); - string content = cc.PlanTitle; - return Content(content); - } - } -} + + public ActionResult ReadOnlyMeeting(int meetingID) { + int isITARCompliant = 1; + CCMeeting meeting = new CCMeeting(); + meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); + ViewBag.PCRValues = ccDMO.GetPCRValues(); + + if (isITARCompliant == 0) // not ITAR Compliant + { + return View("UnAuthorizedAccess"); + } else { + return View(meeting); + } + } + + [HttpPost] + public ActionResult EditMeeting(CCMeeting meeting) { + try { + ccDMO.UpdateMeeting(meeting); + } catch (Exception ex) { + return Content(ex.Message); + } + + return Content("Successfully Saved"); + } + + public ActionResult EditMeetingUpdate(int meetingID) { + int isITARCompliant = 1; + CCMeeting meeting = new CCMeeting(); + meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); + ViewBag.PCRValues = ccDMO.GetPCRValues(); + //TODO locked functionality + List userList = MiscDMO.GetApproversListByDocument(meeting.PlanNumber, meeting.CurrentStep, (int)GlobalVars.DocumentType.ChangeControl); + ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (appUser != null) { + ViewBag.IsApprover = "true"; + } + + if (isITARCompliant == 0) // not ITAR Compliant + { + return View("UnAuthorizedAccess"); + } else { + if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) + || (meeting.PCRBClosed)) { + return RedirectToAction("ReadOnlyMeeting", new { meetingID = meetingID }); + } else { + meeting = ccDMO.GetMeeting(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible(); + + return View(meeting); + } + } + } + + public FileResult DownloadMeetingFile(string fileGuid, int planNumber) { + string fileName = ccDMO.GetMeetingFileName(fileGuid); + + string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); + + string ecnFolderPath = _AppSettings.AttachmentFolder + "ChangeControl\\" + planNumber.ToString(); + var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); + + var FDir_AppData = _AppSettings.AttachmentFolder; + if (!sDocument.StartsWith(FDir_AppData)) { + // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder + // and block requests outside like "../web.config" + throw new HttpException(403, "Forbidden"); + } + + if (!System.IO.File.Exists(sDocument)) { + return null; + //throw new Exception("File not found"); + } + + return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + } + + public ActionResult GetDecisionsSummaryList([DataSourceRequest] DataSourceRequest request, int meetingID) { + return Json(ccDMO.GetDecisionsSummaryList(meetingID).ToDataSourceResult(request)); + } + + public ActionResult UpdateMeetingDecisionNotes(CCDecisionSummary model) { + try { + ccDMO.UpdateDecisionSummary(model); + } catch (Exception ex) { + return Content(ex.Message); + } + return Content("Saved Succesfully"); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteDecisionsSummary([DataSourceRequest] DataSourceRequest request, CCDecisionSummary model) { + if (model != null && ModelState.IsValid) { + ccDMO.DeleteDecisionSummary(model); + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult InsertDecisionsSummary(CCDecisionSummary model) { + try { + ccDMO.InsertDecisionSummary(model); + } catch (Exception ex) { + return Content(ex.Message); + } + return Content("Saved Succesfully"); + } + + public ActionResult UpdateECN_LotDispoLinks(int id, string ecnLinks, string lotDispoLinks) { + try { + ccDMO.UpdateDecisionSummaryLinks(id, ecnLinks, lotDispoLinks); + } catch (Exception ex) { + return Content(ex.Message); + } + return Content("Saved Succesfully", "application/json"); + } + + public ActionResult GetMeetingList([DataSourceRequest] DataSourceRequest request, int planNumber) { + var meetingList = ccDMO.GetMeetingList(planNumber); + return Json(meetingList.ToDataSourceResult(request)); + } + + /// + public ActionResult GetMeetingAttendees([DataSourceRequest] DataSourceRequest request, int meetingID) { + return Json(ccDMO.GetMeetingAttendees(meetingID).ToDataSourceResult(request)); + } + public ActionResult GetPCRBAttendees([DataSourceRequest] DataSourceRequest request, int PCRBID) { + return Json(ccDMO.GetPCRBAttendees(PCRBID).ToDataSourceResult(request)); + } + + public void InsertNewMeetingAttendee(string attendeeName, string jobTitle, string siteName) { + try { + //ccDMO.InsertNewMeetingAttendee(meetingId, attendeeName, jobTitle, siteName); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + //string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + //Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateMeetingAttendee - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + //EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); + //throw new Exception(e.Message); + } + } + + public void UpdateMeetingAttendee(int id, string attendeeName, string jobTitle, string siteName) { + int docid = id; + try { + ccDMO.UpdateMeetingAttendee(id, attendeeName, jobTitle, siteName); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateMeetingAttendee - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); + throw new Exception(e.Message); + } + + //return Content(""); + } + + [HttpPost] + public void UpdatePCRBAttendee(int id, int attendeeId, string jobTitle, string siteName) { + int docid = id; + + try { + ccDMO.UpdatePCRBAttendee(id, attendeeId, jobTitle, siteName); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateMeetingAttendee - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); + throw new Exception(e.Message); + } + + //return Content(""); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteMeetingAttendee([DataSourceRequest] DataSourceRequest request, CCMeetingAttendee model) { + if (model != null && ModelState.IsValid) { + ccDMO.DeleteMeetingAttendee(model); + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult InsertMeetingAttendee([DataSourceRequest] DataSourceRequest request, int pcrId, int attendeeId, string jobTitle, string siteName) { + CCPCRBAttendee newAttendee = new CCPCRBAttendee(); + newAttendee.AttendeeID = attendeeId; + newAttendee.PCRBID = pcrId; + newAttendee.JobTitle = jobTitle; + newAttendee.Location = siteName; + + try { + ccDMO.InsertMeetingAttendee(newAttendee); + } catch (Exception ex) { + return Content(ex.Message.ToString()); + } + + return Content("1"); + + //return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult GetMeetingActionItems([DataSourceRequest] DataSourceRequest request, int meetingID) { + return Json(ccDMO.GetMeetingActionItems(meetingID).ToDataSourceResult(request)); + } + + public ActionResult GetPCRBActionItems([DataSourceRequest] DataSourceRequest request, int pcrbID) { + return Json(ccDMO.GetPCRBActionItems(pcrbID).ToDataSourceResult(request)); + } + + public ActionResult GetMeetingActionItems_All([DataSourceRequest] DataSourceRequest request, int planNumber) { + return Json(ccDMO.GetMeetingActionItems_All(planNumber).ToDataSourceResult(request)); + } + + [AcceptVerbs(HttpVerbs.Post)] + //public ActionResult InsertMeetingActionItem([DataSourceRequest] DataSourceRequest request, CCMeetingActionItem model) + //{ + // if (model != null && ModelState.IsValid) + // { + // ccDMO.InsertMeetingActionItem(model); + // } + + // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + //} + + public ActionResult InsertPCRBActionItem(CCPCRBActionItem model) { + try { + if (model != null) { + ccDMO.InsertPCRBActionItem(model); + } + + } catch (Exception ex) { + return Content(ex.Message.ToString()); + } + + return Content("1"); + } + + public ActionResult InsertMeetingActionItem(CCMeetingActionItem model) { + try { + if (model != null) { + ccDMO.InsertMeetingActionItem(model); + } + + } catch (Exception ex) { + return Content(ex.Message.ToString()); + } + + return Content("1"); + } + + public ActionResult InsertPCRBAttendee([DataSourceRequest] DataSourceRequest request, int pcrId, int attendeeId, string jobTitle, string siteName) { + CCPCRBAttendee newAttendee = new CCPCRBAttendee(); + newAttendee.AttendeeID = attendeeId; + newAttendee.PCRBID = pcrId; + newAttendee.JobTitle = jobTitle; + newAttendee.Location = siteName; + + try { + ccDMO.InsertPCRBAttendee(newAttendee); + } catch (Exception ex) { + return Content(ex.Message.ToString()); + } + + return Content("1"); + + //return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult UpdatePCRBActionItem(CCPCRBActionItem model) { + try { + if (model != null) { + ccDMO.UpdatePCRBActionItem(model); + } + } catch (Exception ex) { + return Content(ex.Message.ToString()); + } + + return Content("1"); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult UpdateMeetingActionItemAll([DataSourceRequest] DataSourceRequest request, CCMeetingActionItemAll model) { + if (model != null && ModelState.IsValid) { + model.ClosedBy = (int)Session[GlobalVars.SESSION_USERID]; + ccDMO.UpdateMeetingActionItem_All(model); + } + if (model.ClosedStatus) + model.ClosedDate = DateTime.Now; + else + model.ClosedDate = null; + + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult UpdateMeetingActionItem(CCMeetingActionItem model) { + try { + if (model != null) { + ccDMO.UpdateMeetingActionItem(model); + } + } catch (Exception ex) { + return Content(ex.Message.ToString()); + } + + return Content("1"); + } + + [HttpPost] + public ActionResult ReassignMeetingActionItemResponsiblePersons(int meetingActionItemId, string newResponsiblePersonIDs, string comments) { + if (Session[GlobalVars.IS_ADMIN] == null) + throw new Exception("Permission denied"); + + try { + ccDMO.ReassignMeetingActionItemResponsiblePersons(meetingActionItemId, newResponsiblePersonIDs, comments, (int)Session[GlobalVars.SESSION_USERID]); + } catch (Exception ex) { + return Content(ex.Message.ToString()); + } + + return Content("1"); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteMeetingActionItem([DataSourceRequest] DataSourceRequest request, CCMeetingActionItem model) { + if (model != null && ModelState.IsValid) { + ccDMO.DeleteMeetingActionItem(model); + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult DeletePCRBActionItem([DataSourceRequest] DataSourceRequest request, CCPCRBActionItem model) { + if (model != null && ModelState.IsValid) { + ccDMO.DeletePCRBActionItem(model); + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public void CompleteCC(int planNumber) { + int docid = planNumber; + try { + ccDMO.CompleteCC(planNumber); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n CompleteCC - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "CompleteCC - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public void CancelCC(int planNumber) { + int docid = planNumber; + try { + ccDMO.CancelCC(planNumber); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n CompleteCC - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "CancelCC - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public ActionResult AttachSaveActionItem(IEnumerable AIfiles, int planNumber, int attachID) { + // The Name of the Upload component is "files" + if (AIfiles != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in AIfiles) { + ccDMO.AttachSaveActionItem(planNumber, attachID, userId, file.FileName, file.InputStream); + } + } + return Content(""); + } + + public FileResult DownloadActionItemFile(string fileGuid, int planNumber) { + string fileName = ccDMO.GetActionItemFileName(fileGuid); + + string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); + + string ecnFolderPath = _AppSettings.AttachmentFolder + "ChangeControl\\" + planNumber.ToString(); + var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); + + var FDir_AppData = _AppSettings.AttachmentFolder; + if (!sDocument.StartsWith(FDir_AppData)) { + // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder + // and block requests outside like "../web.config" + throw new HttpException(403, "Forbidden"); + } + + if (!System.IO.File.Exists(sDocument)) { + return null; + //throw new Exception("File not found"); + } + + return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + } + + public void UpdateMeetingNotes(int meetingID, string notes) { + ccDMO.UpdateMeetingNotes(meetingID, notes); + } + + public void ReleaseLockOnDocument(int planNumber) { + ccDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], planNumber); + + try { + ccDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], planNumber); + } catch (Exception e) { + try { + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument LD\r\n" + planNumber.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + } catch { } + ccDMO.ReleaseLockOnDocument(-1, planNumber); + } + } + + public JsonResult GetAllUsersList() { + //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep); + //return Json(userList, JsonRequestBehavior.AllowGet); + + UserAccountDMO userDMO = new UserAccountDMO(); + IEnumerable userlist = userDMO.GetAllUsers(); + return Json(userlist, JsonRequestBehavior.AllowGet); + } + + [HttpPost] + public void ReAssignOwnerByAdmin(string planNumber, string comments, int newOwnerId) { + if (Session[GlobalVars.IS_ADMIN] == null) + throw new Exception("Permission denied"); + + int planNumberInt = 0; + + try { + // remove non-numeric characters from Plan # then convert to int + planNumberInt = Int32.Parse(new String(planNumber.Where(c => char.IsNumber(c)).ToArray())); + + ccDMO.ReassignOwner(planNumberInt, newOwnerId, comments, (int)Session[GlobalVars.SESSION_USERID]); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim(); + if (exceptionString.Length > 450) + exceptionString = exceptionString.Substring(0, 450); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignOwnerByAdmin\r\n" + planNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = planNumberInt, UserID = @User.Identity.Name, DocumentType = "ChangeControl", OperationType = "Error", Comments = "ReAssignOwnerByAdmin - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public ActionResult GetPCRBMesaTitle(int issueID) { + int isItarCompliant = 1; + ChangeControlViewModel cc = ccDMO.GetChangeControlRead(issueID, out isItarCompliant, (int)Session[GlobalVars.SESSION_USERID]); + string content = cc.PlanTitle; + return Content(content); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/CorrectiveActionController.cs b/Fab2ApprovalSystem/Controllers/CorrectiveActionController.cs index 725f284..224223d 100644 --- a/Fab2ApprovalSystem/Controllers/CorrectiveActionController.cs +++ b/Fab2ApprovalSystem/Controllers/CorrectiveActionController.cs @@ -1,304 +1,120 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.Utilities; +using Fab2ApprovalSystem.ViewModels; + +using Kendo.Mvc.Extensions; +using Kendo.Mvc.UI; + using System; using System.Collections.Generic; +using System.Configuration; +using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; -using Kendo.Mvc.Extensions; -using Kendo.Mvc.UI; -using Fab2ApprovalSystem.Models; -using Fab2ApprovalSystem.DMO; -using Fab2ApprovalSystem.Misc; -using System.IO; -using System.Configuration; -using Fab2ApprovalSystem.ViewModels; -using Fab2ApprovalSystem.Utilities; -namespace Fab2ApprovalSystem.Controllers -{ - [Authorize] - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - [SessionExpireFilter] - public class CorrectiveActionController : Controller - { - CorrectiveActionDMO caDMO = new CorrectiveActionDMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); - UserAccountDMO userDMO = new UserAccountDMO(); - AuditDMO auditDMO = new AuditDMO(); - FileUtilities fileUtilities = new FileUtilities(); +namespace Fab2ApprovalSystem.Controllers; +[Authorize] +[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +[SessionExpireFilter] +public class CorrectiveActionController : Controller { - public ActionResult Index() - { - return View(); + AuditDMO auditDMO; + CorrectiveActionDMO caDMO; + WorkflowDMO wfDMO = new WorkflowDMO(); + private readonly AppSettings _AppSettings; + UserAccountDMO userDMO = new UserAccountDMO(); + FileUtilities fileUtilities = new FileUtilities(); + + public CorrectiveActionController(AppSettings appSettings) { + _AppSettings = appSettings; + auditDMO = new AuditDMO(appSettings); + caDMO = new CorrectiveActionDMO(appSettings); + } + + public ActionResult Index() { + return View(); + } + + public ActionResult Create() { + CorrectiveAction ca = new CorrectiveAction(); + try { + // TODO: Add insert logic here + + ca.RequestorID = (int)Session[GlobalVars.SESSION_USERID]; + caDMO.InsertCA(ca); + return RedirectToAction("Edit", new { issueID = ca.CANo }); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + throw new Exception(e.Message); } + } - public ActionResult Create() - { - - - CorrectiveAction ca = new CorrectiveAction(); - try - { - // TODO: Add insert logic here - - - ca.RequestorID = (int)Session[GlobalVars.SESSION_USERID]; - caDMO.InsertCA(ca); - return RedirectToAction("Edit", new { issueID = ca.CANo }); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); - throw new Exception(e.Message); + public ActionResult CreateFromAudit(string title) { + CorrectiveAction ca = new CorrectiveAction(); + try { + // TODO: Add insert logic here + ca.RequestorID = (int)Session[GlobalVars.SESSION_USERID]; + ca.CASource = "Audit"; + caDMO.InsertCA(ca); + string test = ca.CANoDisp; + return Content((ca.CANo).ToString()); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + throw new Exception(e.Message); } - public ActionResult CreateFromAudit(string title) - { + } + public ActionResult Edit(int issueID) { + CorrectiveAction ca = new CorrectiveAction(); + string s = Functions.ReturnCANoStringFormat(issueID); + try { + List _8DQAList = caDMO.Get8DQA(); - CorrectiveAction ca = new CorrectiveAction(); - try - { - // TODO: Add insert logic here - - - ca.RequestorID = (int)Session[GlobalVars.SESSION_USERID]; - ca.CASource = "Audit"; - caDMO.InsertCA(ca); - string test = ca.CANoDisp; - return Content((ca.CANo).ToString()); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); - throw new Exception(e.Message); - - } - } - - /// - /// - /// - /// - /// - public ActionResult Edit(int issueID) - { - CorrectiveAction ca = new CorrectiveAction(); - string s = Functions.ReturnCANoStringFormat(issueID); - try - { - List _8DQAList = caDMO.Get8DQA(); - - int QAs = _8DQAList.Find(delegate(int al) { return al == (int)Session[GlobalVars.SESSION_USERID]; }); - - ViewBag.Is8DQA = "false"; - if (QAs != 0) - { - ViewBag.Is8DQA = "true"; - } - - ca = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); - - ViewBag.CanCompleteCA = "false"; - if (ca.D1AssigneeID == (int)Session[GlobalVars.SESSION_USERID]) - ViewBag.CanCompleteCA = "true"; - - List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ca.CurrentStep, (int)GlobalVars.DocumentType.CorrectiveAction); - ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (approver == null) - ViewBag.IsApprover = "false"; - else - ViewBag.IsApprover = "true"; - - ViewBag.IsAIAssignee = caDMO.IsAIAssignee((int)Session[GlobalVars.SESSION_USERID], issueID); - ViewBag.IsSectionApprover = caDMO.IsUserSectionApprover(ca.CANo, (int)Session[GlobalVars.SESSION_USERID]); - ViewBag.AuditFindingCategoriesOptions = auditDMO.GetAuditFindingCategories().ToList(); - if(ca.RelatedAudit != null && ca.RelatedAudit > 0) - { - Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, (int)Session[GlobalVars.SESSION_USERID]); - IEnumerable auditFindings = auditDMO.GetAuditFindingsList(audit.AuditNo); - - AuditFindings relatedFinding = (from a in auditFindings where a.CANo == ca.CANo select a).First(); - - string relatedAuditFinding = relatedFinding.Findings; - IEnumerable relatedAuditFindingCatIds = auditDMO.GetAuditFindingCategoryIdsByFindingId(relatedFinding.ID); - string relatedViolatedClause = relatedFinding.ViolatedClause; - - ViewBag.AuditFinding = relatedAuditFinding; - ViewBag.AuditFindingCategories = relatedAuditFindingCatIds; - ViewBag.ViolatedClause = relatedViolatedClause; - } - else - { - ViewBag.AuditFinding = ""; - ViewBag.AuditFindingCategories = ""; - ViewBag.ViolatedClause = ""; - } - - if ((ca.ClosedDate != null) || - // TODO Aproverslist================================================================ - (ca.ClosedDate != null && ViewBag.IsApprover == "false" && ViewBag.IsAIAssignee == "false") || - (ca.RecordLockIndicator && ca.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ca.Status == 11 && ViewBag.IsApprover == "false")) - { - return RedirectToAction("ReadOnlyCA", new { caNo = ca.CANo }); - } - else - { - ViewBag.ECNList = caDMO.GetECNList(); - if (ca.Status == 1 || ca.Status == 2 || ca.Status == 11) - { - //Pulling in the user list which includes inactive users. - ViewBag.UserList = caDMO.GetAllUserList(); - } - else - { - //Pulling in the user list which only includes active users. - ViewBag.UserList = caDMO.GetUserList(); - } - ViewBag.CASourceList = caDMO.GetCASourceList(); - ViewBag.ModuleList = caDMO.GetModuleList(); - ViewBag.D3RiskAssessmentAreas = caDMO.GetD3RiskAssessmentAreas(); - ViewBag.D5D6ImprovementIDs = caDMO.GetD5D6Improvement(); - } - - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Edit - CA\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString }); - throw new Exception(e.Message); + int QAs = _8DQAList.Find(delegate (int al) { return al == (int)Session[GlobalVars.SESSION_USERID]; }); + ViewBag.Is8DQA = "false"; + if (QAs != 0) { + ViewBag.Is8DQA = "true"; } + ca = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); - return View(ca); - } + ViewBag.CanCompleteCA = "false"; + if (ca.D1AssigneeID == (int)Session[GlobalVars.SESSION_USERID]) + ViewBag.CanCompleteCA = "true"; - - [HttpPost] - public ActionResult Edit(CorrectiveAction model) - { - int currentUserId = (int)Session[GlobalVars.SESSION_USERID]; - CorrectiveAction caPrevious = caDMO.GetCAItemReadOnly(model.CANo, currentUserId); - if((currentUserId != caPrevious.D1AssigneeID && currentUserId != caPrevious.QAID && currentUserId != caPrevious.RequestorID)) - { - return Content("User is not authorized to save the CA."); - } - try - { - if (model.TriggerApproval) - { - //model.FollowUpDate = DateTime.Now.AddMonths(6); - } - caDMO.UpdateCorrectiveAction(model); - - if ((model.D1AssigneeID != model.CurrentD1AssigneeID && model.CASubmitted) || (model.CASubmitted && !caPrevious.CASubmitted)) - { - //Set Due Dates here: - DateTime? D3DueDate = null; - DateTime? D5D7DueDate = null; - - if (model.CAType != "D0") - { - D3DueDate = SetD3DueDate(model.CANo); - if(model.CAType != "D3") - { - D5D7DueDate = SetD5D7DueDate(model.CANo); - } - } - - - - NotifyAssignee(model.CANo, model.D1AssigneeID, "CorrectiveActionAssignee.txt", D3DueDate, D5D7DueDate); - } - - if (model.TriggerSectionApproval) - { - if (model.SectionApproval == "D5D6D7Validation") - { - caDMO.StartSectionApproval(model.CANo, model.RequestorID, model.SectionApproval); - return Content("Successfully Saved...Validation initiated!"); - } - caDMO.StartSectionApproval(model.CANo, model.QAID, model.SectionApproval); - caDMO.StartSectionApproval(model.CANo, model.RequestorID, model.SectionApproval); - - NotifySectionApprover(model.CANo, model.QAID, model.SectionApproval); - - NotifySectionApprover(model.CANo, model.RequestorID, model.SectionApproval); - //NotifyApprovers(model.CANo, 1); - return Content("Successfully Saved...Approval initiated!"); - } - if (model.TriggerApproval) - { - caDMO.StartApproval(model.CANo, (int)Session[GlobalVars.SESSION_USERID], model.WorkFlowNumber); - NotifyApprovers(model.CANo, 1); - return Content("Successfully Saved...Approval initiated!"); - } - } - catch (Exception ex) - { - return Content(ex.Message); - } - - - return Content("Successfully Saved"); - } - - - public ActionResult ReadOnlyCA(int caNo) - { - CorrectiveAction ca = new CorrectiveAction(); - - ca = caDMO.GetCAItemReadOnly(caNo, (int)Session[GlobalVars.SESSION_USERID]); - if(ca.Status == 1 || ca.Status == 2 || ca.Status == 11 || ca.ClosedDate != null) - { - ViewBag.UserList = caDMO.GetAllUserList(); - } + List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ca.CurrentStep, (int)GlobalVars.DocumentType.CorrectiveAction); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (approver == null) + ViewBag.IsApprover = "false"; else - { - ViewBag.UserList = caDMO.GetUserList(); - } - ViewBag.CASourceList = caDMO.GetCASourceList(); - ViewBag.ModuleList = caDMO.GetModuleList(); - ViewBag.D3RiskAssessmentAreas = caDMO.GetD3RiskAssessmentAreas(); - ViewBag.D5D6ImprovementIDs = caDMO.GetD5D6Improvement(); + ViewBag.IsApprover = "true"; + ViewBag.IsAIAssignee = caDMO.IsAIAssignee((int)Session[GlobalVars.SESSION_USERID], issueID); + ViewBag.IsSectionApprover = caDMO.IsUserSectionApprover(ca.CANo, (int)Session[GlobalVars.SESSION_USERID]); ViewBag.AuditFindingCategoriesOptions = auditDMO.GetAuditFindingCategories().ToList(); - if (ca.RelatedAudit != null && ca.RelatedAudit > 0) - { + if (ca.RelatedAudit != null && ca.RelatedAudit > 0) { Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, (int)Session[GlobalVars.SESSION_USERID]); IEnumerable auditFindings = auditDMO.GetAuditFindingsList(audit.AuditNo); @@ -311,1830 +127,1256 @@ namespace Fab2ApprovalSystem.Controllers ViewBag.AuditFinding = relatedAuditFinding; ViewBag.AuditFindingCategories = relatedAuditFindingCatIds; ViewBag.ViolatedClause = relatedViolatedClause; - } - else - { + } else { ViewBag.AuditFinding = ""; ViewBag.AuditFindingCategories = ""; ViewBag.ViolatedClause = ""; } - return View(ca); - - } - public void ReleaseLockOnDocumentAdmin(int issueID) - { - try - { - caDMO.ReleaseLockOnDocument(-1, issueID); - } - catch (Exception e) - { - try - { - Functions.WriteEvent(@User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + if ((ca.ClosedDate != null) || + // TODO Aproverslist================================================================ + (ca.ClosedDate != null && ViewBag.IsApprover == "false" && ViewBag.IsAIAssignee == "false") || + (ca.RecordLockIndicator && ca.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ca.Status == 11 && ViewBag.IsApprover == "false")) { + return RedirectToAction("ReadOnlyCA", new { caNo = ca.CANo }); + } else { + ViewBag.ECNList = caDMO.GetECNList(); + if (ca.Status == 1 || ca.Status == 2 || ca.Status == 11) { + //Pulling in the user list which includes inactive users. + ViewBag.UserList = caDMO.GetAllUserList(); + } else { + //Pulling in the user list which only includes active users. + ViewBag.UserList = caDMO.GetUserList(); } - catch { } - caDMO.ReleaseLockOnDocument(-1, issueID); - + ViewBag.CASourceList = caDMO.GetCASourceList(); + ViewBag.ModuleList = caDMO.GetModuleList(); + ViewBag.D3RiskAssessmentAreas = caDMO.GetD3RiskAssessmentAreas(); + ViewBag.D5D6ImprovementIDs = caDMO.GetD5D6Improvement(); } - - } - /// - /// - /// - /// - /// - /// - public ActionResult GetD2AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) - { - - return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D2)).ToDataSourceResult(request)); - } - - public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int caNO) - { - return Json(caDMO.GetCAAttachmentsList(caNO, "Main").ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - - /// - /// - /// - /// - [HttpPost] - public void DeleteCAAttachment(int attachmentID) - { - caDMO.DeleteCAAttachment(attachmentID); - } - - /// - /// - /// - /// - /// - /// - public ActionResult DownloadCAAttachment(string fileGuid, int caNo) - { - - - try - { - string fileName = caDMO.GetCAAttachmentFileName(fileGuid); - - string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); - - string ecnFolderPath = Functions.GetAttachmentFolder() + "CorrectiveAction\\" + caNo.ToString(); - var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); - - var FDir_AppData = Functions.GetAttachmentFolder(); - if (!sDocument.StartsWith(FDir_AppData)) - { - // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder - // and block requests outside like "../web.config" - throw new HttpException(403, "Forbidden"); - } - - if (!System.IO.File.Exists(sDocument)) - { - return null; - //throw new Exception("File not found"); - } - - return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Edit - CA\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString }); + throw new Exception(e.Message); + } - catch - { - // TODO - proces the error - throw; + return View(ca); + } + + [HttpPost] + public ActionResult Edit(CorrectiveAction model) { + int currentUserId = (int)Session[GlobalVars.SESSION_USERID]; + CorrectiveAction caPrevious = caDMO.GetCAItemReadOnly(model.CANo, currentUserId); + if ((currentUserId != caPrevious.D1AssigneeID && currentUserId != caPrevious.QAID && currentUserId != caPrevious.RequestorID)) { + return Content("User is not authorized to save the CA."); + } + try { + if (model.TriggerApproval) { + //model.FollowUpDate = DateTime.Now.AddMonths(6); } - } - public ActionResult DownloadTemplatesFiles() - { + caDMO.UpdateCorrectiveAction(model); - //string templatesPath = GlobalVars.CA_BlankFormsLocation; - //string fullName = Server.MapPath("~" + filePath); - string fileName = "5Why_Is_Is_Not_Fishbone.pptx"; - string pathToFile = GlobalVars.MesaTemplateFiles + "\\5Why_Is_Is_Not_Fishbone.pptx"; - byte[] fileBytes = fileUtilities.GetFile(pathToFile); - return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); - } + if ((model.D1AssigneeID != model.CurrentD1AssigneeID && model.CASubmitted) || (model.CASubmitted && !caPrevious.CASubmitted)) { + //Set Due Dates here: + DateTime? D3DueDate = null; + DateTime? D5D7DueDate = null; - - /// - /// - /// - /// - /// - /// - public ActionResult AttachSave(IEnumerable files, int caNo) - { - try - { - // The Name of the Upload component is "files" - if (files != null) - { - foreach (var file in files) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var ccPhysicalPath = Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo; - di = new DirectoryInfo(ccPhysicalPath); - if (!di.Exists) - di.Create(); - - - var guid = Guid.NewGuid().ToString(); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension); - - - file.SaveAs(physicalPath); - CA_Attachment attach = new CA_Attachment() - { - CANo = caNo, - FileGUID = guid, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID], - Section = Functions.CASectionMapper(GlobalVars.CASection.Main) - }; - - - //ccDMO.InsertCCAttachment(attach); - caDMO.InsertCAAttachment(attach); + if (model.CAType != "D0") { + D3DueDate = SetD3DueDate(model.CANo); + if (model.CAType != "D3") { + D5D7DueDate = SetD5D7DueDate(model.CANo); } } - } - catch - { - throw; + + NotifyAssignee(model.CANo, model.D1AssigneeID, "CorrectiveActionAssignee.txt", D3DueDate, D5D7DueDate); } + if (model.TriggerSectionApproval) { + if (model.SectionApproval == "D5D6D7Validation") { + caDMO.StartSectionApproval(model.CANo, model.RequestorID, model.SectionApproval); + return Content("Successfully Saved...Validation initiated!"); + } + caDMO.StartSectionApproval(model.CANo, model.QAID, model.SectionApproval); + caDMO.StartSectionApproval(model.CANo, model.RequestorID, model.SectionApproval); - return Content(""); + NotifySectionApprover(model.CANo, model.QAID, model.SectionApproval); + + NotifySectionApprover(model.CANo, model.RequestorID, model.SectionApproval); + //NotifyApprovers(model.CANo, 1); + return Content("Successfully Saved...Approval initiated!"); + } + if (model.TriggerApproval) { + caDMO.StartApproval(model.CANo, (int)Session[GlobalVars.SESSION_USERID], model.WorkFlowNumber); + NotifyApprovers(model.CANo, 1); + return Content("Successfully Saved...Approval initiated!"); + } + } catch (Exception ex) { + return Content(ex.Message); } - /// - /// - /// - /// - /// - /// - public ActionResult GetD3ContainmentActionsList([DataSourceRequest] DataSourceRequest request, int caNo) - { + return Content("Successfully Saved"); + } - return Json(caDMO.GetD3ContainmentActions(caNo).ToDataSourceResult(request)); + public ActionResult ReadOnlyCA(int caNo) { + CorrectiveAction ca = new CorrectiveAction(); + + ca = caDMO.GetCAItemReadOnly(caNo, (int)Session[GlobalVars.SESSION_USERID]); + if (ca.Status == 1 || ca.Status == 2 || ca.Status == 11 || ca.ClosedDate != null) { + ViewBag.UserList = caDMO.GetAllUserList(); + } else { + ViewBag.UserList = caDMO.GetUserList(); + } + ViewBag.CASourceList = caDMO.GetCASourceList(); + ViewBag.ModuleList = caDMO.GetModuleList(); + ViewBag.D3RiskAssessmentAreas = caDMO.GetD3RiskAssessmentAreas(); + ViewBag.D5D6ImprovementIDs = caDMO.GetD5D6Improvement(); + + ViewBag.AuditFindingCategoriesOptions = auditDMO.GetAuditFindingCategories().ToList(); + if (ca.RelatedAudit != null && ca.RelatedAudit > 0) { + Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, (int)Session[GlobalVars.SESSION_USERID]); + IEnumerable auditFindings = auditDMO.GetAuditFindingsList(audit.AuditNo); + + AuditFindings relatedFinding = (from a in auditFindings where a.CANo == ca.CANo select a).First(); + + string relatedAuditFinding = relatedFinding.Findings; + IEnumerable relatedAuditFindingCatIds = auditDMO.GetAuditFindingCategoryIdsByFindingId(relatedFinding.ID); + string relatedViolatedClause = relatedFinding.ViolatedClause; + + ViewBag.AuditFinding = relatedAuditFinding; + ViewBag.AuditFindingCategories = relatedAuditFindingCatIds; + ViewBag.ViolatedClause = relatedViolatedClause; + } else { + ViewBag.AuditFinding = ""; + ViewBag.AuditFindingCategories = ""; + ViewBag.ViolatedClause = ""; } - /// - /// - /// - /// - /// - public ActionResult UpdateD3ContainmentAction(D3ContainmentAction data) - { - caDMO.UpdateD3ContainmentAction(data); - if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID !=0) - { - NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); + return View(ca); + } + + public void ReleaseLockOnDocumentAdmin(int issueID) { + try { + caDMO.ReleaseLockOnDocument(-1, issueID); + } catch (Exception e) { + try { + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + } catch { } + caDMO.ReleaseLockOnDocument(-1, issueID); + } + } + + public ActionResult GetD2AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) { + + return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D2)).ToDataSourceResult(request)); + } + + public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int caNO) { + return Json(caDMO.GetCAAttachmentsList(caNO, "Main").ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } + + [HttpPost] + public void DeleteCAAttachment(int attachmentID) { + caDMO.DeleteCAAttachment(attachmentID); + } + + public ActionResult DownloadCAAttachment(string fileGuid, int caNo) { + try { + string fileName = caDMO.GetCAAttachmentFileName(fileGuid); + + string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); + + string ecnFolderPath = _AppSettings.AttachmentFolder + "CorrectiveAction\\" + caNo.ToString(); + var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); + + var FDir_AppData = _AppSettings.AttachmentFolder; + if (!sDocument.StartsWith(FDir_AppData)) { + // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder + // and block requests outside like "../web.config" + throw new HttpException(403, "Forbidden"); } - return Content(""); - } - - - /// - /// - /// - /// - /// - public ActionResult InsertD3ContainmentAction(D3ContainmentAction data) - { - caDMO.InsertD3ContainmentAction(data); - if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) - { - NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); + if (!System.IO.File.Exists(sDocument)) { + return null; + //throw new Exception("File not found"); } - return Content(""); + + return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + } catch { + // TODO - proces the error + throw; } + } + public ActionResult DownloadTemplatesFiles() { + //string templatesPath = GlobalVars.CA_BlankFormsLocation; + //string fullName = Server.MapPath("~" + filePath); + string fileName = "5Why_Is_Is_Not_Fishbone.pptx"; + string pathToFile = GlobalVars.MesaTemplateFiles + "\\5Why_Is_Is_Not_Fishbone.pptx"; + byte[] fileBytes = fileUtilities.GetFile(pathToFile); + return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + } - /// - /// - /// - /// - [HttpPost] - public void DeletetD3ContainmentActionItem(int d3ContainmentActionID) - { - caDMO.DeleteD3ContainmentActionItem(d3ContainmentActionID); - } - - - /// - /// - /// - /// - /// - /// - public ActionResult GetD4AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) - { - - return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D4)).ToDataSourceResult(request)); - } - - - - /// - /// - /// - /// - /// - /// - public ActionResult D4FilesAttachSave(IEnumerable D4Files, int caNo) - { - try - { - // The Name of the Upload component is "files" - if (D4Files != null) - { - foreach (var file in D4Files) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var ccPhysicalPath = Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo; - di = new DirectoryInfo(ccPhysicalPath); - if (!di.Exists) - di.Create(); - - - var guid = Guid.NewGuid().ToString(); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension); - - - file.SaveAs(physicalPath); - CA_Attachment attach = new CA_Attachment() - { - CANo = caNo, - FileGUID = guid, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID], - Section = Functions.CASectionMapper(GlobalVars.CASection.D4) - - }; - - - //ccDMO.InsertCCAttachment(attach); - caDMO.InsertCAAttachment(attach); - } + public ActionResult AttachSave(IEnumerable files, int caNo) { + try { + // The Name of the Upload component is "files" + if (files != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in files) { + caDMO.AttachSave(caNo, userId, file.FileName, file.InputStream); } } - catch - { - throw; - } - - - return Content(""); + } catch { + throw; } - /// - /// - /// - /// - /// - /// - public ActionResult GetD5D6CorrectivetActionList([DataSourceRequest] DataSourceRequest request, int caNo) - { + return Content(""); + } - return Json(caDMO.GetD5D6CorrectivetActions(caNo).ToDataSourceResult(request)); + public ActionResult GetD3ContainmentActionsList([DataSourceRequest] DataSourceRequest request, int caNo) { + return Json(caDMO.GetD3ContainmentActions(caNo).ToDataSourceResult(request)); + } + + public ActionResult UpdateD3ContainmentAction(D3ContainmentAction data) { + caDMO.UpdateD3ContainmentAction(data); + if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID != 0) { + NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); } - /// - /// - /// - /// - /// - public ActionResult InsertD5D6CAItem(D5D6CorrectivetAction data) - { - try - { - caDMO.InsertD5D6CorrectivetAction(data); - } - catch(Exception e) - { - return Content(e.Message + " Please try again..."); - } - if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) - { - //NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); - //NotifyRequestor(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); - + return Content(""); + } - } - return Content(""); + public ActionResult InsertD3ContainmentAction(D3ContainmentAction data) { + caDMO.InsertD3ContainmentAction(data); + if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) { + NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); } + return Content(""); + } - /// - /// - /// - /// - /// - public ActionResult UpdateD5D6CAItem(D5D6CorrectivetAction data) - { - D5D6CorrectivetAction previousData = caDMO.GetD5D5CAItem(data.ID); - CorrectiveAction caData = caDMO.GetCAItem(data.CANo, (int)Session[GlobalVars.SESSION_USERID]); - try - { - caDMO.UpdateD5D6CorrectivetAction(data); - } - catch(Exception e) - { - return Content(e.Message + " Please try again..."); - } - if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID != 0) - { - NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); - } - if(data.IsImplemented && previousData.ImplementedDate == null) - { - //Notify completion to Assignee and Requestor - NotifyActionItemCompletion(data.CANo, data.ECD, caData.D1AssigneeID, "CorrectiveActionAICompleted.txt"); - NotifyActionItemCompletion(data.CANo, data.ECD, caData.RequestorID, "CorrectiveActionAICompleted.txt"); - NotifyActionItemCompletion(data.CANo, data.ECD, caData.QAID, "CorrectiveActionAICompleted.txt"); + [HttpPost] + public void DeletetD3ContainmentActionItem(int d3ContainmentActionID) { + caDMO.DeleteD3ContainmentActionItem(d3ContainmentActionID); + } - } - return Content(""); - } + public ActionResult GetD4AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) { + return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D4)).ToDataSourceResult(request)); + } - /// - /// - /// - /// - /// - public ActionResult GetD5D6CAItem(int d5d6CAID) - { - var model = new D5D6CorrectivetAction(); - model = caDMO.GetD5D5CAItem(d5d6CAID); - - return PartialView("_D5D6CAAttachment", model); - } - - - /// - /// - /// - /// - /// - /// - public ActionResult GetD5D6ItemAttachments([DataSourceRequest] DataSourceRequest request, int d5d6CAID) - { - - return Json(caDMO.GetD5D6ItemAttachments(d5d6CAID).ToDataSourceResult(request)); - } - - /// - /// - /// - /// - [HttpPost] - public void DeleteD5D6CAItem(int d5d6CAID) - { - caDMO.DeleteD5D6CorrectivetAction(d5d6CAID); - } - - - - /// - /// - /// - /// - /// - /// - /// - public ActionResult SaveD5D6CA_Attachemnt(IEnumerable D5D6CA_Attachemnt, int d5d6CAID, int caNo) - { - try - { - // The Name of the Upload component is "files" - if (D5D6CA_Attachemnt != null) - { - foreach (var file in D5D6CA_Attachemnt) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var ccPhysicalPath = Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo; - di = new DirectoryInfo(ccPhysicalPath); - if (!di.Exists) - di.Create(); - - - var guid = Guid.NewGuid().ToString(); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension); - - - file.SaveAs(physicalPath); - CA_Attachment attach = new CA_Attachment() - { - D5D6CAID = d5d6CAID, - CANo = caNo, - FileGUID = guid, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID], - Section = Functions.CASectionMapper(GlobalVars.CASection.D5) - - }; - - - caDMO.InsertCAAttachment(attach); - } + public ActionResult D4FilesAttachSave(IEnumerable D4Files, int caNo) { + try { + // The Name of the Upload component is "files" + if (D4Files != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in D4Files) { + caDMO.D4FilesAttachSave(caNo, userId, file.FileName, file.InputStream); } } - catch - { - throw; - } - - - return Content(""); + } catch { + throw; } + return Content(""); + } + public ActionResult GetD5D6CorrectivetActionList([DataSourceRequest] DataSourceRequest request, int caNo) { + return Json(caDMO.GetD5D6CorrectivetActions(caNo).ToDataSourceResult(request)); + } - // D7 ==================================================================================== - public ActionResult GetD7PreventiveActionList([DataSourceRequest] DataSourceRequest request, int caNo) - { - - return Json(caDMO.GetD7PreventiveActions(caNo).ToDataSourceResult(request)); + public ActionResult InsertD5D6CAItem(D5D6CorrectivetAction data) { + try { + caDMO.InsertD5D6CorrectivetAction(data); + } catch (Exception e) { + return Content(e.Message + " Please try again..."); } - - /// - /// - /// - /// - /// - public ActionResult InsertD7PAItem(D7PreventiveAction data) - { - caDMO.InsertD7PreventiveAction(data); - if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) - { - NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); - } - - return Content(""); + if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) { + //NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); + //NotifyRequestor(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); } + return Content(""); + } - /// - /// - /// - /// - /// - public ActionResult UpdateD7PAItem(D7PreventiveAction data) - { - caDMO.UpdateD7PreventiveAction(data); - if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID != 0) - { - NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); - } - - return Content(""); + public ActionResult UpdateD5D6CAItem(D5D6CorrectivetAction data) { + D5D6CorrectivetAction previousData = caDMO.GetD5D5CAItem(data.ID); + CorrectiveAction caData = caDMO.GetCAItem(data.CANo, (int)Session[GlobalVars.SESSION_USERID]); + try { + caDMO.UpdateD5D6CorrectivetAction(data); + } catch (Exception e) { + return Content(e.Message + " Please try again..."); } - - /// - /// - /// - /// - /// - public ActionResult GetD7PAItem(int d7paID) - { - var model = new D7PreventiveAction(); - model = caDMO.GetD7PAItem(d7paID); - - return PartialView("_D7PAAttachment", model); + if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID != 0) { + NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); } - - - /// - /// - /// - /// - /// - /// - public ActionResult GetD7ItemAttachments([DataSourceRequest] DataSourceRequest request, int d7PAID) - { - - return Json(caDMO.GetD7ItemAttachments(d7PAID).ToDataSourceResult(request)); + if (data.IsImplemented && previousData.ImplementedDate == null) { + //Notify completion to Assignee and Requestor + NotifyActionItemCompletion(data.CANo, data.ECD, caData.D1AssigneeID, "CorrectiveActionAICompleted.txt"); + NotifyActionItemCompletion(data.CANo, data.ECD, caData.RequestorID, "CorrectiveActionAICompleted.txt"); + NotifyActionItemCompletion(data.CANo, data.ECD, caData.QAID, "CorrectiveActionAICompleted.txt"); } + return Content(""); + } + public ActionResult GetD5D6CAItem(int d5d6CAID) { + var model = new D5D6CorrectivetAction(); + model = caDMO.GetD5D5CAItem(d5d6CAID); - /// - /// - /// - /// - [HttpPost] - public void DeleteD7PAItem(int d7PAID) - { - caDMO.DeleteD7PreventiveActionItem(d7PAID); - } + return PartialView("_D5D6CAAttachment", model); + } - + public ActionResult GetD5D6ItemAttachments([DataSourceRequest] DataSourceRequest request, int d5d6CAID) { + return Json(caDMO.GetD5D6ItemAttachments(d5d6CAID).ToDataSourceResult(request)); + } - + [HttpPost] + public void DeleteD5D6CAItem(int d5d6CAID) { + caDMO.DeleteD5D6CorrectivetAction(d5d6CAID); + } - - /// - /// - /// - /// - /// - /// - /// - public ActionResult SaveD7PA_Attachemnt(IEnumerable D7PA_Attachemnt, int d7PAID, int caNo) - { - try - { - // The Name of the Upload component is "files" - if (D7PA_Attachemnt != null) - { - foreach (var file in D7PA_Attachemnt) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var ccPhysicalPath = Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo; - di = new DirectoryInfo(ccPhysicalPath); - if (!di.Exists) - di.Create(); - - - var guid = Guid.NewGuid().ToString(); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension); - - - file.SaveAs(physicalPath); - CA_Attachment attach = new CA_Attachment() - { - D7PAID = d7PAID, - CANo = caNo, - FileGUID = guid, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID], - Section = Functions.CASectionMapper(GlobalVars.CASection.D7) - - }; - - - caDMO.InsertCAAttachment(attach); - } + public ActionResult SaveD5D6CA_Attachemnt(IEnumerable D5D6CA_Attachemnt, int d5d6CAID, int caNo) { + try { + // The Name of the Upload component is "files" + if (D5D6CA_Attachemnt != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in D5D6CA_Attachemnt) { + caDMO.SaveD5D6CA_Attachemnt(d5d6CAID, caNo, userId, file.FileName, file.InputStream); } } - catch - { - throw; - } - - - return Content(""); + } catch { + throw; } + return Content(""); + } - - - /// - /// - /// - /// - public void ReleaseLockOnDocument(int issueID) - { - try - { - caDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); - } - catch (Exception e) - { - try - { - Functions.WriteEvent(@User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); - } - catch { } - caDMO.ReleaseLockOnDocument(-1, issueID); - - } - + // D7 ==================================================================================== + public ActionResult GetD7PreventiveActionList([DataSourceRequest] DataSourceRequest request, int caNo) { + return Json(caDMO.GetD7PreventiveActions(caNo).ToDataSourceResult(request)); + } + public ActionResult InsertD7PAItem(D7PreventiveAction data) { + caDMO.InsertD7PreventiveAction(data); + if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) { + NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); } - /// - /// - /// - /// - public JsonResult GetAllUsersList() - { - //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep); - //return Json(userList, JsonRequestBehavior.AllowGet); - - UserAccountDMO userDMO = new UserAccountDMO(); - IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); + return Content(""); + } + public ActionResult UpdateD7PAItem(D7PreventiveAction data) { + caDMO.UpdateD7PreventiveAction(data); + if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID != 0) { + NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); } + return Content(""); + } + public ActionResult GetD7PAItem(int d7paID) { + var model = new D7PreventiveAction(); + model = caDMO.GetD7PAItem(d7paID); - /// - /// - /// - /// - /// - /// - /// - public void ReAssignApproverByAdmin(int issueID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType) - { - var email = ""; - try - { + return PartialView("_D7PAAttachment", model); + } - email = wfDMO.ReAssignApproval(issueID, reAssignApproverFrom, reAssignApproverTo, step, docType); + public ActionResult GetD7ItemAttachments([DataSourceRequest] DataSourceRequest request, int d7PAID) { + return Json(caDMO.GetD7ItemAttachments(d7PAID).ToDataSourceResult(request)); + } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); + [HttpPost] + public void DeleteD7PAItem(int d7PAID) { + caDMO.DeleteD7PreventiveActionItem(d7PAID); + } + + public ActionResult SaveD7PA_Attachemnt(IEnumerable D7PA_Attachemnt, int d7PAID, int caNo) { + try { + // The Name of the Upload component is "files" + if (D7PA_Attachemnt != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in D7PA_Attachemnt) { + caDMO.SaveD7PA_Attachemnt(d7PAID, caNo, userId, file.FileName, file.InputStream); } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); - throw new Exception(e.Message); - } + } catch { + throw; + } + return Content(""); + } - string emailTemplate = "CorrectiveActionReAssigned.txt"; - string userEmail = string.Empty; - string subject = "Corrective Action Re-Assignment"; - string senderName = "CorrectiveAction"; + public void ReleaseLockOnDocument(int issueID) { + try { + caDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); + } catch (Exception e) { + try { + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + } catch { } + caDMO.ReleaseLockOnDocument(-1, issueID); + } + } - subject = "Corrective Action Re-Assignment" + " - Email would be sent to " + email; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[3]; + public JsonResult GetAllUsersList() { + //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep); + //return Json(userList, JsonRequestBehavior.AllowGet); + + UserAccountDMO userDMO = new UserAccountDMO(); + IEnumerable userlist = userDMO.GetAllUsers(); + return Json(userlist, JsonRequestBehavior.AllowGet); + } + + public void ReAssignApproverByAdmin(int issueID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType) { + var email = ""; + try { + email = wfDMO.ReAssignApproval(issueID, reAssignApproverFrom, reAssignApproverTo, step, docType); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + throw new Exception(e.Message); + } + + string emailTemplate = "CorrectiveActionReAssigned.txt"; + string userEmail = string.Empty; + string subject = "Corrective Action Re-Assignment"; + string senderName = "CorrectiveAction"; + + subject = "Corrective Action Re-Assignment" + " - Email would be sent to " + email; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[3]; + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + } catch { } + } + + public void ReAssignApproval(int issueID, int userIDs, byte step) { + var email = ""; + try { + email = wfDMO.ReAssignApproval(issueID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, (int)GlobalVars.DocumentType.CorrectiveAction); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + throw new Exception(e.Message); + } + + string emailTemplate = "CorrectiveActionReAssigned.txt"; + string userEmail = string.Empty; + string subject = "Corrective Action Re-Assignment"; + string senderName = "CorrectiveAction"; + + subject = "Corrective Action Re-Assignment" + " - Email would be sent to " + email; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[3]; + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + } catch { } + } + + public void Reject(int issueID, byte currentStep, string comments) { + try { + if (Session[GlobalVars.SESSION_USERID] != null) { + wfDMO.Reject(issueID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction); + NotifyRejectionToAssignee(issueID, comments); + } else { + Response.Redirect("~/Account/Login"); + } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Reject\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public void NotifyRejectionToAssignee(int issueID, string comments) { + List emailIst = caDMO.GetRejectionAssigneeEmailList(@issueID).Distinct().ToList(); + + string emailTemplate = "CorrectiveActionReject.txt"; + string userEmail = string.Empty; + string subject = "Corrective Action Rejection"; + string senderName = "CorrectiveAction"; + + foreach (string email in emailIst) { + subject = "Corrective Action Rejection"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; emailparams[0] = Functions.ReturnCANoStringFormat(issueID); emailparams[1] = issueID.ToString(); emailparams[2] = GlobalVars.hostURL; + emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString(); + emailparams[4] = comments; userEmail = email; //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; + // userEmail = "rkotian1@irf.com"; //#endif - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email }); - } - catch { } - + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); } - /// - /// - /// - /// - /// - /// - /// - public void ReAssignApproval(int issueID, int userIDs, byte step) - { - var email = ""; - try - { - email = wfDMO.ReAssignApproval(issueID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, (int)GlobalVars.DocumentType.CorrectiveAction); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Rejection: " + userEmail }); + } catch { } + } + + public void Approve(int issueID, byte currentStep, string comments) { + int isITARCompliant = 1; + try { + bool lastStep = false; + CorrectiveAction ca = caDMO.GetCAItemReadOnly(issueID, (int)Session[GlobalVars.SESSION_USERID]); + + bool lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction, ca.WorkFlowNumber); + + //while (lastApprover && !lastStep) + //{ + // currentStep++; + // //lastApprover = wfDMO.Approve(issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction, ca.WorkFlowNumber); + // NotifyApprovers(issueID, currentStep); + //} + if (lastApprover && !lastStep) { + //Set to complete + DateTime followUpDate = caDMO.SetCAComplete(issueID); + //Notify completion and send follow up date + NotifyCompletionOf8D(issueID, followUpDate); } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); - throw new Exception(e.Message); + if (lastApprover && lastStep) { + //Notify re the closure of the 8D + NotifyClosureOf8D(issueID); } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw new Exception(e.Message); + } + } + public void NotifySectionApprover(int issueID, int userId, string section) { + try { + string userEmail = userDMO.GetUserEmailByID(userId); - string emailTemplate = "CorrectiveActionReAssigned.txt"; - string userEmail = string.Empty; - string subject = "Corrective Action Re-Assignment"; + string emailTemplate = "CorrectiveActionSectionAssignee.txt"; + //string userEmail = string.Empty; + string subject = "Corrective Action Assignment"; string senderName = "CorrectiveAction"; - subject = "Corrective Action Re-Assignment" + " - Email would be sent to " + email; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[3]; + subject = "Corrective Action Assignment - Section Approval"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; emailparams[0] = Functions.ReturnCANoStringFormat(issueID); emailparams[1] = issueID.ToString(); emailparams[2] = GlobalVars.hostURL; - userEmail = email; + emailparams[3] = section; //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; + // userEmail = "rkotian1@irf.com"; //#endif - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - try - { + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - catch { } - + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw e; } + } + public void NotifyApprovers(int issueID, byte currentStep) { + try { + string emailSentList = ""; - /// - /// - /// - /// - /// - /// - public void Reject(int issueID, byte currentStep, string comments) - { - try - { - if (Session[GlobalVars.SESSION_USERID] != null) - { - wfDMO.Reject(issueID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction); - NotifyRejectionToAssignee(issueID, comments); - } - else - { + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + List emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.CorrectiveAction).Distinct().ToList(); - Response.Redirect("~/Account/Login"); - } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Reject\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString }); - throw new Exception(e.Message); - - } - - } - - /// - /// - /// - /// - public void NotifyRejectionToAssignee(int issueID, string comments) - { - - List emailIst = caDMO.GetRejectionAssigneeEmailList(@issueID).Distinct().ToList(); - - string emailTemplate = "CorrectiveActionReject.txt"; + string emailTemplate = "CorrectiveActionAssigned.txt"; string userEmail = string.Empty; - string subject = "Corrective Action Rejection"; + string subject = "Corrective Action Assignment"; string senderName = "CorrectiveAction"; - foreach (string email in emailIst) - { - subject = "Corrective Action Rejection"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; + foreach (string email in emailIst) { + subject = "Corrective Action Assignment - Final Approval"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[3]; emailparams[0] = Functions.ReturnCANoStringFormat(issueID); emailparams[1] = issueID.ToString(); emailparams[2] = GlobalVars.hostURL; - emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString(); - emailparams[4] = comments; userEmail = email; //#if(DEBUG) // userEmail = "rkotian1@irf.com"; //#endif - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + emailSentList += email + ","; } - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Rejection: " + userEmail }); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - catch { } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw e; + } + } + #region Additional Approvers + public void AddAdditionalApproval(int issueID, byte step, string userIDs) { + string emailSentList = ""; + var emailArray = ""; + try { + emailArray = wfDMO.AddAdditionalApproval(issueID, userIDs, step, (int)GlobalVars.DocumentType.CorrectiveAction); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw new Exception(e.Message); } - /// - /// - /// - /// - /// - /// - public void Approve(int issueID, byte currentStep, string comments) - { - int isITARCompliant = 1; - try - { - bool lastStep = false; - CorrectiveAction ca = caDMO.GetCAItemReadOnly(issueID, (int)Session[GlobalVars.SESSION_USERID]); + string emailTemplate = "CorrectiveActionAssigned.txt"; + string userEmail = string.Empty; + string subject = "Corrective Action Assignment - Final Approval"; + string senderName = "CorrectiveAction"; - bool lastApprover = wfDMO.Approve(issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction, ca.WorkFlowNumber); - - //while (lastApprover && !lastStep) - //{ - // currentStep++; - // //lastApprover = wfDMO.Approve(issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction, ca.WorkFlowNumber); - // NotifyApprovers(issueID, currentStep); - //} - if (lastApprover && !lastStep) - { - //Set to complete - DateTime followUpDate = caDMO.SetCAComplete(issueID); - //Notify completion and send follow up date - NotifyCompletionOf8D(issueID, followUpDate); - - } - if (lastApprover && lastStep) - { - //Notify re the closure of the 8D - NotifyClosureOf8D(issueID); - - } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw new Exception(e.Message); - } - - } - - - public void NotifySectionApprover(int issueID, int userId, string section) - { - try - { - string userEmail = userDMO.GetUserEmailByID(userId.ToString()); - - string emailTemplate = "CorrectiveActionSectionAssignee.txt"; - //string userEmail = string.Empty; - string subject = "Corrective Action Assignment"; - string senderName = "CorrectiveAction"; - - subject = "Corrective Action Assignment - Section Approval"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = section; + string[] emailIst = emailArray.Split(new char[] { '~' }); + foreach (string email in emailIst) { + if (email.Length > 0) { + //subject = "Lot Disposition Assignment" + " - Email would be sent to " + email; + subject = "Corrective Action Assignment"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[3]; + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + userEmail = email; //#if(DEBUG) // userEmail = "rkotian1@irf.com"; //#endif - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; - - - } - - } - public void NotifyApprovers(int issueID, byte currentStep) - { - try - { - string emailSentList = ""; - - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - List emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.CorrectiveAction).Distinct().ToList(); - - string emailTemplate = "CorrectiveActionAssigned.txt"; - string userEmail = string.Empty; - string subject = "Corrective Action Assignment"; - string senderName = "CorrectiveAction"; - - foreach (string email in emailIst) - { - subject = "Corrective Action Assignment - Final Approval"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[3]; - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - userEmail = email; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - emailSentList += email + ","; - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; - + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + emailSentList += email + ","; } } - #region Additional Approvers + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); + } catch { } + } + #endregion - /// - /// - /// - /// - /// - /// - public void AddAdditionalApproval(int issueID, byte step, string userIDs) - { + public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) { + //return Json(ldDMO.GetApproversList(issueID, step).ToDataSourceResult(request)); + return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.CorrectiveAction).ToDataSourceResult(request)); + } + public ActionResult GetSectionApprovalLog([DataSourceRequest] DataSourceRequest request, int caNo) { + //return Json(ldDMO.GetApproversList(issueID, step).ToDataSourceResult(request)); + return Json(caDMO.GetCASectionApprovalLog(caNo).ToDataSourceResult(request)); + } + + public void NotifyRequestor(int issueID, DateTime? dueDate, int? responsibleOwnerID, string template) { + try { string emailSentList = ""; - var emailArray = ""; - try - { - emailArray = wfDMO.AddAdditionalApproval(issueID, userIDs, step, (int)GlobalVars.DocumentType.CorrectiveAction); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw new Exception(e.Message); - } - string emailTemplate = "CorrectiveActionAssigned.txt"; + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + string email = MiscDMO.GetEmail(responsibleOwnerID); + + string emailTemplate = template; string userEmail = string.Empty; - string subject = "Corrective Action Assignment - Final Approval"; + string subject = "Corrective Action Assignment - " + Functions.ReturnCANoStringFormat(issueID); string senderName = "CorrectiveAction"; - string[] emailIst = emailArray.Split(new char[] { '~' }); - foreach (string email in emailIst) - { - if (email.Length > 0) - { - //subject = "Lot Disposition Assignment" + " - Email would be sent to " + email; - subject = "Corrective Action Assignment"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[3]; - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - userEmail = email; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = dueDate.ToString(); + emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction); + emailparams[3] = GlobalVars.hostURL; + emailparams[4] = issueID.ToString(); + //userEmail = email; - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - emailSentList += email + ","; - - } + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); + emailSentList += email + ","; + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - try - { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); - } - catch { } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); + //throw e; } - - #endregion - - /// - /// - /// - /// - /// - /// - /// - public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) - { - //return Json(ldDMO.GetApproversList(issueID, step).ToDataSourceResult(request)); - return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.CorrectiveAction).ToDataSourceResult(request)); - } - public ActionResult GetSectionApprovalLog([DataSourceRequest] DataSourceRequest request, int caNo) - { - //return Json(ldDMO.GetApproversList(issueID, step).ToDataSourceResult(request)); - return Json(caDMO.GetCASectionApprovalLog(caNo).ToDataSourceResult(request)); - } - /// - /// - /// - /// - /// - /// - public void NotifyRequestor(int issueID, DateTime? dueDate, int? responsibleOwnerID, string template) - { - try - { - string emailSentList = ""; - - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - string email = MiscDMO.GetEmail(responsibleOwnerID); - - string emailTemplate = template; - string userEmail = string.Empty; - string subject = "Corrective Action Assignment - " + Functions.ReturnCANoStringFormat(issueID); - string senderName = "CorrectiveAction"; - - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = dueDate.ToString(); - emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction); - emailparams[3] = GlobalVars.hostURL; - emailparams[4] = issueID.ToString(); - //userEmail = email; - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); - emailSentList += email + ","; - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); - //throw e; - - - } - - } - public void NotifyAssignee(int issueID, int? responsibleOwnerID, string template, DateTime? D3DueDate, DateTime? D5D7DueDate) - { - try - { - string emailSentList = ""; - - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - string email = MiscDMO.GetEmail(responsibleOwnerID); - - string emailTemplate = template; - string userEmail = string.Empty; - string subject = "CAR Assigned - " + Functions.ReturnCANoStringFormat(issueID); - string senderName = "CorrectiveAction"; - - string D3DueDateString = D3DueDate != null ? D3DueDate.ToString() : "N/A"; - string D5D7DueDateString = D5D7DueDate != null ? D5D7DueDate.ToString() : "N/A"; - - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[6]; - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = issueID.ToString(); - emailparams[4] = D3DueDateString; - emailparams[5] = D5D7DueDateString; - //userEmail = email; - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); - emailSentList += email + ","; - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); - //throw e; - - - } - - } - /// - /// - /// - /// - /// - /// - public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID, string template) - { - try - { - string emailSentList = ""; - - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - string email = MiscDMO.GetEmail(responsibleOwnerID); - - string emailTemplate = template; - string userEmail = string.Empty; - string subject = "Action Item in " + Functions.ReturnCANoStringFormat(issueID); - string senderName = "CorrectiveAction"; - - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = dueDate.ToString(); - emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction); - emailparams[3] = GlobalVars.hostURL; - emailparams[4] = issueID.ToString(); - //userEmail = email; - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); - emailSentList += email + ","; - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); - //throw e; - - - } - - } - public void NotifyActionItemCompletion(int issueID, DateTime? dueDate, int? recipientId, string template) - { - try - { - string emailSentList = ""; - - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - string email = MiscDMO.GetEmail(recipientId); - - string emailTemplate = template; - string userEmail = string.Empty; - string subject = "8D Action Item Completion - " + Functions.ReturnCANoStringFormat(issueID); - string senderName = "CorrectiveAction"; - - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = dueDate.ToString(); - emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction); - emailparams[3] = GlobalVars.hostURL; - emailparams[4] = issueID.ToString(); - //userEmail = email; - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); - emailSentList += email + ","; - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemCompletion\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); - //throw e; - - - } - - } - /// - /// - /// - /// - public void NotifyClosureOf8D(int issueID) - { - try - { - string emailSentList = ""; - - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - List emailIst = MiscDMO.Get8DEmailListForClosureNotification(issueID); - - - string emailTemplate = "CorrectiveActionClosed.txt"; - //string userEmail = string.Empty; - string subject = "Corrective Action Follow Up Closure - " + Functions.ReturnCANoStringFormat(issueID); - string senderName = "CorrectiveAction"; - - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[3]; - foreach (string email in emailIst) - { - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = GlobalVars.hostURL; - emailparams[2] = issueID.ToString(); - //userEmail = email; - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); - emailSentList += email + ","; - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Closure of 8D Item" + ":" + emailSentList }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Closure of 8D:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Closure of 8D - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Closure of 8D Notification - " + exceptionString }); - //throw e; - - - } - } - public void NotifyCompletionOf8D(int issueID, DateTime? followUpDate) - { - try - { - string emailSentList = ""; - - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - List emailIst = MiscDMO.Get8DEmailListForClosureNotification(issueID); - - - string emailTemplate = "CorrectiveActionCompleted.txt"; - //string userEmail = string.Empty; - string subject = "Corrective Action Completion - " + Functions.ReturnCANoStringFormat(issueID); - string senderName = "CorrectiveAction"; - - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - foreach (string email in emailIst) - { - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = GlobalVars.hostURL; - emailparams[2] = issueID.ToString(); - emailparams[3] = followUpDate.ToString(); - //userEmail = email; - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); - emailSentList += email + ","; - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Closure of 8D Item" + ":" + emailSentList }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Closure of 8D:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Closure of 8D - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Closure of 8D Notification - " + exceptionString }); - //throw e; - - - } - } - public void StartSectionApproval(int issueID, string dSection) - { - try - { - CorrectiveAction ca = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); - - int requestorId = ca.RequestorID; - int qaId = ca.QAID; - //int userID = (int)Session[GlobalVars.SESSION_USERID]; - - caDMO.StartSectionApproval(issueID, requestorId, dSection); - NotifySectionApprover(issueID, requestorId, dSection); - caDMO.StartSectionApproval(issueID, qaId, dSection); - NotifySectionApprover(issueID, qaId, dSection); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw new Exception(e.Message); - } - } - [HttpPost] - public ActionResult ApproveSection(int issueID, string dSection) - { - try - { - int userID = (int)Session[GlobalVars.SESSION_USERID]; - CorrectiveAction caItem = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); - caDMO.ApproveSection(issueID, userID, dSection); - bool isLastApprover = caDMO.IsLastSectionApprover(issueID, dSection); - if (isLastApprover) - { - if(dSection == "D5D6D7") - { - NotifyForD5D6D7Validation(issueID, caItem.D1AssigneeID, dSection); - NotifyForD5D6D7Validation(issueID, caItem.RequestorID, dSection); - NotifyForD5D6D7Validation(issueID, caItem.QAID, dSection); - - //Notify AI owners of pending action items - List actionItems = caDMO.GetD5D6CorrectivetActions(issueID).ToList(); - foreach(var item in actionItems) - { - NotifyActionItemOwner(issueID, item.ECD, item.CurrentResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); - } - } - else - { - NotifyUsersDSectionApproved(issueID, caItem.D1AssigneeID, dSection); - NotifyUsersDSectionApproved(issueID, caItem.RequestorID, dSection); - NotifyUsersDSectionApproved(issueID, caItem.QAID, dSection); - } - //TODO Notify Requestor for approval - return Content("Successfully Saved, Last Approver"); - } - else - { - return Content("Successfully Saved, More Approvers"); - } - - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); - return Content(e.Message); - //return Content(ex.Message); - } - } - [HttpPost] - public ActionResult RejectSection(int issueID, string dSection, string comments) - { - try - { - - int userID = (int)Session[GlobalVars.SESSION_USERID]; - CorrectiveAction ca = caDMO.GetCAItem(issueID, userID); - caDMO.RejectSection(issueID, userID, dSection, comments); - //Notify Rejection to assignee and requestor - int assigneeId = ca.D1AssigneeID; - int requestorId = ca.RequestorID; - int qaId = ca.QAID; - NotifySectionRejection(issueID, assigneeId, userID, dSection, comments); - NotifySectionRejection(issueID, requestorId, userID, dSection, comments); - NotifySectionRejection(issueID, qaId, userID, dSection, comments); - - return Content("Successfully Saved"); - } - catch(Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n " + "Reject\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString }); - return Content(e.Message); - } - } - public void NotifySectionRejection(int issueID, int recipientUserId, int loggedInUserId, string section, string comment) - { - try - { - LoginModel recipient = userDMO.GetUserByID(recipientUserId); - string recipientEmail = recipient.Email; - - LoginModel loggedInUser = userDMO.GetUserByID(loggedInUserId); - - string emailTemplate = "CorrectiveActionSectionRejection.txt"; - //string userEmail = string.Empty; - string subject = "Corrective Action Rejection - " + Functions.ReturnCANoStringFormat(issueID); - string senderName = "CorrectiveAction"; - - //subject = "Corrective Action Assignment"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[6]; - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = section; - emailparams[4] = loggedInUser.FirstName + " " + loggedInUser.LastName; - emailparams[5] = comment; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, recipientEmail, null, subject, emailparams); - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; - - - } - - } - public void NotifyForD5D6D7Validation(int issueID, int userId, string dSection) - { - try - { - string userEmail = userDMO.GetUserEmailByID(userId.ToString()); - - string emailTemplate = "CorrectiveActionSectionApproved.txt"; - //string userEmail = string.Empty; - string subject = "Corrective Action Section Approval - " + Functions.ReturnCANoStringFormat(issueID); - string senderName = "CorrectiveAction"; - - //subject = "Corrective Action Assignment"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = dSection; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; - - - } - - } - public void NotifyUsersDSectionApproved(int issueID, int userId, string dSection) - { - try - { - string userEmail = userDMO.GetUserEmailByID(userId.ToString()); - - string emailTemplate = "CorrectiveActionSectionApproved.txt"; - //string userEmail = string.Empty; - string subject = "Corrective Action Section Approval - " + Functions.ReturnCANoStringFormat(issueID); - string senderName = "CorrectiveAction"; - - //subject = "Corrective Action Assignment"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = Functions.ReturnCANoStringFormat(issueID); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = dSection; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; - - - } - - } - public DateTime SetD3DueDate(int caNo) - { - DateTime d3DueDate = caDMO.SetCAD3DueDate(caNo); - - return d3DueDate; - } - public DateTime SetD5D7DueDate(int caNo) - { - DateTime d5d7DueDate = caDMO.SetCAD5D7DueDate(caNo); - return d5d7DueDate; - } - public bool ProcessCARDueDates() - { - bool isSuccess = false; - List dueCAs = caDMO.GetCAD3D5D7Due().ToList(); - - foreach (var dueCA in dueCAs) - { - CorrectiveAction ca = caDMO.GetCAItemReadOnly(dueCA.CANo, 999); - int assigneeID = ca.D1AssigneeID; - LoginModel user = userDMO.GetUserByID(assigneeID); - - try - { - string emailTemplate = "D3D5D7Due.txt"; - //string userEmail = string.Empty; - string subject = "Corrective Action " + dueCA.ItemDue + " " + dueCA.ExpiryType + " - " + Functions.ReturnCANoStringFormat(dueCA.CANo); - string senderName = "CorrectiveAction"; - string[] emailparams = new string[7]; - emailparams[0] = Functions.ReturnCANoStringFormat(dueCA.CANo); - emailparams[1] = dueCA.CANo.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = dueCA.ExpiryType; - emailparams[4] = dueCA.ItemDue; - if (ca.D3DueDate != null) - { - emailparams[5] = ca.D3DueDate.ToString(); - } - else - { - emailparams[5] = "N/A"; - } - if(ca.D5D7DueDate != null) - { - emailparams[6] = ca.D5D7DueDate.ToString(); - } - else - { - emailparams[6] = "N/A"; - } - - //subject = "Corrective Action Assignment"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, user.Email, "jonathan.ouellette@infineon.com", subject, emailparams); - caDMO.SetD3D5D7NotificationDate(dueCA.CANo, dueCA.ItemDue); - isSuccess = true; - - } - catch (Exception e) - { - isSuccess = false; - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + dueCA.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Corrective Action - ProcessCARDueDates\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = dueCA.CANo, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "ProcessCARDueDates - Called via API - " + exceptionString }); - - - } - - } - return true; - } - public void ProcessCAForFollowUp() - { - - } - } -} + public void NotifyAssignee(int issueID, int? responsibleOwnerID, string template, DateTime? D3DueDate, DateTime? D5D7DueDate) { + try { + string emailSentList = ""; + + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + string email = MiscDMO.GetEmail(responsibleOwnerID); + + string emailTemplate = template; + string userEmail = string.Empty; + string subject = "CAR Assigned - " + Functions.ReturnCANoStringFormat(issueID); + string senderName = "CorrectiveAction"; + + string D3DueDateString = D3DueDate != null ? D3DueDate.ToString() : "N/A"; + string D5D7DueDateString = D5D7DueDate != null ? D5D7DueDate.ToString() : "N/A"; + + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[6]; + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = issueID.ToString(); + emailparams[4] = D3DueDateString; + emailparams[5] = D5D7DueDateString; + //userEmail = email; + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); + emailSentList += email + ","; + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); + //throw e; + } + } + + public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID, string template) { + try { + string emailSentList = ""; + + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + string email = MiscDMO.GetEmail(responsibleOwnerID); + + string emailTemplate = template; + string userEmail = string.Empty; + string subject = "Action Item in " + Functions.ReturnCANoStringFormat(issueID); + string senderName = "CorrectiveAction"; + + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = dueDate.ToString(); + emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction); + emailparams[3] = GlobalVars.hostURL; + emailparams[4] = issueID.ToString(); + //userEmail = email; + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); + emailSentList += email + ","; + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); + //throw e; + } + } + public void NotifyActionItemCompletion(int issueID, DateTime? dueDate, int? recipientId, string template) { + try { + string emailSentList = ""; + + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + string email = MiscDMO.GetEmail(recipientId); + + string emailTemplate = template; + string userEmail = string.Empty; + string subject = "8D Action Item Completion - " + Functions.ReturnCANoStringFormat(issueID); + string senderName = "CorrectiveAction"; + + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = dueDate.ToString(); + emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction); + emailparams[3] = GlobalVars.hostURL; + emailparams[4] = issueID.ToString(); + //userEmail = email; + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); + emailSentList += email + ","; + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemCompletion\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); + //throw e; + } + } + + public void NotifyClosureOf8D(int issueID) { + try { + string emailSentList = ""; + + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + List emailIst = MiscDMO.Get8DEmailListForClosureNotification(issueID); + + string emailTemplate = "CorrectiveActionClosed.txt"; + //string userEmail = string.Empty; + string subject = "Corrective Action Follow Up Closure - " + Functions.ReturnCANoStringFormat(issueID); + string senderName = "CorrectiveAction"; + + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[3]; + foreach (string email in emailIst) { + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = GlobalVars.hostURL; + emailparams[2] = issueID.ToString(); + //userEmail = email; + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); + emailSentList += email + ","; + } + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Closure of 8D Item" + ":" + emailSentList }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Closure of 8D:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Closure of 8D - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Closure of 8D Notification - " + exceptionString }); + //throw e; + } + } + public void NotifyCompletionOf8D(int issueID, DateTime? followUpDate) { + try { + string emailSentList = ""; + + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + List emailIst = MiscDMO.Get8DEmailListForClosureNotification(issueID); + + string emailTemplate = "CorrectiveActionCompleted.txt"; + //string userEmail = string.Empty; + string subject = "Corrective Action Completion - " + Functions.ReturnCANoStringFormat(issueID); + string senderName = "CorrectiveAction"; + + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + foreach (string email in emailIst) { + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = GlobalVars.hostURL; + emailparams[2] = issueID.ToString(); + emailparams[3] = followUpDate.ToString(); + //userEmail = email; + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams); + emailSentList += email + ","; + } + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Closure of 8D Item" + ":" + emailSentList }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Closure of 8D:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Closure of 8D - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Closure of 8D Notification - " + exceptionString }); + //throw e; + } + } + public void StartSectionApproval(int issueID, string dSection) { + try { + CorrectiveAction ca = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); + + int requestorId = ca.RequestorID; + int qaId = ca.QAID; + //int userID = (int)Session[GlobalVars.SESSION_USERID]; + + caDMO.StartSectionApproval(issueID, requestorId, dSection); + NotifySectionApprover(issueID, requestorId, dSection); + caDMO.StartSectionApproval(issueID, qaId, dSection); + NotifySectionApprover(issueID, qaId, dSection); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw new Exception(e.Message); + } + } + [HttpPost] + public ActionResult ApproveSection(int issueID, string dSection) { + try { + int userID = (int)Session[GlobalVars.SESSION_USERID]; + CorrectiveAction caItem = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); + caDMO.ApproveSection(issueID, userID, dSection); + bool isLastApprover = caDMO.IsLastSectionApprover(issueID, dSection); + if (isLastApprover) { + if (dSection == "D5D6D7") { + NotifyForD5D6D7Validation(issueID, caItem.D1AssigneeID, dSection); + NotifyForD5D6D7Validation(issueID, caItem.RequestorID, dSection); + NotifyForD5D6D7Validation(issueID, caItem.QAID, dSection); + + //Notify AI owners of pending action items + List actionItems = caDMO.GetD5D6CorrectivetActions(issueID).ToList(); + foreach (var item in actionItems) { + NotifyActionItemOwner(issueID, item.ECD, item.CurrentResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); + } + } else { + NotifyUsersDSectionApproved(issueID, caItem.D1AssigneeID, dSection); + NotifyUsersDSectionApproved(issueID, caItem.RequestorID, dSection); + NotifyUsersDSectionApproved(issueID, caItem.QAID, dSection); + } + //TODO Notify Requestor for approval + return Content("Successfully Saved, Last Approver"); + } else { + return Content("Successfully Saved, More Approvers"); + } + + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); + return Content(e.Message); + //return Content(ex.Message); + } + } + [HttpPost] + public ActionResult RejectSection(int issueID, string dSection, string comments) { + try { + + int userID = (int)Session[GlobalVars.SESSION_USERID]; + CorrectiveAction ca = caDMO.GetCAItem(issueID, userID); + caDMO.RejectSection(issueID, userID, dSection, comments); + //Notify Rejection to assignee and requestor + int assigneeId = ca.D1AssigneeID; + int requestorId = ca.RequestorID; + int qaId = ca.QAID; + NotifySectionRejection(issueID, assigneeId, userID, dSection, comments); + NotifySectionRejection(issueID, requestorId, userID, dSection, comments); + NotifySectionRejection(issueID, qaId, userID, dSection, comments); + + return Content("Successfully Saved"); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Reject\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString }); + return Content(e.Message); + } + } + public void NotifySectionRejection(int issueID, int recipientUserId, int loggedInUserId, string section, string comment) { + try { + LoginModel recipient = userDMO.GetUserByID(recipientUserId); + string recipientEmail = recipient.Email; + + LoginModel loggedInUser = userDMO.GetUserByID(loggedInUserId); + + string emailTemplate = "CorrectiveActionSectionRejection.txt"; + //string userEmail = string.Empty; + string subject = "Corrective Action Rejection - " + Functions.ReturnCANoStringFormat(issueID); + string senderName = "CorrectiveAction"; + + //subject = "Corrective Action Assignment"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[6]; + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = section; + emailparams[4] = loggedInUser.FirstName + " " + loggedInUser.LastName; + emailparams[5] = comment; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, recipientEmail, null, subject, emailparams); + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw e; + } + } + public void NotifyForD5D6D7Validation(int issueID, int userId, string dSection) { + try { + string userEmail = userDMO.GetUserEmailByID(userId); + + string emailTemplate = "CorrectiveActionSectionApproved.txt"; + //string userEmail = string.Empty; + string subject = "Corrective Action Section Approval - " + Functions.ReturnCANoStringFormat(issueID); + string senderName = "CorrectiveAction"; + + //subject = "Corrective Action Assignment"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = dSection; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw e; + } + } + + public void NotifyUsersDSectionApproved(int issueID, int userId, string dSection) { + try { + string userEmail = userDMO.GetUserEmailByID(userId); + + string emailTemplate = "CorrectiveActionSectionApproved.txt"; + //string userEmail = string.Empty; + string subject = "Corrective Action Section Approval - " + Functions.ReturnCANoStringFormat(issueID); + string senderName = "CorrectiveAction"; + + //subject = "Corrective Action Assignment"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = Functions.ReturnCANoStringFormat(issueID); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = dSection; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw e; + } + } + public DateTime SetD3DueDate(int caNo) { + DateTime d3DueDate = caDMO.SetCAD3DueDate(caNo); + + return d3DueDate; + } + public DateTime SetD5D7DueDate(int caNo) { + DateTime d5d7DueDate = caDMO.SetCAD5D7DueDate(caNo); + return d5d7DueDate; + } + public bool ProcessCARDueDates() { + bool isSuccess = false; + List dueCAs = caDMO.GetCAD3D5D7Due().ToList(); + + foreach (var dueCA in dueCAs) { + CorrectiveAction ca = caDMO.GetCAItemReadOnly(dueCA.CANo, 999); + int assigneeID = ca.D1AssigneeID; + LoginModel user = userDMO.GetUserByID(assigneeID); + + try { + string emailTemplate = "D3D5D7Due.txt"; + //string userEmail = string.Empty; + string subject = "Corrective Action " + dueCA.ItemDue + " " + dueCA.ExpiryType + " - " + Functions.ReturnCANoStringFormat(dueCA.CANo); + string senderName = "CorrectiveAction"; + string[] emailparams = new string[7]; + emailparams[0] = Functions.ReturnCANoStringFormat(dueCA.CANo); + emailparams[1] = dueCA.CANo.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = dueCA.ExpiryType; + emailparams[4] = dueCA.ItemDue; + if (ca.D3DueDate != null) { + emailparams[5] = ca.D3DueDate.ToString(); + } else { + emailparams[5] = "N/A"; + } + if (ca.D5D7DueDate != null) { + emailparams[6] = ca.D5D7DueDate.ToString(); + } else { + emailparams[6] = "N/A"; + } + + //subject = "Corrective Action Assignment"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, user.Email, "jonathan.ouellette@infineon.com", subject, emailparams); + caDMO.SetD3D5D7NotificationDate(dueCA.CANo, dueCA.ItemDue); + isSuccess = true; + + } catch (Exception e) { + isSuccess = false; + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + dueCA.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - ProcessCARDueDates\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = dueCA.CANo, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "ProcessCARDueDates - Called via API - " + exceptionString }); + + } + + } + return true; + } + + public void ProcessCAForFollowUp() { + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/ECNController.cs b/Fab2ApprovalSystem/Controllers/ECNController.cs index c1e66c6..d00035b 100644 --- a/Fab2ApprovalSystem/Controllers/ECNController.cs +++ b/Fab2ApprovalSystem/Controllers/ECNController.cs @@ -1,1061 +1,788 @@ +using Dapper; + +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; +//using ReportManagement; +using Fab2ApprovalSystem.PdfGenerator; +using Fab2ApprovalSystem.ViewModels; + +using Kendo.Mvc.Extensions; +using Kendo.Mvc.UI; + using System; using System.Collections.Generic; +using System.Configuration; +using System.IO; +//using Ionic.Zip; +using System.IO.Compression; using System.Linq; using System.Web; using System.Web.Mvc; -using Kendo.Mvc.Extensions; -using Kendo.Mvc.UI; -using Fab2ApprovalSystem.Models; -using Fab2ApprovalSystem.DMO; -using Fab2ApprovalSystem.Misc; -using System.IO; -using System.Configuration; -using Fab2ApprovalSystem.ViewModels; -//using Ionic.Zip; -using System.IO.Compression; -//using ReportManagement; -using Fab2ApprovalSystem.PdfGenerator; -using Dapper; -namespace Fab2ApprovalSystem.Controllers -{ - [Authorize] - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - [SessionExpireFilter] - public class ECNController : PdfViewController - { - private const string ECN_PREFIX = "ECN_"; - private const string TECN_PREFIX = "TECN_"; - private const string ETECN_PREFIX = "ETECN_"; +namespace Fab2ApprovalSystem.Controllers; - ECN_DMO ecnDMO = new ECN_DMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); - TrainingDMO trainingDMO = new TrainingDMO(); - UserAccountDMO userDMO = new UserAccountDMO(); +[Authorize] +[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +[SessionExpireFilter] +public class ECNController : PdfViewController { + private const string ECN_PREFIX = "ECN_"; + private const string TECN_PREFIX = "TECN_"; + private const string ETECN_PREFIX = "ETECN_"; - - // - // GET: /ECN/ - public ActionResult Index() - { - return View(); - - } + ECN_DMO ecnDMO = new ECN_DMO(); + WorkflowDMO wfDMO = new WorkflowDMO(); + TrainingDMO trainingDMO = new TrainingDMO(); + UserAccountDMO userDMO = new UserAccountDMO(); + private readonly AppSettings _AppSettings; - // - // GET: /ECN/Details/5 - public ActionResult Details(int id) - { - return View(); - } + public ECNController(AppSettings appSettings) { + _AppSettings = appSettings; + } - // - // GET: /ECN/Create - public ActionResult Create() - { - - - ECN ecn = new ECN(); - try - { - // TODO: Add insert logic here + // + // GET: /ECN/ + public ActionResult Index() { + return View(); + } + // + // GET: /ECN/Details/5 + public ActionResult Details(int id) { + return View(); + } - ecn.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; - ecnDMO.InsertECN(ecn); - return RedirectToAction("Edit", new { issueID = ecn.ECNNumber }); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecn.ECNNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument - ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecn.ECNNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); - throw new Exception(e.Message); - + // + // GET: /ECN/Create + public ActionResult Create() { + + ECN ecn = new ECN(); + try { + // TODO: Add insert logic here + + ecn.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + ecnDMO.InsertECN(ecn); + return RedirectToAction("Edit", new { issueID = ecn.ECNNumber }); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecn.ECNNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecn.ECNNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + throw new Exception(e.Message); } + } - // - - // - // GET: /ECN/Edit/5 - public ActionResult Edit(int issueID) - { + // - int isITARCompliant = 1; - ECN ecn = new ECN(); - //GlobalVars.DocumentType docType = GlobalVars.DocumentType.ECN; - try + // + // GET: /ECN/Edit/5 + public ActionResult Edit(int issueID) { + int isITARCompliant = 1; + ECN ecn = new ECN(); + //GlobalVars.DocumentType docType = GlobalVars.DocumentType.ECN; + try { + + //ecn = ecnDMO.GetECN(issueID); + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + //if (ecn.IsTECN && ecn.IsEmergencyTECN) + // docType = GlobalVars.DocumentType.EECN; + + if (isITARCompliant == 0) // not ITAR Compliant { - - //ecn = ecnDMO.GetECN(issueID); - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + return View("UnAuthorizedAccess"); + } else { - //if (ecn.IsTECN && ecn.IsEmergencyTECN) - // docType = GlobalVars.DocumentType.EECN; - - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); + //if (ecn.CloseDate != null) + //{ + // return RedirectToAction("ReadOnly", new { issueID = issueID }); + //} + if (ecn.Deleted) { + return RedirectToAction("ReadOnly", new { issueID = issueID }); } - else - { + if (ecn.CurrentStep >= 1) { + return RedirectToAction("EditApproval", new { issueID = issueID }); + } else { + //ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - //if (ecn.CloseDate != null) - //{ - // return RedirectToAction("ReadOnly", new { issueID = issueID }); - //} - if (ecn.Deleted) - { + if ((ecn.RecordLockIndicator && ecn.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID])) { return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - if (ecn.CurrentStep >= 1) - { - return RedirectToAction("EditApproval", new { issueID = issueID }); - } - else - { - //ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - if ((ecn.RecordLockIndicator && ecn.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID])) - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - else - { - ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - ViewBag.Departments = ecnDMO.GetDepartments(); - ViewBag.AffectedModules = ecnDMO.GetModules(); - ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); - ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); - ViewBag.AcknowledgementTrainingByIDs = trainingDMO.GetTrainingGroups(); - ViewBag.Categories = ecnDMO.GetCategories(); - ViewBag.ProductFamilies = ecnDMO.GetProductFamilies(); - return View(ecn); - } - } - } - - - - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent( - String.Format("{0}\r\nEdit ECN\r\n{1}\r\n{2}", @User?.Identity?.Name, ecn?.ECNNumber, e.InnerException), - System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); - return View("Error"); - } - - } - - // - // POST: /ECN/Edit/5 - [HttpPost] - public void Edit(ECN ecn) - { - try - { - // TODO: Add update logic here - - ecnDMO.UpdateECN(ecn);; - } - catch - { - //return View(); - } - } - - //public JsonResult GetTechnology(int? area) - //{ - // List respIssue = ecnDMO.GetECNTechnology(area); - - // var data = respIssue.Select(s => new SelectListItem { Value = s.TechnologyID.ToString(), Text = s.Technology }); - // return Json(data, JsonRequestBehavior.AllowGet); - //} - - - /// - /// - /// - /// - /// - public ActionResult ReadOnly(int issueID) - { - int isITARCompliant = 1; - ECN ecn = new ECN(); - try - { - - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - bool trainingRequired = ecn.TrainingRequired; - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); - } - else - { - GlobalVars.DocumentType docType = (ecn.ExpirationInProgress || ecn.ExpirationProcessed || ecn.CancellationInProgress || ecn.CancellationApproved)? GlobalVars.DocumentType.TECNCancelledExpired : GlobalVars.DocumentType.ECN; - if (ecn.IsEmergencyTECN) - docType = GlobalVars.DocumentType.EECN; - - List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType); - ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (approver == null) - ViewBag.IsApprover = "false"; - else - ViewBag.IsApprover = "true"; - - - if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID) - ViewBag.IsOriginator = "true"; - else - ViewBag.IsOriginator = "false"; - int trainingId = trainingDMO.GetTrainingId(ecn.ECNNumber); - if(trainingId > 0) - { - bool? trainingStatus = (trainingDMO.GetTraining(trainingId)).Status; - - ViewBag.TrainingID = trainingId; - ViewBag.TrainingStatus = trainingStatus; - } - - ViewBag.Departments = ecnDMO.GetDepartments(); - ViewBag.AffectedModules = ecnDMO.GetModules(); - ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); - ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); - ViewBag.AcknowledgementTrainingByIDs = trainingDMO.GetTrainingGroups(); - ViewBag.Categories = ecnDMO.GetCategories(); - ViewBag.ProductFamilies = ecnDMO.GetProductFamilies(); - ViewBag.ECNNumber = ecn.ECNNumber; - - return View(ecn); - } - } - - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - - } - } - [OutputCache(Duration = 60, VaryByCustom = "host")] - public ActionResult ECNTrainingView(int issueID) - { - int isITARCompliant = 1; - ECN ecn = new ECN(); - try - { - - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - //bool trainingRequired = ecn.TrainingRequired; - if (isITARCompliant == 0) // not ITAR Compliant - { - return PartialView("UnAuthorizedAccess"); - } - else - { - ViewBag.Departments = ecnDMO.GetDepartments(); - ViewBag.AffectedModules = ecnDMO.GetModules(); - ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); - ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); - ViewBag.AcknowledgementTrainingByIDs = ecnDMO.GetECNAcknowledgementTrainingBy(); - ViewBag.Categories = ecnDMO.GetCategories(); - ViewBag.ProductFamilies = ecnDMO.GetProductFamilies(); - ViewBag.ECNNumber = ecn.ECNNumber; - - return PartialView(ecn); - } - } - - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - - } - } - public ActionResult Acknowledge(int issueID) - { - int isITARCompliant = 1; - ECN ecn = new ECN(); - try - { - - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); - } - else - { - GlobalVars.DocumentType docType = (ecn.ExpirationInProgress || ecn.ExpirationProcessed || ecn.CancellationInProgress || ecn.CancellationApproved) ? GlobalVars.DocumentType.TECNCancelledExpired : GlobalVars.DocumentType.ECN; - if (ecn.IsEmergencyTECN) - docType = GlobalVars.DocumentType.EECN; - - List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType); - ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (approver == null) - ViewBag.IsApprover = "false"; - else - ViewBag.IsApprover = "true"; - - - if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID) - ViewBag.IsOriginator = "true"; - else - ViewBag.IsOriginator = "false"; - - ViewBag.Departments = ecnDMO.GetDepartments(); - ViewBag.AffectedModules = ecnDMO.GetModules(); - ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); - ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); - ViewBag.AcknowledgementTrainingByIDs = ecnDMO.GetECNAcknowledgementTrainingBy(); - ViewBag.Categories = ecnDMO.GetCategories(); - ViewBag.ProductFamilies = ecnDMO.GetProductFamilies(); - - return View(ecn); - } - } - - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - - } - } - - - /// - /// - /// - /// - /// - public ActionResult EditApproval(int issueID) - { - int isITARCompliant = 1; - ECN ecn = new ECN(); - try - { - - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); - } - else - { - if (ecn.Deleted) - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - - GlobalVars.DocumentType docType = GlobalVars.DocumentType.ECN; - if (ecn.IsEmergencyTECN) - docType = GlobalVars.DocumentType.EECN; - if (ecn.ExpirationInProgress || ecn.ExpirationProcessed || ecn.CancellationInProgress || ecn.CancellationApproved) - docType = GlobalVars.DocumentType.TECNCancelledExpired; - - List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType); - ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (approver == null) - ViewBag.IsApprover = "false"; - else - ViewBag.IsApprover = "true"; - - - if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID) - ViewBag.IsOriginator = "true"; - else - ViewBag.IsOriginator = "false"; - - - - //============== - - //if ((ViewBag.IsApprover == "true" && ecn.CancellationInProgress) - // || - // (ViewBag.IsApprover == "true" && ecn.ExpirationInProgress) - // || - // ( - // (ViewBag.IsApprover == "true" && ecn.TECNExtensionState && ecn.CurrentStep > 2) - // || (ViewBag.IsApprover == "true" && ecn.CurrentStep == 3 && ecn.ConvertedFromNumber != null) - // ) - // || - // (ViewBag.IsApprover == "true") - // || - // (ecn.CurrentStep <= 2 && ecn.CloseDate == null && !ecn.ReSubmitted && ecn.ConvertedFromNumber == null && ecn.TECNExtensionState == false) - //) - int trainingId = trainingDMO.GetTrainingId(ecn.ECNNumber); - if (trainingId > 0) - { - bool? trainingStatus = (trainingDMO.GetTraining(trainingId)).Status; - - ViewBag.TrainingID = trainingId; - ViewBag.TrainingStatus = trainingStatus; - } - if (ViewBag.IsApprover == "true" || ViewBag.IsOriginator == "true") - { + } else { ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - if (ecn.RecordLockIndicator && ecn.RecordLockedBy == (int)Session[GlobalVars.SESSION_USERID]) - - { - - ViewBag.Departments = ecnDMO.GetDepartments(); - ViewBag.AffectedModules = ecnDMO.GetModules(); - ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); - ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); - ViewBag.AcknowledgementTrainingByIDs = trainingDMO.GetTrainingGroups(); - ViewBag.Categories = ecnDMO.GetCategories(); - ViewBag.ProductFamilies = ecnDMO.GetProductFamilies(); - - return View(ecn); - } - else - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } + ViewBag.Departments = ecnDMO.GetDepartments(); + ViewBag.AffectedModules = ecnDMO.GetModules(); + ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); + ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); + ViewBag.AcknowledgementTrainingByIDs = trainingDMO.GetTrainingGroups(); + ViewBag.Categories = ecnDMO.GetCategories(); + ViewBag.ProductFamilies = ecnDMO.GetProductFamilies(); + return View(ecn); } - else - { + } + } + + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent( + _AppSettings, + String.Format("{0}\r\nEdit ECN\r\n{1}\r\n{2}", @User?.Identity?.Name, ecn?.ECNNumber, e.InnerException), + System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); + return View("Error"); + } + } + + // + // POST: /ECN/Edit/5 + [HttpPost] + public void Edit(ECN ecn) { + try { + // TODO: Add update logic here + + ecnDMO.UpdateECN(ecn); + ; + } catch { + //return View(); + } + } + + public ActionResult ReadOnly(int issueID) { + int isITARCompliant = 1; + ECN ecn = new ECN(); + try { + + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + bool trainingRequired = ecn.TrainingRequired; + if (isITARCompliant == 0) // not ITAR Compliant + { + return View("UnAuthorizedAccess"); + } else { + GlobalVars.DocumentType docType = (ecn.ExpirationInProgress || ecn.ExpirationProcessed || ecn.CancellationInProgress || ecn.CancellationApproved) ? GlobalVars.DocumentType.TECNCancelledExpired : GlobalVars.DocumentType.ECN; + if (ecn.IsEmergencyTECN) + docType = GlobalVars.DocumentType.EECN; + + List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (approver == null) + ViewBag.IsApprover = "false"; + else + ViewBag.IsApprover = "true"; + + if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID) + ViewBag.IsOriginator = "true"; + else + ViewBag.IsOriginator = "false"; + int trainingId = trainingDMO.GetTrainingId(ecn.ECNNumber); + if (trainingId > 0) { + bool? trainingStatus = (trainingDMO.GetTraining(trainingId)).Status; + + ViewBag.TrainingID = trainingId; + ViewBag.TrainingStatus = trainingStatus; + } + + ViewBag.Departments = ecnDMO.GetDepartments(); + ViewBag.AffectedModules = ecnDMO.GetModules(); + ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); + ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); + ViewBag.AcknowledgementTrainingByIDs = trainingDMO.GetTrainingGroups(); + ViewBag.Categories = ecnDMO.GetCategories(); + ViewBag.ProductFamilies = ecnDMO.GetProductFamilies(); + ViewBag.ECNNumber = ecn.ECNNumber; + + return View(ecn); + } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); + } + } + [OutputCache(Duration = 60, VaryByCustom = "host")] + public ActionResult ECNTrainingView(int issueID) { + int isITARCompliant = 1; + ECN ecn = new ECN(); + try { + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + //bool trainingRequired = ecn.TrainingRequired; + if (isITARCompliant == 0) // not ITAR Compliant + { + return PartialView("UnAuthorizedAccess"); + } else { + ViewBag.Departments = ecnDMO.GetDepartments(); + ViewBag.AffectedModules = ecnDMO.GetModules(); + ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); + ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); + ViewBag.AcknowledgementTrainingByIDs = ecnDMO.GetECNAcknowledgementTrainingBy(); + ViewBag.Categories = ecnDMO.GetCategories(); + ViewBag.ProductFamilies = ecnDMO.GetProductFamilies(); + ViewBag.ECNNumber = ecn.ECNNumber; + + return PartialView(ecn); + } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); + } + } + public ActionResult Acknowledge(int issueID) { + int isITARCompliant = 1; + ECN ecn = new ECN(); + try { + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + if (isITARCompliant == 0) // not ITAR Compliant + { + return View("UnAuthorizedAccess"); + } else { + GlobalVars.DocumentType docType = (ecn.ExpirationInProgress || ecn.ExpirationProcessed || ecn.CancellationInProgress || ecn.CancellationApproved) ? GlobalVars.DocumentType.TECNCancelledExpired : GlobalVars.DocumentType.ECN; + if (ecn.IsEmergencyTECN) + docType = GlobalVars.DocumentType.EECN; + + List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (approver == null) + ViewBag.IsApprover = "false"; + else + ViewBag.IsApprover = "true"; + + if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID) + ViewBag.IsOriginator = "true"; + else + ViewBag.IsOriginator = "false"; + + ViewBag.Departments = ecnDMO.GetDepartments(); + ViewBag.AffectedModules = ecnDMO.GetModules(); + ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); + ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); + ViewBag.AcknowledgementTrainingByIDs = ecnDMO.GetECNAcknowledgementTrainingBy(); + ViewBag.Categories = ecnDMO.GetCategories(); + ViewBag.ProductFamilies = ecnDMO.GetProductFamilies(); + + return View(ecn); + } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); + } + } + + public ActionResult EditApproval(int issueID) { + int isITARCompliant = 1; + ECN ecn = new ECN(); + try { + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + if (isITARCompliant == 0) // not ITAR Compliant + { + return View("UnAuthorizedAccess"); + } else { + if (ecn.Deleted) { + return RedirectToAction("ReadOnly", new { issueID = issueID }); + } + + GlobalVars.DocumentType docType = GlobalVars.DocumentType.ECN; + if (ecn.IsEmergencyTECN) + docType = GlobalVars.DocumentType.EECN; + if (ecn.ExpirationInProgress || ecn.ExpirationProcessed || ecn.CancellationInProgress || ecn.CancellationApproved) + docType = GlobalVars.DocumentType.TECNCancelledExpired; + + List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (approver == null) + ViewBag.IsApprover = "false"; + else + ViewBag.IsApprover = "true"; + + if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID) + ViewBag.IsOriginator = "true"; + else + ViewBag.IsOriginator = "false"; + + //============== + + //if ((ViewBag.IsApprover == "true" && ecn.CancellationInProgress) + // || + // (ViewBag.IsApprover == "true" && ecn.ExpirationInProgress) + // || + // ( + // (ViewBag.IsApprover == "true" && ecn.TECNExtensionState && ecn.CurrentStep > 2) + // || (ViewBag.IsApprover == "true" && ecn.CurrentStep == 3 && ecn.ConvertedFromNumber != null) + // ) + // || + // (ViewBag.IsApprover == "true") + // || + // (ecn.CurrentStep <= 2 && ecn.CloseDate == null && !ecn.ReSubmitted && ecn.ConvertedFromNumber == null && ecn.TECNExtensionState == false) + //) + int trainingId = trainingDMO.GetTrainingId(ecn.ECNNumber); + if (trainingId > 0) { + bool? trainingStatus = (trainingDMO.GetTraining(trainingId)).Status; + + ViewBag.TrainingID = trainingId; + ViewBag.TrainingStatus = trainingStatus; + } + if (ViewBag.IsApprover == "true" || ViewBag.IsOriginator == "true") { + ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + if (ecn.RecordLockIndicator && ecn.RecordLockedBy == (int)Session[GlobalVars.SESSION_USERID]) { + + ViewBag.Departments = ecnDMO.GetDepartments(); + ViewBag.AffectedModules = ecnDMO.GetModules(); + ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); + ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); + ViewBag.AcknowledgementTrainingByIDs = trainingDMO.GetTrainingGroups(); + ViewBag.Categories = ecnDMO.GetCategories(); + ViewBag.ProductFamilies = ecnDMO.GetProductFamilies(); + + return View(ecn); + } else { return RedirectToAction("ReadOnly", new { issueID = issueID }); } - - //if (ecn.CloseDate != null ) - //{ - // return RedirectToAction("ReadOnly", new { issueID = issueID }); - //} - - //if ( - // (ecn.RecordLockIndicator && ecn.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) - // || ((ViewBag.IsApprover == "false") && (ViewBag.IsOriginator == "false")) - // ) - //{ - // return RedirectToAction("ReadOnly", new { issueID = issueID }); - //} - //else - //{ - // ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - // ViewBag.Departments = ecnDMO.GetDepartments(); - // ViewBag.AffectedModules = ecnDMO.GetModules(); - // ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); - // ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); - // ViewBag.AcknowledgementTrainingByIDs = ecnDMO.GetECNAcknowledgementTrainingBy(); - - - // return View(ecn); - //} + } else { + return RedirectToAction("ReadOnly", new { issueID = issueID }); } + + //if (ecn.CloseDate != null ) + //{ + // return RedirectToAction("ReadOnly", new { issueID = issueID }); + //} + + //if ( + // (ecn.RecordLockIndicator && ecn.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) + // || ((ViewBag.IsApprover == "false") && (ViewBag.IsOriginator == "false")) + // ) + //{ + // return RedirectToAction("ReadOnly", new { issueID = issueID }); + //} + //else + //{ + // ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + // ViewBag.Departments = ecnDMO.GetDepartments(); + // ViewBag.AffectedModules = ecnDMO.GetModules(); + // ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); + // ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies(); + // ViewBag.AcknowledgementTrainingByIDs = ecnDMO.GetECNAcknowledgementTrainingBy(); + + // return View(ecn); + //} + } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); + } + } + public ActionResult AttachSave(IEnumerable files, int ecnNumber) { + string returnString = ""; + // The Name of the Upload component is "files" + if (files != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in files) { + returnString = ecnDMO.AttachSave(_AppSettings, ecnNumber, returnString, userId, file.FileName, file.InputStream); } } + return Content(returnString); + } - /// - /// - /// - /// - /// - public ActionResult AttachSave(IEnumerable files, int ecnNumber) - { - string returnString = ""; - // The Name of the Upload component is "files" - if (files != null) - { - foreach (var file in files) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - var fileName = Path.GetFileName(file.FileName); + public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int ecnNumber) { + return Json(ecnDMO.GetECNAttachments(ecnNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } - string ecnFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString(); + public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int ecnNumber) { + return Json(ecnDMO.GetECNApprovalLogHistory(ecnNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } - DirectoryInfo di = new DirectoryInfo(ecnFolderPath); - if (!di.Exists) - try - { - di.Create(); - } - catch - { - returnString = "Error creating ECN directory."; - } - if (returnString == "") - { - var physicalPath = Path.Combine(ecnFolderPath, fileName); - if (!System.IO.File.Exists(physicalPath)) - { - file.SaveAs(physicalPath); - ECNAttachment attach = new ECNAttachment() - { - ECNNumber = ecnNumber, - FileName = fileName, - UserID = (int)Session[GlobalVars.SESSION_USERID], - }; - if (System.IO.File.Exists(physicalPath)) - { + //[AcceptVerbs(HttpVerbs.Post)] + + [HttpPost] + public void DeleteAttachment(int attachmentID, string fileName, int ecnNumber) { + try { + if (ModelState.IsValid) { + ecnDMO.DeleteECNAttachment(attachmentID); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + //var physicalPath = Path.Combine(@"C:\Websites\Fab2ApprovalAttachments\ECN\" + ecnNumber.ToString(), fileName); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"ECN\" + ecnNumber.ToString(), fileName); + + FileInfo f = new FileInfo(physicalPath); + + if (f.Exists) + f.Delete(); - ecnDMO.InsertECNAttachment(attach); - } - else - { - returnString = "File was not uploaded to server."; - } - } - else - { - returnString = "Cannot have duplicate file names."; - } - } - } } - return Content(returnString); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n DeleteAttachment ECN\r\n" + ecnNumber.ToString() + detailedException.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Delete Attachment " + exceptionString }); + throw new Exception(e.Message); + } + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult Attachment_Destroy([DataSourceRequest] DataSourceRequest request, Attachment attachment) { + try { + if (attachment != null && ModelState.IsValid) { + ecnDMO.DeleteECNAttachment(attachment.AttachmentID); + + } + } catch (Exception e) { + //string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + //Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AttachmentID ECN\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + //EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); + //throw new Exception(e.Message); } - /// - /// - /// - /// - /// - /// - public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int ecnNumber) - { - return Json(ecnDMO.GetECNAttachments(ecnNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } + return Json(new[] { attachment }.ToDataSourceResult(request, ModelState)); + } - /// - /// - /// - /// - /// - /// - public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int ecnNumber) - { - return Json(ecnDMO.GetECNApprovalLogHistory(ecnNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - - - //[AcceptVerbs(HttpVerbs.Post)] - /// - /// - /// - /// - /// - [HttpPost] - public void DeleteAttachment(int attachmentID, string fileName, int ecnNumber) - { - try + /// + /// + public ActionResult SubmitDocument(int ecnNumber, int documentType, string ecnTypeString) { + int isITARCompliant = 1; + try { + int appoverCount = ecnDMO.SubmitDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, out isITARCompliant); + if (isITARCompliant == 0) // not ITAR Compliant { - if (ModelState.IsValid) - { - ecnDMO.DeleteECNAttachment(attachmentID); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - //var physicalPath = Path.Combine(@"C:\Websites\Fab2ApprovalAttachments\ECN\" + ecnNumber.ToString(), fileName); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"ECN\" + ecnNumber.ToString(), fileName); - - - FileInfo f = new FileInfo(physicalPath); - - if (f.Exists) - f.Delete(); - - } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n DeleteAttachment ECN\r\n" + ecnNumber.ToString() + detailedException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Delete Attachment " + exceptionString }); - throw new Exception(e.Message); - - } - } - - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult Attachment_Destroy([DataSourceRequest] DataSourceRequest request, Attachment attachment) - { - try - { - if (attachment != null && ModelState.IsValid) - { - ecnDMO.DeleteECNAttachment(attachment.AttachmentID); - - } - } - catch (Exception e) - { - //string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - //Functions.WriteEvent(@User.Identity.Name + "\r\n AttachmentID ECN\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - //EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); - //throw new Exception(e.Message); - - } - - - return Json(new[] { attachment }.ToDataSourceResult(request, ModelState)); - } - - - /// - /// - /// - /// - public ActionResult SubmitDocument(int ecnNumber, int documentType, string ecnTypeString) - { - int isITARCompliant = 1; - try - { - - int appoverCount = ecnDMO.SubmitDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, out isITARCompliant); - if (isITARCompliant == 0) // not ITAR Compliant - { - // the content gets evaluated on the client side - return Content("ITAR"); - } - else - { - - if (appoverCount > 0) - { - NotifyApprovers(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, documentType, ecnTypeString); - } - else - { - // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval - Approve(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, "", documentType, ecnTypeString); // this is the Submit Level Approval - - } - - - if (Request.IsAjaxRequest()) - { - // the content gets evaluated on the client side - return Content("Redirect"); - } - else - return Content("Invalid"); - } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); - throw new Exception(e.Message); - - } - } - - - /// - /// - /// - /// - /// - /// - /// - /// - public ActionResult SubmitTECNExtension(int ecnNumber, int documentType, string ecnTypeString, DateTime extensionDate) - { - try - { - - - - int appoverCount = ecnDMO.SubmitTECNExtensionDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, extensionDate); - - // Update the TECN Extension History - try - { - //ecnDMO.TECNExtensionLog(ecnNumber, extensionDate); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n TECNExtensionLog\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "TECNExtensionLog - " + exceptionString }); - - } - - if (appoverCount > 0) + // the content gets evaluated on the client side + return Content("ITAR"); + } else { + if (appoverCount > 0) { NotifyApprovers(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, documentType, ecnTypeString); - else - { + } else { // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval Approve(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, "", documentType, ecnTypeString); // this is the Submit Level Approval } - - if (Request.IsAjaxRequest()) - { + if (Request.IsAjaxRequest()) { + // the content gets evaluated on the client side return Content("Redirect"); - } - else + } else return Content("Invalid"); } - catch (Exception e) - { + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public ActionResult SubmitTECNExtension(int ecnNumber, int documentType, string ecnTypeString, DateTime extensionDate) { + try { + int appoverCount = ecnDMO.SubmitTECNExtensionDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, extensionDate); + + // Update the TECN Extension History + try { + //ecnDMO.TECNExtensionLog(ecnNumber, extensionDate); + } catch (Exception e) { string detailedException = ""; - try - { + try { detailedException = e.InnerException.ToString(); - } - catch - { + } catch { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); - throw new Exception(e.Message); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n TECNExtensionLog\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "TECNExtensionLog - " + exceptionString }); } + + if (appoverCount > 0) + NotifyApprovers(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, documentType, ecnTypeString); + else { + // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval + Approve(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, "", documentType, ecnTypeString); // this is the Submit Level Approval + + } + + if (Request.IsAjaxRequest()) { + return Content("Redirect"); + } else + return Content("Invalid"); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + throw new Exception(e.Message); } + } + /// + /// + public ActionResult SubmitDocument_EmergencyTECN(int ecnNumber, int documentType) { + int isITARCompliant = 0; + try { + ecnDMO.SubmitDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, out isITARCompliant); - /// - /// - /// - /// - public ActionResult SubmitDocument_EmergencyTECN(int ecnNumber, int documentType) - { - int isITARCompliant = 0; - try + if (isITARCompliant == 0) // not ITAR Compliant { - - ecnDMO.SubmitDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, out isITARCompliant); - - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("ITAR"); - } - else - { - - if (Request.IsAjaxRequest()) - { - return Content("Redirect"); - } - else - return Content("Invalid"); - } + return View("ITAR"); + } else { + if (Request.IsAjaxRequest()) { + return Content("Redirect"); + } else + return Content("Invalid"); } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument ETECN\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument-ETECN - " + exceptionString }); - throw new Exception(e.Message); - + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument ETECN\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument-ETECN - " + exceptionString }); + throw new Exception(e.Message); } + } + /// + /// + /// + public void Approve(int ecnNumber, byte currentStep, string comments, int documentType, string ecnTypeString) { + try { + bool lastStep = false; + ECN ecn = ecnDMO.GetECN(ecnNumber); + bool lastApprover = wfDMO.Approve(_AppSettings, ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType, ecn.WorkFlowNumber); - /// - /// - /// - /// - /// - /// - public void Approve(int ecnNumber, byte currentStep, string comments, int documentType, string ecnTypeString) - { - try - { - bool lastStep = false; - ECN ecn = ecnDMO.GetECN(ecnNumber); - bool lastApprover = wfDMO.Approve(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType, ecn.WorkFlowNumber); + while (lastApprover && !lastStep) { - - while (lastApprover && !lastStep) - { - - currentStep++; - //Changed this next line of code to not pass the currently approving user. This prevents a user from approving multiple steps at once. An undesired function. - lastApprover = wfDMO.Approve(ecnNumber, currentStep, comments, out lastStep, 11111111, documentType, ecn.WorkFlowNumber); - NotifyApprovers(ecnNumber, currentStep, documentType, ecnTypeString); - - } - - - //#if(!DEBUG) - // only execute at the last step of the Approval loop - if (lastApprover && lastStep) - { - NotifySubmitter(ecn.ECNNumber, ecnTypeString); - NotifyAdmin(ecn.ECNNumber, ecnTypeString); - if (ecn.TrainingRequired) - { - TrainingController NewTraining = new TrainingController(); - NewTraining.Create(ecnNumber); - } - - if (ecn.IsECN && ecn.ConvertedFromNumber != null) - { - // Set the cancellation date for the TECN - ecnDMO.CancelECN(ecn.ConvertedFromNumber); - - //copy the TECN to the new ECN folder - GenerateECNPdfDifferentLocation((int)ecn.ConvertedFromNumber, ecnNumber); - - - - } - // Combine the TECN and the ECN in a zipped file for DCC task creation - PostApproval(ecnNumber, documentType); - - - if (ecn.IsECN && ecn.ConvertedFromNumber != null) - { - ApprovalLogDMO.Add(new ApprovalLog - { - IssueID = (int)ecn.ConvertedFromNumber, - DocumentTypeID = documentType, - OperationType = "Change to " + ecnTypeString + ecnNumber.ToString() + " Approved", - UserID = (int)Session[GlobalVars.SESSION_USERID], - OperationLog = "Approval of the Document conversion" - }); - - List attachments = new List(); - attachments.Add(Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber + "\\ECNForm_" + ecnNumber + ".pdf"); - attachments.Add(Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber + "\\ECNForm_" + ecn.ConvertedFromNumber + ".pdf"); - - NotifyTECNAutoCancellation(ecnNumber, (int)ecn.ConvertedFromNumber, attachments); - } - - } -//#endif + currentStep++; + //Changed this next line of code to not pass the currently approving user. This prevents a user from approving multiple steps at once. An undesired function. + lastApprover = wfDMO.Approve(_AppSettings, ecnNumber, currentStep, comments, out lastStep, 11111111, documentType, ecn.WorkFlowNumber); + NotifyApprovers(ecnNumber, currentStep, documentType, ecnTypeString); } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw new Exception(e.Message); - } + //#if(!DEBUG) + // only execute at the last step of the Approval loop + if (lastApprover && lastStep) { + NotifySubmitter(ecn.ECNNumber, ecnTypeString); + NotifyAdmin(ecn.ECNNumber, ecnTypeString); + if (ecn.TrainingRequired) { + TrainingController NewTraining = new TrainingController(); + NewTraining.Create(ecnNumber); + } + + if (ecn.IsECN && ecn.ConvertedFromNumber != null) { + // Set the cancellation date for the TECN + ecnDMO.CancelECN(ecn.ConvertedFromNumber); + + //copy the TECN to the new ECN folder + GenerateECNPdfDifferentLocation((int)ecn.ConvertedFromNumber, ecnNumber); + + } + // Combine the TECN and the ECN in a zipped file for DCC task creation + PostApproval(ecnNumber, documentType); + + if (ecn.IsECN && ecn.ConvertedFromNumber != null) { + ApprovalLogDMO.Add(new ApprovalLog { + IssueID = (int)ecn.ConvertedFromNumber, + DocumentTypeID = documentType, + OperationType = "Change to " + ecnTypeString + ecnNumber.ToString() + " Approved", + UserID = (int)Session[GlobalVars.SESSION_USERID], + OperationLog = "Approval of the Document conversion" + }); + + List attachments = new List(); + attachments.Add(_AppSettings.AttachmentFolder + "ECN\\" + ecnNumber + "\\ECNForm_" + ecnNumber + ".pdf"); + attachments.Add(_AppSettings.AttachmentFolder + "ECN\\" + ecnNumber + "\\ECNForm_" + ecn.ConvertedFromNumber + ".pdf"); + + NotifyTECNAutoCancellation(ecnNumber, (int)ecn.ConvertedFromNumber, attachments); + } + + } + //#endif + + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw new Exception(e.Message); } + } + void PostApproval(int ecnNumber, int documentType) { + try { + ECNPdf ecn = new ECNPdf(); - /// - /// - /// - /// - void PostApproval(int ecnNumber, int documentType) - { - try - { - ECNPdf ecn = new ECNPdf(); + // Generate the PDF version of the ECN form and Approval log + if (GenerateECNPdf(ecnNumber, out ecn)) { + // Zip up all the attached files along with the Pdf version of the ECN form and the Approval Log + if (CreateZip(ecn)) { + //Documentum.Process(_AppSettings.AttachmentFolder + "\\ECNZipped\\" + ecnNumber.ToString() + ".zip"); - // Generate the PDF version of the ECN form and Approval log - if (GenerateECNPdf(ecnNumber, out ecn)) - { - // Zip up all the attached files along with the Pdf version of the ECN form and the Approval Log - if (CreateZip(ecn)) - { - //Documentum.Process(Functions.GetAttachmentFolder() + "\\ECNZipped\\" + ecnNumber.ToString() + ".zip"); - - } - else - { - // TODO How to recreate and send the files to documentum - throw new Exception("Problems while generating the ZIP file. Please contact the system Administrator"); - } - } - else - { - throw new Exception("Problems while generating the PDF file. Please contact the system Administrator"); - } - - // Notify a list of people when the E-TECN is approved - if (documentType == (int)GlobalVars.DocumentType.EECN) - { - NotifyEmergencyTECNApproval(ecnNumber, ecn.ExpirationDate); + } else { + // TODO How to recreate and send the files to documentum + throw new Exception("Problems while generating the ZIP file. Please contact the system Administrator"); } + } else { + throw new Exception("Problems while generating the PDF file. Please contact the system Administrator"); } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ECN - PostApproval \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "PostApprovalForECNsDerivedFromTECN - " + exceptionString }); - throw e; + + // Notify a list of people when the E-TECN is approved + if (documentType == (int)GlobalVars.DocumentType.EECN) { + NotifyEmergencyTECNApproval(ecnNumber, ecn.ExpirationDate); } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ECN - PostApproval \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "PostApprovalForECNsDerivedFromTECN - " + exceptionString }); + throw e; } + } - /// - /// - /// - /// - /// - //void PostApprovalForECNsDerivedFromTECN(int ecnNumber, int tecnNumber) - //{ + //void PostApprovalForECNsDerivedFromTECN(int ecnNumber, int tecnNumber) + //{ + // try + // { + // // Generate the PDF version of the ECN form and Approval log + // string sourceFile = _AppSettings.AttachmentFolder + "ECN\\" + tecnNumber + "\\ECNForm_" + tecnNumber + ".pdf"; + // string destFile = _AppSettings.AttachmentFolder + "ECN\\" + ecnNumber + "\\ECNForm_" + tecnNumber + ".pdf"; - // try - // { - // // Generate the PDF version of the ECN form and Approval log - // string sourceFile = Functions.GetAttachmentFolder() + "ECN\\" + tecnNumber + "\\ECNForm_" + tecnNumber + ".pdf"; - // string destFile = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber + "\\ECNForm_" + tecnNumber + ".pdf"; + // GenerateECNPdfDifferentLocation(ecnNumber, tecnNumber); + // } - // GenerateECNPdfDifferentLocation(ecnNumber, tecnNumber); + // catch(Exception e) + // { + // string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + // Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ECN - PostApprovalForECNsDerivedFromTECN \r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + // EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "PostApprovalForECNsDerivedFromTECN - " + exceptionString }); + // throw e; + // } + //} + public void NotifySubmitter(int ecnNumber, string ecnTypeString) { + try { + string emailSentList = ""; + ECN ecn = ecnDMO.GetECN(ecnNumber); + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + //List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); + int ecnCreatedById = ecn.OriginatorID; + string ecnCreatedByEmail = MiscDMO.GetEmail(ecnCreatedById); + string emailTemplate = "ECNApproved.txt"; + string userEmail = string.Empty; + string subject = string.Empty; + string senderName = ecnTypeString; - // } + subject = ecnTypeString + " Approval notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; - // catch(Exception e) - // { - // string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - // Functions.WriteEvent(@User.Identity.Name + "\r\n ECN - PostApprovalForECNsDerivedFromTECN \r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - // EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "PostApprovalForECNsDerivedFromTECN - " + exceptionString }); - // throw e; - // } + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = ecnNumber.ToString(); + emailparams[1] = ecnNumber.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = ecnTypeString; + userEmail = ecnCreatedByEmail; + //#if(DEBUG) + //string SenderEmail = "MesaFabApproval@infineon.com"; + //userEmail = "jonathan.ouellette@infineon.com"; + //#endif + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams); + emailSentList = ecnCreatedByEmail; + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + ":" + emailSentList }); + } catch { } - //} - /// - /// - /// - /// - /// - public void NotifySubmitter(int ecnNumber, string ecnTypeString) - { - - try - { - string emailSentList = ""; - ECN ecn = ecnDMO.GetECN(ecnNumber); - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - //List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); - int ecnCreatedById = ecn.OriginatorID; - string ecnCreatedByEmail = MiscDMO.GetEmail(ecnCreatedById); + //EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + //string[] emailparams = new string[4]; + //emailparams[0] = issueID.ToString(); + //emailparams[1] = issueID.ToString(); + //emailparams[2] = GlobalVars.hostURL; + //emailparams[3] =Session[GlobalVars.SESSION_USERNAME].ToString(); + //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw e; + } + } + public void NotifyAdmin(int ecnNumber, string ecnTypeString) { + try { + string emailSentList = ""; + ECN ecn = ecnDMO.GetECN(ecnNumber); + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + //List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); + IEnumerable ecnAdminIDs = MiscDMO.GetUserIDsBySubRoleID(383); + foreach (int id in ecnAdminIDs) { + string ecnCreatedByEmail = MiscDMO.GetEmail(id); string emailTemplate = "ECNApproved.txt"; string userEmail = string.Empty; @@ -1064,30 +791,27 @@ namespace Fab2ApprovalSystem.Controllers subject = ecnTypeString + " Approval notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = ecnNumber.ToString(); - emailparams[1] = ecnNumber.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = ecnTypeString; - userEmail = ecnCreatedByEmail; - //#if(DEBUG) - //string SenderEmail = "MesaFabApproval@infineon.com"; - //userEmail = "jonathan.ouellette@infineon.com"; - //#endif + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = ecnNumber.ToString(); + emailparams[1] = ecnNumber.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = ecnTypeString; + userEmail = ecnCreatedByEmail; + //#if(DEBUG) + //string SenderEmail = "MesaFabApproval@infineon.com"; + //userEmail = "jonathan.ouellette@infineon.com"; + //#endif - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams); - emailSentList = ecnCreatedByEmail; + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams); + emailSentList = ecnCreatedByEmail; - try - { + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + ":" + emailSentList }); + } catch { } - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + ":" + emailSentList }); - } - catch { } - - //EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + //EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); //string[] emailparams = new string[4]; //emailparams[0] = issueID.ToString(); //emailparams[1] = issueID.ToString(); @@ -1095,1885 +819,1238 @@ namespace Fab2ApprovalSystem.Controllers //emailparams[3] =Session[GlobalVars.SESSION_USERNAME].ToString(); //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw e; + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - - + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw e; } - public void NotifyAdmin(int ecnNumber, string ecnTypeString) - { + } - try - { - string emailSentList = ""; - ECN ecn = ecnDMO.GetECN(ecnNumber); - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - //List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); - IEnumerable ecnAdminIDs = MiscDMO.GetUserIDsBySubRoleID(383); - foreach (int id in ecnAdminIDs) - { - string ecnCreatedByEmail = MiscDMO.GetEmail(id); - - string emailTemplate = "ECNApproved.txt"; - string userEmail = string.Empty; - string subject = string.Empty; - string senderName = ecnTypeString; - - subject = ecnTypeString + " Approval notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; - - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = ecnNumber.ToString(); - emailparams[1] = ecnNumber.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = ecnTypeString; - userEmail = ecnCreatedByEmail; - //#if(DEBUG) - //string SenderEmail = "MesaFabApproval@infineon.com"; - //userEmail = "jonathan.ouellette@infineon.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams); - emailSentList = ecnCreatedByEmail; - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + ":" + emailSentList }); - } - catch { } - - //EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - //string[] emailparams = new string[4]; - //emailparams[0] = issueID.ToString(); - //emailparams[1] = issueID.ToString(); - //emailparams[2] = GlobalVars.hostURL; - //emailparams[3] =Session[GlobalVars.SESSION_USERNAME].ToString(); - //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); - } - - - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw e; - - } - - - } - /// - /// - /// - /// - /// - public void NotifyApprovers(int ecnNumber, byte currentStep, int documentType, string ecnTypeString) - { - - try - { - string emailSentList = ""; - ECN ecn = ecnDMO.GetECN(ecnNumber); - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); - - string emailTemplate = "ECNAssigned.txt"; - string userEmail = string.Empty; - string subject = string.Empty; - string senderName = ecnTypeString; - - subject = ecnTypeString + " Assignment notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; - foreach (string email in emailIst) - { - - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = ecnNumber.ToString(); - emailparams[1] = ecnNumber.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = ecnTypeString; - userEmail = email; - //#if(DEBUG) - //string SenderEmail = "MesaFabApproval@infineon.com"; - //userEmail = "jonathan.ouellette@infineon.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams); - emailSentList += email + ","; - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); - } - catch { } - - //EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - //string[] emailparams = new string[4]; - //emailparams[0] = issueID.ToString(); - //emailparams[1] = issueID.ToString(); - //emailparams[2] = GlobalVars.hostURL; - //emailparams[3] =Session[GlobalVars.SESSION_USERNAME].ToString(); - //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); - } - catch ( Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw e; - - } - - - } - - /// - /// - /// - /// - //public void NotifyRejectionToOrginator(int ecnNumber, int documentType) - //{ - - // List emailIst = ecnDMO.GetRejectionOrginatorEmailList(@ecnNumber).Distinct().ToList(); - - // string emailTemplate = "ECNReject.txt"; - // string userEmail = string.Empty; - // string subject = "ECN Rejection"; - // string senderName = "ECN"; - - // foreach (string email in emailIst) - // { - // subject = "ECN Rejection"; - // EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - // string[] emailparams = new string[4]; - // emailparams[0] = ecnNumber.ToString(); - // emailparams[1] = ecnNumber.ToString(); - // emailparams[2] = GlobalVars.hostURL; - // emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString(); - // userEmail = email; - // //#if(DEBUG) - // // userEmail = GlobalVars.SENDER_EMAIL; - // //#endif - - // en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - // } - - // try - // { - - // EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Email", Comments = "Rejection: " + userEmail }); - // } - // catch { } - - //} - - - /// - /// Get a list of Approvers and the status - /// - /// - /// - /// - /// - public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step, bool isTECN, bool isEmergrncyTECN) - { - int isITARCompliant = 0; - ECN ecn = new ECN(); - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - GlobalVars.DocumentType docType; - // fix related to ticket #35336 - if (ecn.CancellationInProgress || ecn.CancellationApproved || ecn.ExpirationInProgress || ecn.ExpirationProcessed) - docType = GlobalVars.DocumentType.TECNCancelledExpired; - else - docType = isEmergrncyTECN ? GlobalVars.DocumentType.EECN : GlobalVars.DocumentType.ECN; - - return Json(MiscDMO.GetApproversListByDocument(issueID, step,(int) docType).ToDataSourceResult(request)); - } - - - - - - /// - /// - /// - /// - public void NotifyRejectionToOrginator(int issueID, string ecnTypeString, string comments) - { - - List emailIst = ecnDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList(); - ECN ecn = ecnDMO.GetECN(issueID); - - string emailTemplate = "ECNReject.txt"; - string userEmail = string.Empty; - string subject = ecnTypeString + " Rejection"; - string senderName = ecnTypeString; - - foreach (string email in emailIst) - { - subject = ecnTypeString + " Rejection notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[6]; - emailparams[0] = issueID.ToString(); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString(); - emailparams[4] = ecnTypeString; - emailparams[5] = comments; - userEmail = email; - //#if(DEBUG) - // userEmail = GlobalVars.SENDER_EMAIL; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail }); - } - catch { } - - } - - /// - /// - /// - /// - /// - public void NotifyTECNExtensionRejectionToOrginator(int issueID, string ecnTypeString) - { - - List emailIst = ecnDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList(); - ECN ecn = ecnDMO.GetECN(issueID); - - string emailTemplate = "TECNExtensionReject.txt"; - string userEmail = string.Empty; - string subject = ecnTypeString + " Rejection"; - string senderName = ecnTypeString; - - foreach (string email in emailIst) - { - subject = ecnTypeString + " Extension Rejection notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = issueID.ToString(); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString(); - emailparams[4] = ecnTypeString; - userEmail = email; - //#if(DEBUG) - // userEmail = GlobalVars.SENDER_EMAIL; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail }); - } - catch { } - - } - - /// - /// - /// - /// - /// - /// - public void Reject(int ecnNumber, byte currentStep, string comments, int docType, string ecnTypeString) - { - try - { - // TODO - // Check Rejection is for the TECN Extension - - int isITARCompliant = 0; - ECN ecn = new ECN(); - ecn = ecnDMO.GetECNForRead(ecnNumber, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - - if (Session[GlobalVars.SESSION_USERID] != null) - { - if (ecn.TECNExtensionState) - { - wfDMO.RejectTECNExtension(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); - NotifyTECNExtensionRejectionToOrginator(ecnNumber, ecnTypeString); - } - else - { - - if (ecn.IsECN && ecn.ConvertedFromNumber != null) - { - - ecnDMO.ECNResetTECNAtRejection(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], docType); - } - - wfDMO.Reject(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); - NotifyRejectionToOrginator(ecnNumber, ecnTypeString, comments); - } - } - else - { - - Response.Redirect("~/Account/Login"); - } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Reject\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Reject - " + exceptionString }); - throw new Exception(e.Message); - - } - - } - public void RecallDocument(int ecnNumber, byte currentStep, string comments, int docType, string ecnTypeString) - { - try - { - // TODO - // Check Rejection is for the TECN Extension - - int isITARCompliant = 0; - ECN ecn = new ECN(); - ecn = ecnDMO.GetECNForRead(ecnNumber, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - - if (Session[GlobalVars.SESSION_USERID] != null) - { - NotifyApproversForRecall(ecnNumber, currentStep, docType, ecnTypeString, comments); - wfDMO.Recall(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); - - //NotifyRejectionToOrginator(ecnNumber, ecnTypeString, comments); - } - else - { - - Response.Redirect("~/Account/Login"); - } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Reject\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Reject - " + exceptionString }); - throw new Exception(e.Message); - - } - } - - - - /// - /// - /// - /// - /// - /// - /// - public void ReAssignApproverByAdmin(int issueID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType, string ecnTypeString) - { - var email = ""; - try - { - - email = wfDMO.ReAssignApproval(issueID, reAssignApproverFrom, reAssignApproverTo, step, docType); - - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); - throw new Exception(e.Message); - - } - - ECN ecn = ecnDMO.GetECN(issueID); - string emailTemplate = "ECNReAssigned.txt"; - string userEmail = string.Empty; - string subject; - string senderName = ecnTypeString; - - subject = ecnTypeString + " Re-Assignment" + " - ECN #" + ecn.ECNNumber + ", - " + ecn.Title;; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = issueID.ToString(); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = ecnTypeString; - - userEmail = email; - //#if(DEBUG) - // userEmail = "rkotian1@infineon.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "ReAssign Approver: " + email }); - } - catch { } - - } - - [HttpPost] - public void ReAssignOriginatorByAdmin(int ecnNumber, string comments, int newOriginatorId) - { - if (Session[GlobalVars.IS_ADMIN] == null) - throw new Exception("Permission denied"); - - try - { - ecnDMO.ReassignOriginatorECN(ecnNumber, newOriginatorId, comments, (int)Session[GlobalVars.SESSION_USERID]); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim(); - if (exceptionString.Length > 450) exceptionString = exceptionString.Substring(0, 450); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignOriginatorByAdmin\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "ReAssignOriginatorByAdmin - " + exceptionString }); - throw new Exception(e.Message); - } - } - - /// - /// - /// - /// - /// - /// - /// - public void ReAssignApproval(int issueID, int userIDs, byte step, int docType, string ecnTypeString) - { - var email = ""; - try - { - email = wfDMO.ReAssignApproval(issueID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, docType); - - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); - throw new Exception(e.Message); - - } - - ECN ecn = ecnDMO.GetECN(issueID); - string emailTemplate = "ECNReAssigned.txt"; - string userEmail = string.Empty; - string subject = ecnTypeString + " Re-Assignment"; - string senderName = ecnTypeString; - - subject = ecnTypeString + " Re-Assignment" + " - Email would be sent to " + email + " for Number " + ecn.ECNNumber + ", - " + ecn.Title;; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = issueID.ToString(); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = ecnTypeString; - userEmail = email; - //#if(DEBUG) - // userEmail = GlobalVars.SENDER_EMAIL; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "ReAssign Approver: " + email }); - } - catch { } - - } - - - #region - #endregion - - /// - /// - /// - /// - //public JsonResult GetUserListForAdditionalAppprrovers() - //{ - // UserAccountDMO userDMO = new UserAccountDMO(); - // IEnumerable userlist = userDMO.GetAllUsers(); - // return Json(userlist, JsonRequestBehavior.AllowGet); - - //} - - /// - /// - /// - /// - /// - /// - public JsonResult GetAllUsersList() - { - //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep); - //return Json(userList, JsonRequestBehavior.AllowGet); - - UserAccountDMO userDMO = new UserAccountDMO(); - IEnumerable userlist = userDMO.GetAllActiveUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); - - } - - /// - /// - /// - /// - /// - /// - /// - public void AddAdditionalApproval(int issueID, byte step, string userIDs, int docType, string ecnTypeString) - { + public void NotifyApprovers(int ecnNumber, byte currentStep, int documentType, string ecnTypeString) { + try { string emailSentList = ""; - var emailArray = ""; - try - { - emailArray = wfDMO.AddAdditionalApproval(issueID, userIDs, step, docType); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw new Exception(e.Message); - } - ECN ecn = ecnDMO.GetECN(issueID); - - string emailTemplate = "ECNAssigned.txt"; - string userEmail = string.Empty; - string subject = ecnTypeString + " Assignment"; - string senderName = ecnTypeString; - - - string[] emailIst = emailArray.Split(new char[] { '~' }); - foreach (string email in emailIst) - { - if (email.Length > 0) - { - //subject = "Lot Disposition Assignment" + " - Email would be sent to " + email; - subject = ecnTypeString + "Assignment notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = issueID.ToString(); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = ecnTypeString; - - userEmail = email; - //#if(DEBUG) - // userEmail = "rkotian1@infineon.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - emailSentList += email + ","; - - } - - } - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); - } - catch { } - } - - - /// - /// - /// - /// - public bool GenerateECNPdf(int ecnNumber, out ECNPdf ecn) - { - //DateTime? expDt; - try - { - - string outputFileName = ""; - - ecn = ecnDMO.GetECNPdf(ecnNumber); - //expDate = ecn.ExpirationDate; - //extensionDate = ecn.ExtensionDate; - - outputFileName = ecnNumber.ToString() + ".pdf"; - - - string ecnFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString(); - //string ecnFolderPath = @"C:\Users\Ouellette\Desktop"; - DirectoryInfo di = new DirectoryInfo(ecnFolderPath); - // create the folder for the ECN if it does not exist - if (!di.Exists) - di.Create(); - - // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This - // requires the controller to be inherited from MyController instead of MVC's Controller. - SavePdf(ecnFolderPath + "\\ECNForm_" + outputFileName, "ECNPdf", ecn); - SavePdf(ecnFolderPath + "\\ECNApprovalLog_" + outputFileName, "ECNApprovalPdf", ecn); - } - catch (Exception ex) - { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Generate PDF", Comments = ex.Message }); - ecn = null; - return false; - - } - - return true; - } - - - /// - /// - /// - /// - /// - /// - /// - public bool GenerateECNPdfDifferentLocation(int ecnNumber, int folderName) - { - ECNPdf ecn = new ECNPdf(); - try - { - - string outputFileName = ""; - - ecn = ecnDMO.GetECNPdf(ecnNumber); - //expDate = ecn.ExpirationDate; - //extensionDate = ecn.ExtensionDate; - - outputFileName = ecnNumber.ToString() + ".pdf"; - - - string ecnFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + folderName.ToString(); - - DirectoryInfo di = new DirectoryInfo(ecnFolderPath); - // create the folder for the ECN if it does not exist - if (!di.Exists) - di.Create(); - - // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This - // requires the controller to be inherited from MyController instead of MVC's Controller. - SavePdf(ecnFolderPath + "\\ECNForm_" + outputFileName, "ECNPdf", ecn); - } - catch (Exception ex) - { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Generate PDF", Comments = ex.Message }); - ecn = null; - return false; - - } - - return true; - } - - - /// - /// - /// - /// - /// - /// - public ActionResult PrintECNPdf(int ecnNumber) - { - ECNPdf ecn; - try - { - - //string outputFileName = ""; - - ecn = ecnDMO.GetECNPdf(ecnNumber); - // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This - // requires the controller to be inherited from MyController instead of MVC's Controller. - return this.ViewPdf("", "ECNPdf", ecn); - - } - catch (Exception ex) - { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Print PDF", Comments = ex.Message }); - ecn = null; - return Content(""); - - } - - //return true; - } - - - - /// - /// - /// - /// - public void NotifyEmergencyTECNApproval(int ecnNumber, DateTime? expDate) - { - string ecnFolderPath = Functions.GetAttachmentFolder() + "E-TECNZipped\\" + ETECN_PREFIX + ecnNumber.ToString() + ".zip"; - - string emailSentList = ""; - - List emailIst = MiscDMO.GetEmergencyTECNApprovalNotifyList(ecnNumber).Distinct().ToList(); - - string emailTemplate = "ETECNApproved.txt"; - string userEmail = string.Empty; - string subject = "E-TECN Approved"; - string senderName = "E-TECN"; - ECN ecn = ecnDMO.GetECN(ecnNumber); - subject = "E-TECN Approved notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = ecnNumber.ToString(); - emailparams[1] = ecnNumber.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = "E-TECN"; - emailparams[4] = expDate.ToString(); - -//#if(DEBUG) -// userEmail = "rkotian1@infineon.com"; -//#endif - - if (IsITAR(ecn)) - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); - else - en.SendNotificationEmailWithAttachment(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, ecnFolderPath, emailparams); - - //emailSentList += email + ","; - emailSentList = String.Join(", ", emailIst.Distinct().ToArray()) ; - - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Step 1:" + emailSentList }); - } - catch { } - - } - - /// - /// - /// - /// - /// - /// - /// - public void NotifyApproversForCancellation(int ecnNumber, byte currentStep, int documentType, string ecnTypeString) - { - ECN ecn = ecnDMO.GetECN(ecnNumber); - string emailSentList = ""; - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); - string emailTemplate = "TECNCancellationApproval.txt"; + string emailTemplate = "ECNAssigned.txt"; string userEmail = string.Empty; - string subject = ecnTypeString + " Cancellation Approval Required - " + ecnNumber + " for " + ecn.Title + ", Cancellation initiated on :" + ecn.CancellationDate; + string subject = string.Empty; string senderName = ecnTypeString; - foreach (string email in emailIst) - { - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + subject = ecnTypeString + " Assignment notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; + foreach (string email in emailIst) { + + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); string[] emailparams = new string[4]; emailparams[0] = ecnNumber.ToString(); emailparams[1] = ecnNumber.ToString(); emailparams[2] = GlobalVars.hostURL; emailparams[3] = ecnTypeString; userEmail = email; -//#if(DEBUG) -// userEmail = "rkotian1@infineon.com"; -//#endif + //#if(DEBUG) + //string SenderEmail = "MesaFabApproval@infineon.com"; + //userEmail = "jonathan.ouellette@infineon.com"; + //#endif - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams); emailSentList += email + ","; } - try - { - + try { EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + } catch { } + + //EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + //string[] emailparams = new string[4]; + //emailparams[0] = issueID.ToString(); + //emailparams[1] = issueID.ToString(); + //emailparams[2] = GlobalVars.hostURL; + //emailparams[3] =Session[GlobalVars.SESSION_USERNAME].ToString(); + //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - catch { } - - - + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw e; } - /// - /// - /// - /// - /// - /// - /// - public void NotifyApproversForRecall(int ecnNumber, byte currentStep, int documentType, string ecnTypeString, string recallComments) - { - ECN ecn = ecnDMO.GetECN(ecnNumber); - string emailSentList = ""; + } - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); - emailIst.Add("Jeanne.McIntyre@infineon.com"); - emailIst.Add("Jonathan.Ouellette@infineon.com"); - string emailTemplate = "ECNRecallApproval.txt"; - string userEmail = string.Empty; - string subject = ecnTypeString + " Recalled - " + ecnNumber + " for " + ecn.Title + ", Recall initiated on :" + DateTime.Now.ToString(); - string senderName = ecnTypeString; + /// + /// Get a list of Approvers and the status + /// + public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step, bool isTECN, bool isEmergrncyTECN) { + int isITARCompliant = 0; + ECN ecn = new ECN(); + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - foreach (string email in emailIst) - { - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = ecnNumber.ToString(); - emailparams[1] = ecnNumber.ToString(); + GlobalVars.DocumentType docType; + // fix related to ticket #35336 + if (ecn.CancellationInProgress || ecn.CancellationApproved || ecn.ExpirationInProgress || ecn.ExpirationProcessed) + docType = GlobalVars.DocumentType.TECNCancelledExpired; + else + docType = isEmergrncyTECN ? GlobalVars.DocumentType.EECN : GlobalVars.DocumentType.ECN; + + return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)docType).ToDataSourceResult(request)); + } + + public void NotifyRejectionToOrginator(int issueID, string ecnTypeString, string comments) { + List emailIst = ecnDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList(); + ECN ecn = ecnDMO.GetECN(issueID); + + string emailTemplate = "ECNReject.txt"; + string userEmail = string.Empty; + string subject = ecnTypeString + " Rejection"; + string senderName = ecnTypeString; + + foreach (string email in emailIst) { + subject = ecnTypeString + " Rejection notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[6]; + emailparams[0] = issueID.ToString(); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString(); + emailparams[4] = ecnTypeString; + emailparams[5] = comments; + userEmail = email; + //#if(DEBUG) + // userEmail = GlobalVars.SENDER_EMAIL; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + } + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail }); + } catch { } + } + + public void NotifyTECNExtensionRejectionToOrginator(int issueID, string ecnTypeString) { + List emailIst = ecnDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList(); + ECN ecn = ecnDMO.GetECN(issueID); + + string emailTemplate = "TECNExtensionReject.txt"; + string userEmail = string.Empty; + string subject = ecnTypeString + " Rejection"; + string senderName = ecnTypeString; + + foreach (string email in emailIst) { + subject = ecnTypeString + " Extension Rejection notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; + emailparams[0] = issueID.ToString(); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString(); + emailparams[4] = ecnTypeString; + userEmail = email; + //#if(DEBUG) + // userEmail = GlobalVars.SENDER_EMAIL; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + } + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail }); + } catch { } + } + + public void Reject(int ecnNumber, byte currentStep, string comments, int docType, string ecnTypeString) { + try { + // TODO + // Check Rejection is for the TECN Extension + + int isITARCompliant = 0; + ECN ecn = new ECN(); + ecn = ecnDMO.GetECNForRead(ecnNumber, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + if (Session[GlobalVars.SESSION_USERID] != null) { + if (ecn.TECNExtensionState) { + wfDMO.RejectTECNExtension(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); + NotifyTECNExtensionRejectionToOrginator(ecnNumber, ecnTypeString); + } else { + if (ecn.IsECN && ecn.ConvertedFromNumber != null) { + ecnDMO.ECNResetTECNAtRejection(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], docType); + } + + wfDMO.Reject(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); + NotifyRejectionToOrginator(ecnNumber, ecnTypeString, comments); + } + } else { + Response.Redirect("~/Account/Login"); + } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Reject\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Reject - " + exceptionString }); + throw new Exception(e.Message); + } + } + public void RecallDocument(int ecnNumber, byte currentStep, string comments, int docType, string ecnTypeString) { + try { + // TODO + // Check Rejection is for the TECN Extension + + int isITARCompliant = 0; + ECN ecn = new ECN(); + ecn = ecnDMO.GetECNForRead(ecnNumber, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + if (Session[GlobalVars.SESSION_USERID] != null) { + NotifyApproversForRecall(ecnNumber, currentStep, docType, ecnTypeString, comments); + wfDMO.Recall(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); + + //NotifyRejectionToOrginator(ecnNumber, ecnTypeString, comments); + } else { + Response.Redirect("~/Account/Login"); + } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Reject\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Reject - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public void ReAssignApproverByAdmin(int issueID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType, string ecnTypeString) { + var email = ""; + try { + + email = wfDMO.ReAssignApproval(issueID, reAssignApproverFrom, reAssignApproverTo, step, docType); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + throw new Exception(e.Message); + } + + ECN ecn = ecnDMO.GetECN(issueID); + string emailTemplate = "ECNReAssigned.txt"; + string userEmail = string.Empty; + string subject; + string senderName = ecnTypeString; + + subject = ecnTypeString + " Re-Assignment" + " - ECN #" + ecn.ECNNumber + ", - " + ecn.Title; + ; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = issueID.ToString(); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = ecnTypeString; + + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@infineon.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "ReAssign Approver: " + email }); + } catch { } + } + + [HttpPost] + public void ReAssignOriginatorByAdmin(int ecnNumber, string comments, int newOriginatorId) { + if (Session[GlobalVars.IS_ADMIN] == null) + throw new Exception("Permission denied"); + + try { + ecnDMO.ReassignOriginatorECN(ecnNumber, newOriginatorId, comments, (int)Session[GlobalVars.SESSION_USERID]); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim(); + if (exceptionString.Length > 450) + exceptionString = exceptionString.Substring(0, 450); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignOriginatorByAdmin\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "ReAssignOriginatorByAdmin - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public void ReAssignApproval(int issueID, int userIDs, byte step, int docType, string ecnTypeString) { + var email = ""; + try { + email = wfDMO.ReAssignApproval(issueID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, docType); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + throw new Exception(e.Message); + } + + ECN ecn = ecnDMO.GetECN(issueID); + string emailTemplate = "ECNReAssigned.txt"; + string userEmail = string.Empty; + string subject = ecnTypeString + " Re-Assignment"; + string senderName = ecnTypeString; + + subject = ecnTypeString + " Re-Assignment" + " - Email would be sent to " + email + " for Number " + ecn.ECNNumber + ", - " + ecn.Title; + ; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = issueID.ToString(); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = ecnTypeString; + userEmail = email; + //#if(DEBUG) + // userEmail = GlobalVars.SENDER_EMAIL; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "ReAssign Approver: " + email }); + } catch { } + } + + #region + #endregion + + public JsonResult GetAllUsersList() { + //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep); + //return Json(userList, JsonRequestBehavior.AllowGet); + + UserAccountDMO userDMO = new UserAccountDMO(); + IEnumerable userlist = userDMO.GetAllActiveUsers(); + return Json(userlist, JsonRequestBehavior.AllowGet); + } + + public void AddAdditionalApproval(int issueID, byte step, string userIDs, int docType, string ecnTypeString) { + string emailSentList = ""; + var emailArray = ""; + try { + emailArray = wfDMO.AddAdditionalApproval(issueID, userIDs, step, docType); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw new Exception(e.Message); + } + ECN ecn = ecnDMO.GetECN(issueID); + + string emailTemplate = "ECNAssigned.txt"; + string userEmail = string.Empty; + string subject = ecnTypeString + " Assignment"; + string senderName = ecnTypeString; + + string[] emailIst = emailArray.Split(new char[] { '~' }); + foreach (string email in emailIst) { + if (email.Length > 0) { + //subject = "Lot Disposition Assignment" + " - Email would be sent to " + email; + subject = ecnTypeString + "Assignment notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = issueID.ToString(); + emailparams[1] = issueID.ToString(); emailparams[2] = GlobalVars.hostURL; emailparams[3] = ecnTypeString; - emailparams[4] = recallComments; + userEmail = email; //#if(DEBUG) - // userEmail = "rkotian1@infineon.com"; + // userEmail = "rkotian1@infineon.com"; //#endif en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); emailSentList += email + ","; + } - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); - } - catch { } - - - } - /// - /// - /// - /// - /// - /// - /// - public void NotifyApproversForExpiration(int ecnNumber, byte currentStep, int documentType, string ecnTypeString) - { - ECN ecn = ecnDMO.GetECN(ecnNumber); - string emailSentList = ""; + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); + } catch { } + } - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); + public bool GenerateECNPdf(int ecnNumber, out ECNPdf ecn) { + //DateTime? expDt; + try { - string emailTemplate = "TECNExpirationApproval.txt"; - string userEmail = string.Empty; - string subject = " TECN Expiration Approval Reqquired - " + ecnTypeString + "# " + ecnNumber + " for " + ecn.Title + ", Expired:" + ecn.ExpirationDate; - string senderName = ecnTypeString; + string outputFileName = ""; - foreach (string email in emailIst) - { - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = ecnNumber.ToString(); - emailparams[1] = ecnNumber.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = ecnTypeString; - userEmail = email; -#if(DEBUG) - userEmail = GlobalVars.SENDER_EMAIL; -#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - emailSentList += email + ","; - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); - } - catch { } + ecn = ecnDMO.GetECNPdf(ecnNumber); + //expDate = ecn.ExpirationDate; + //extensionDate = ecn.ExtensionDate; + outputFileName = ecnNumber.ToString() + ".pdf"; + string ecnFolderPath = _AppSettings.AttachmentFolder + "ECN\\" + ecnNumber.ToString(); + //string ecnFolderPath = @"C:\Users\Ouellette\Desktop"; + DirectoryInfo di = new DirectoryInfo(ecnFolderPath); + // create the folder for the ECN if it does not exist + if (!di.Exists) + di.Create(); + // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This + // requires the controller to be inherited from MyController instead of MVC's Controller. + SavePdf(ecnFolderPath + "\\ECNForm_" + outputFileName, "ECNPdf", ecn); + SavePdf(ecnFolderPath + "\\ECNApprovalLog_" + outputFileName, "ECNApprovalPdf", ecn); + } catch (Exception ex) { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Generate PDF", Comments = ex.Message }); + ecn = null; + return false; } - /// - /// - /// - /// - public void NotifyTECNCancellation(int ecnNumber, string ecnFolderPath) - { - //string ecnFolderPath = Functions.GetAttachmentFolder() + "TECNCancelledZipped\\" + TECN_PREFIX + ecnNumber.ToString() + ".zip"; - ECN ecn = ecnDMO.GetECN(ecnNumber); - string emailSentList = ""; + return true; + } - List emailIst = MiscDMO.GetTECNCancelledApprovalNotifyList(ecnNumber).Distinct().ToList(); - List notificationUserList = ecnDMO.GetTECNNotificationUsers().ToList(); - foreach (int userId in notificationUserList) - { - string email = userDMO.GetUserEmailByID(userId.ToString()); - if (email != null && !emailIst.Contains(email)) emailIst.Add(email); - } + public bool GenerateECNPdfDifferentLocation(int ecnNumber, int folderName) { + ECNPdf ecn = new ECNPdf(); + try { + string outputFileName = ""; - string emailTemplate = "TECNCancelled.txt"; - string userEmail = string.Empty; - string subject = string.Empty; - if (ecn.CancellationApprovalDate == null) - { - subject = "TECN Cancellation Initiated Notice - " + ecnNumber + " for " + ecn.Title + ", Cancellation Initiated on:" + DateTime.Now; - } - else - { - subject = "TECN Cancellation Approved Notice - " + ecnNumber + " for " + ecn.Title + ", Cancelled:" + ecn.CancellationApprovalDate; - } - string senderName = "ECN"; + ecn = ecnDMO.GetECNPdf(ecnNumber); + //expDate = ecn.ExpirationDate; + //extensionDate = ecn.ExtensionDate; - //foreach (string email in emailIst) - //{ - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = ecnNumber.ToString(); - emailparams[1] = ecnNumber.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = "TECN"; - emailparams[4] = DateTime.Now.ToString(); - //userEmail = email; + outputFileName = ecnNumber.ToString() + ".pdf"; -#if(DEBUG) - userEmail = GlobalVars.SENDER_EMAIL; -#endif + string ecnFolderPath = _AppSettings.AttachmentFolder + "ECN\\" + folderName.ToString(); - //en.SendNotificationEmailWithAttachment(emailTemplate, "rkotian1@irf.com", senderName, userEmail, null, subject, ecnFolderPath, emailparams); - if (IsITAR(ecn)) - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); - else - en.SendNotificationEmailWithAttachment(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, ecnFolderPath, emailparams); - //emailSentList += email + ","; - emailSentList = String.Join(", ", emailIst.Distinct().ToArray()); - - //} - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Cancellation :" + emailSentList }); - } - catch { } + DirectoryInfo di = new DirectoryInfo(ecnFolderPath); + // create the folder for the ECN if it does not exist + if (!di.Exists) + di.Create(); + // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This + // requires the controller to be inherited from MyController instead of MVC's Controller. + SavePdf(ecnFolderPath + "\\ECNForm_" + outputFileName, "ECNPdf", ecn); + } catch (Exception ex) { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Generate PDF", Comments = ex.Message }); + ecn = null; + return false; } - - /// - /// - /// - /// - /// - public void NotifyTECNAutoCancellation(int ecnNumber, int tecnNumber, List attachments) - { - //string ecnFolderPath = Functions.GetAttachmentFolder() + "TECNCancelledZipped\\" + TECN_PREFIX + ecnNumber.ToString() + ".zip"; - ECN ecn = ecnDMO.GetECN(tecnNumber); - string emailSentList = ""; + return true; + } - List emailIst = MiscDMO.GetTECNCancelledApprovalNotifyList(ecnNumber).Distinct().ToList(); + public ActionResult PrintECNPdf(int ecnNumber) { + ECNPdf ecn; + try { + //string outputFileName = ""; - string emailTemplate = "TECNAutoCancelled.txt"; - string userEmail = string.Empty; - string subject = string.Empty; - subject = "TECN Conversion and Cancellation Notice - " + tecnNumber + " for " + ecn.Title + ", Converted on:" + DateTime.Now; - string senderName = "ECN"; + ecn = ecnDMO.GetECNPdf(ecnNumber); + // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This + // requires the controller to be inherited from MyController instead of MVC's Controller. + return this.ViewPdf("", "ECNPdf", ecn); + } catch (Exception ex) { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Print PDF", Comments = ex.Message }); + ecn = null; + return Content(""); + } - //foreach (string email in emailIst) - //{ - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[6]; - emailparams[0] = tecnNumber.ToString(); - emailparams[1] = tecnNumber.ToString(); + //return true; + } + + public void NotifyEmergencyTECNApproval(int ecnNumber, DateTime? expDate) { + string ecnFolderPath = _AppSettings.AttachmentFolder + "E-TECNZipped\\" + ETECN_PREFIX + ecnNumber.ToString() + ".zip"; + + string emailSentList = ""; + + List emailIst = MiscDMO.GetEmergencyTECNApprovalNotifyList(ecnNumber).Distinct().ToList(); + + string emailTemplate = "ETECNApproved.txt"; + string userEmail = string.Empty; + string subject = "E-TECN Approved"; + string senderName = "E-TECN"; + + ECN ecn = ecnDMO.GetECN(ecnNumber); + subject = "E-TECN Approved notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; + emailparams[0] = ecnNumber.ToString(); + emailparams[1] = ecnNumber.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = "E-TECN"; + emailparams[4] = expDate.ToString(); + + //#if(DEBUG) + // userEmail = "rkotian1@infineon.com"; + //#endif + + if (IsITAR(ecn)) + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); + else + en.SendNotificationEmailWithAttachment(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, ecnFolderPath, emailparams); + + //emailSentList += email + ","; + emailSentList = String.Join(", ", emailIst.Distinct().ToArray()); + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Step 1:" + emailSentList }); + } catch { } + } + + public void NotifyApproversForCancellation(int ecnNumber, byte currentStep, int documentType, string ecnTypeString) { + ECN ecn = ecnDMO.GetECN(ecnNumber); + string emailSentList = ""; + + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); + + string emailTemplate = "TECNCancellationApproval.txt"; + string userEmail = string.Empty; + string subject = ecnTypeString + " Cancellation Approval Required - " + ecnNumber + " for " + ecn.Title + ", Cancellation initiated on :" + ecn.CancellationDate; + string senderName = ecnTypeString; + + foreach (string email in emailIst) { + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = ecnNumber.ToString(); + emailparams[1] = ecnNumber.ToString(); emailparams[2] = GlobalVars.hostURL; - emailparams[3] = "TECN"; - emailparams[4] = DateTime.Now.ToString(); - emailparams[5] = ecnNumber.ToString(); - //userEmail = email; - -#if(DEBUG) - userEmail = GlobalVars.SENDER_EMAIL; -#endif - - //en.SendNotificationEmailWithAttachment(emailTemplate, "rkotian1@irf.com", senderName, userEmail, null, subject, ecnFolderPath, emailparams); - if (IsITAR(ecn)) - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); - else - en.SendNotificationEmailWithAttachments(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, attachments, emailparams); - //emailSentList += email + ","; - emailSentList = String.Join(", ", emailIst.Distinct().ToArray()); - - //} - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Cancellation :" + emailSentList }); - } - catch { } - - } - - - /// - /// - /// - /// - public void NotifyTECNExpiration(int ecnNumber, string ecnFolderPath) - { - - ECN ecn = ecnDMO.GetECN(ecnNumber); - //string ecnFolderPath = Functions.GetAttachmentFolder() + "TECNExpiredZipped\\" + TECN_PREFIX + ecnNumber.ToString() + ".zip"; - - string emailSentList = ""; - - List emailIst = MiscDMO.GetEmergencyTECNApprovalNotifyList(ecnNumber).Distinct().ToList(); - - string emailTemplate = "TECNExpired.txt"; - string userEmail = string.Empty; - string subject = "TECN Expiration Approved Notice - " + ecnNumber + " for " + ecn.Title + ", Expired:" + ecn.ExpirationDate; - string senderName = "ECN"; - - //foreach (string email in emailIst) - //{ - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = ecnNumber.ToString(); - emailparams[1] = ecnNumber.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = "TECN"; - emailparams[4] = ecn.ExpirationDate.Value.ToShortDateString(); - //userEmail = email; - + emailparams[3] = ecnTypeString; + userEmail = email; //#if(DEBUG) // userEmail = "rkotian1@infineon.com"; //#endif - - //en.SendNotificationEmailWithAttachment(emailTemplate, "rkotian1@infineon.com", senderName, userEmail, null, subject, ecnFolderPath, emailparams); - if (IsITAR(ecn)) - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); - else - en.SendNotificationEmailWithAttachment(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, ecnFolderPath, emailparams); - - - - - //emailSentList += email + ","; - emailSentList = String.Join(", ", emailIst.Distinct().ToArray()); - - //} - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Email", Comments = "Approvers for Expiration:" + emailSentList }); - } - catch { } - + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + emailSentList += email + ","; } - /// - /// - /// - /// - bool CreateZip(ECNPdf ecn) - { - try - { - string sourceDirectory = Functions.GetAttachmentFolder() + "ECN\\" + ecn.ECNNumber.ToString() + "\\"; - string outputFullFilePath = ""; + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + } catch { } + } - string outputFileName; - if (ecn.IsTECN) - { - if (ecn.ExtensionDate != null) - outputFileName = TECN_PREFIX + ecn.ECNNumber.ToString() + "_Extension.zip"; - else - outputFileName = TECN_PREFIX + ecn.ECNNumber.ToString() + ".zip"; + public void NotifyApproversForRecall(int ecnNumber, byte currentStep, int documentType, string ecnTypeString, string recallComments) { + ECN ecn = ecnDMO.GetECN(ecnNumber); + string emailSentList = ""; - - outputFullFilePath = Functions.GetAttachmentFolder() + "\\ECNZipped\\" + outputFileName; - } - - else if (ecn.IsEmergencyTECN) // Transfer it to different folder , coz documentum does not need to have a Workflow Item created for Emergency TECN - { - outputFileName = ETECN_PREFIX + ecn.ECNNumber.ToString() + ".zip"; - outputFullFilePath = Functions.GetAttachmentFolder() + "\\E-TECNZipped\\" + outputFileName; - } - else - { - outputFileName = ECN_PREFIX + ecn.ECNNumber.ToString() + ".zip"; - outputFullFilePath = Functions.GetAttachmentFolder() + "\\ECNZipped\\" + outputFileName; - } + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); + emailIst.Add("Jeanne.McIntyre@infineon.com"); + emailIst.Add("Jonathan.Ouellette@infineon.com"); + string emailTemplate = "ECNRecallApproval.txt"; + string userEmail = string.Empty; + string subject = ecnTypeString + " Recalled - " + ecnNumber + " for " + ecn.Title + ", Recall initiated on :" + DateTime.Now.ToString(); + string senderName = ecnTypeString; - - Zipper zip = new Zipper(); - zip.CreateZip(outputFullFilePath, sourceDirectory); - } - catch(Exception ex) - { - EventLogDMO.Add(new WinEventLog() { IssueID = ecn.ECNNumber, UserID = @User.Identity.Name, DocumentType = ecn.IsECN? "ECN" : (ecn.IsEmergencyTECN? "E-TECN" : "TECN"), OperationType = "Error", Comments = ex.Message }); - return false; - } - - return true; + foreach (string email in emailIst) { + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; + emailparams[0] = ecnNumber.ToString(); + emailparams[1] = ecnNumber.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = ecnTypeString; + emailparams[4] = recallComments; + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@infineon.com"; + //#endif + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + emailSentList += email + ","; } + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + } catch { } + } - /// - /// - /// - /// - /// - /// - public void AddEECNApproval(int ecnNumber, byte step, string engUserIDs, string OpUserIDs) - { - // it is always going to be the first step - step = 1; - string emailSentList = ""; - var emailArray = ""; - try - { - emailArray = wfDMO.AddEECNApproval(ecnNumber, step, (int)GlobalVars.DocumentType.EECN, engUserIDs, OpUserIDs); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + step + " " + " Userid:" + engUserIDs + " - " + OpUserIDs + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AddEECNApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN ", OperationType = "Error", Comments = "AddEECNApproval - " + exceptionString }); - throw new Exception(e.Message); - } - ECN ecn = ecnDMO.GetECN(ecnNumber); - string emailTemplate = "ECNAssigned.txt"; - string userEmail = string.Empty; - string subject = "E-TECN Assignment"; - string senderName = "E-TECN"; + public void NotifyApproversForExpiration(int ecnNumber, byte currentStep, int documentType, string ecnTypeString) { + ECN ecn = ecnDMO.GetECN(ecnNumber); + string emailSentList = ""; - string[] emailIst = emailArray.Split(new char[] { '~' }); - foreach (string email in emailIst) - { - if (email.Length > 0) - { - subject = "E-TECN Assignment notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = ecnNumber.ToString(); - emailparams[1] = ecnNumber.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = "E-TECN"; + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); - userEmail = email; - //#if(DEBUG) - // userEmail = "rkotian1@infineon.com"; - //#endif + string emailTemplate = "TECNExpirationApproval.txt"; + string userEmail = string.Empty; + string subject = " TECN Expiration Approval Reqquired - " + ecnTypeString + "# " + ecnNumber + " for " + ecn.Title + ", Expired:" + ecn.ExpirationDate; + string senderName = ecnTypeString; - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - emailSentList += email + ","; + foreach (string email in emailIst) { + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = ecnNumber.ToString(); + emailparams[1] = ecnNumber.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = ecnTypeString; + userEmail = email; +#if (DEBUG) + userEmail = GlobalVars.SENDER_EMAIL; +#endif - } - - } - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); - } - catch { } + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + emailSentList += email + ","; } + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + } catch { } + } - /// - /// - /// - /// - /// - public void SaveAfterSubmitByApprover(int ecnNumber, string implementationDetails) - { - try - { - ecnDMO.SaveAfterSubmitByApprover(ecnNumber, implementationDetails); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SaveAfterSubmitByApprover\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN ", OperationType = "Error", Comments = "SaveAfterSubmitByApprover - " + exceptionString }); - throw new Exception(e.Message); - } + public void NotifyTECNCancellation(int ecnNumber, string ecnFolderPath) { + //string ecnFolderPath = _AppSettings.AttachmentFolder + "TECNCancelledZipped\\" + TECN_PREFIX + ecnNumber.ToString() + ".zip"; + ECN ecn = ecnDMO.GetECN(ecnNumber); + string emailSentList = ""; + List emailIst = MiscDMO.GetTECNCancelledApprovalNotifyList(ecnNumber).Distinct().ToList(); + List notificationUserList = ecnDMO.GetTECNNotificationUsers().ToList(); + foreach (int userId in notificationUserList) { + string email = userDMO.GetUserEmailByID(userId); + if (email != null && !emailIst.Contains(email)) + emailIst.Add(email); } - /// - /// - /// - /// - /// - public void DeleteDocument(int ecnNumber, string ecnTypeString) - { - try - { - ecnDMO.DeleteDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], ecnTypeString); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n DeleteDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "", OperationType = "Error", Comments = "DeleteDocument - " + exceptionString }); - throw new Exception(e.Message); - } + string emailTemplate = "TECNCancelled.txt"; + string userEmail = string.Empty; + string subject = string.Empty; + if (ecn.CancellationApprovalDate == null) { + subject = "TECN Cancellation Initiated Notice - " + ecnNumber + " for " + ecn.Title + ", Cancellation Initiated on:" + DateTime.Now; + } else { + subject = "TECN Cancellation Approved Notice - " + ecnNumber + " for " + ecn.Title + ", Cancelled:" + ecn.CancellationApprovalDate; } - public void DeleteDocumentBySubmitter(int ecnNumber, string ecnTypeString) - { - ECN ecn = ecnDMO.GetECN(ecnNumber); - int submitterId = ecn.OriginatorID; - if (submitterId == (int)Session[GlobalVars.SESSION_USERID]) - { - try - { - ecnDMO.DeleteDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], ecnTypeString); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n DeleteDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "", OperationType = "Error", Comments = "DeleteDocument - " + exceptionString }); - throw new Exception(e.Message); - } - } - else - { + string senderName = "ECN"; - } - } - /// - /// - /// - /// - /// - /// - /// - /// - public ActionResult ReSubmitDocument(int ecnNumber, int documentType, string ecnTypeString, string oldECNTypeString, string descriptionOfChange, string reasonForChange, string categoryId = "") - { - // Update ECN Type in the ECN table - - ECN ecn = new ECN(); - - int isITARCompliant = 1; - int newECNNumber = 0; - int catId = 0; - Int32.TryParse(categoryId, out catId); - try - { - - int appoverCount = ecnDMO.ReSubmitDocument( - ecnNumber, - (int)Session[GlobalVars.SESSION_USERID], - documentType, - out isITARCompliant, - descriptionOfChange, - reasonForChange, - ecnTypeString, - out newECNNumber, - catId); - - if (isITARCompliant == 0) // not ITAR Compliant - { - // the content gets evaluated on the client side - return Content("ITAR"); - } - else - { - //TODO - COPY ATTACHMENTS - Functions.CopyAttachments(ecnNumber, newECNNumber); - - // Log into the Approval Log - try - { - ecn = ecnDMO.GetECN(ecnNumber); - - //ecnDMO.UpdateECNType(ecnNumber, ecnTypeString); - - ApprovalLogDMO.Add(new ApprovalLog - { - IssueID = ecnNumber, - DocumentTypeID = documentType, - OperationType = "Changed From " + oldECNTypeString + " To " + ecnTypeString, - UserID = (int)Session[GlobalVars.SESSION_USERID], - OperationLog = "Changed the Document Type" - }); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReSubmitDocument (ApprovalLogDMO)\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReSubmitDocument (ApprovalLogDMO)" + exceptionString }); - - } - - // Add to the Document Change Log - try - { - ECNTypeChangeLogDMO.Add(new ECNTypeChangeLog - { - ECNNumber = ecnNumber, - UserID = (int)Session[GlobalVars.SESSION_USERID], - ECNTypeFrom = oldECNTypeString, - ECNTypeTo = ecnTypeString - }); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReSubmitDocument (ECNTypeChangeLogDMO)\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReSubmitDocument (ECNTypeChangeLogDMO)" + exceptionString }); - - } - - - - //if (appoverCount > 0) - //{ - // NotifyApprovers(newECNNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, documentType, ecnTypeString); - //} - //else - //{ - // // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval - // Approve(newECNNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, "", documentType, ecnTypeString); // this is the Submit Level Approval - - //} - - - - if (Request.IsAjaxRequest()) - { - // the content gets evaluated on the client side - return Content("Redirect~" + newECNNumber); - - } - else - return Content("Invalid"); - } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Re-SubmitDocument - " + exceptionString }); - throw new Exception(e.Message); - - } - - } - - /// - /// - /// - /// - /// - public ActionResult PCRBExists(int pcrb) - { - - return Content(ecnDMO.PCRBExists(pcrb).ToString()); - } - - /// - /// - /// - /// - public ActionResult CancelDocument(int ecnNumber, byte currentStep, int documentType, string ecnTypeString) - { - // log the cancelled event - //EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Cancelled", Comments = "Cancelled the document" }); - // Set the ECN Current step to the last step of the document type, which is the execution step - - bool lastApproverAndLastStep = false; - int appoverCount = ecnDMO.SubmitForCancellation(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, (int)Session[GlobalVars.SESSION_USERID], documentType, ecnTypeString, (int)GlobalVars.TECNExpirationCancellation.Cancellation); - if (appoverCount > 0) - { - NotifyApproversForCancellation(ecnNumber, currentStep, documentType, ecnTypeString); - } - else // TODO Automatically close the - { - lastApproverAndLastStep = ApproveCancellation(ecnNumber, currentStep, "", documentType, ecnTypeString); - // automaically approve current step (Step 1) because there are no approvers in step 1 and move to the next step of approval - //Approve(ecnNumber, currentStep, "", documentType, ecnTypeString); // this is the Submit Level Approval - - } - - // if there are approvers dont wait for it to finish the approval loop for sending cancel notications. - if (!lastApproverAndLastStep) - { - // send notifications - try - { - lastApproverAndLastStep = true; - - ECNPdf ecn = new ECNPdf(); - GenerateECNPdf(ecnNumber, out ecn); - - - string sourceDirectory = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString() + "\\"; - string outputFullFilePath = ""; - - string outputFileName; - outputFileName = TECN_PREFIX + ecnNumber.ToString() + ".zip"; - - outputFullFilePath = Functions.GetAttachmentFolder() + "\\TECNCancelledZipped\\" + outputFileName; - - // Create the zipped package - Zipper zip = new Zipper(); - zip.CreateZip(outputFullFilePath, sourceDirectory); - NotifyTECNCancellation(ecnNumber, outputFullFilePath); - - - } - catch (Exception ex) - { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); - - } - - } - int trainingId = trainingDMO.GetTrainingId(ecnNumber); - trainingDMO.DeleteTraining(trainingId); - - if (Request.IsAjaxRequest()) - { - // the content gets evaluated on the client side - return Content("Redirect"); - } - else - return Content("Invalid"); - - } - public ActionResult CancelDocumentBySubmitter(int ecnNumber, byte currentStep, int documentType, string ecnTypeString) - { - return Content("Redirect"); - } - /// - /// - /// - /// - /// - /// - /// - /// - public bool ApproveCancellation(int ecnNumber, byte currentStep, string comments, int documentType, string ecnTypeString) - { - bool lastApproverAndLastStep = false; - bool lastStep = false; - bool lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); - while (lastApprover && !lastStep) - { - currentStep++; - lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); - NotifyApproversForCancellation(ecnNumber, currentStep, documentType, ecnTypeString); - } - - if (lastApprover && lastStep) - { - try - { - lastApproverAndLastStep = true; - - ECNPdf ecn = new ECNPdf(); - GenerateECNPdf(ecnNumber, out ecn); - - - string sourceDirectory = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString() + "\\"; - string outputFullFilePath = ""; - - string outputFileName; - outputFileName = TECN_PREFIX + ecnNumber.ToString() + ".zip"; - - outputFullFilePath = Functions.GetAttachmentFolder() + "\\TECNCancelledZipped\\" + outputFileName; - - // Create the zipped package - Zipper zip = new Zipper(); - zip.CreateZip(outputFullFilePath, sourceDirectory); - NotifyTECNCancellation(ecnNumber, outputFullFilePath); - - - } - catch (Exception ex) - { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); - - } - } - - return lastApproverAndLastStep; - } - - /// - /// - /// - /// - /// - /// - /// - /// - public void ApproveExpiration(int ecnNumber, byte currentStep, string comments, int documentType, string ecnTypeString) - { - bool lastStep = false; - bool lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); - while (lastApprover && !lastStep) - { - currentStep++; - lastApprover = lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); - NotifyApproversForExpiration(ecnNumber, currentStep, documentType, ecnTypeString); - } - if (lastApprover && lastStep) - { - try - { - ECNPdf ecn = new ECNPdf(); - GenerateECNPdf(ecnNumber, out ecn); - - string sourceDirectory = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString() + "\\"; - string outputFullFilePath = ""; - - string outputFileName; - outputFileName = TECN_PREFIX + ecnNumber.ToString() + ".zip"; - - outputFullFilePath = Functions.GetAttachmentFolder() + "\\TECNExpiredZipped\\" + outputFileName; - - - Zipper zip = new Zipper(); - zip.CreateZip(outputFullFilePath, sourceDirectory); - - NotifyTECNExpiration(ecnNumber, outputFullFilePath); - } - catch (Exception ex) - { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); - - } - } - } - - /// - /// - /// - /// - public void CheckCanSubmit(int ecnNumber) - { - bool result = ecnDMO.CanSubmitECN(ecnNumber); - if (result) - { - throw new Exception("Cannot Submit"); - } - } - - - - /// - /// - /// - /// - public void ReleaseLockOnDocument(int issueID) - { - try - { - ecnDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); - } - catch(Exception e) - { - try - { - Functions.WriteEvent(@User.Identity.Name + "\r\n ReleaseLockOnDocument ECN\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); - } - catch { } - ecnDMO.ReleaseLockOnDocument(-1, issueID); - - } - - - } - public void ReleaseLockOnDocumentAdmin(int issueID) - { - try - { - ecnDMO.ReleaseLockOnDocument(-1, issueID); - } - catch (Exception e) - { - try - { - Functions.WriteEvent(@User.Identity.Name + "\r\n ReleaseLockOnDocument ECN\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); - } - catch { } - ecnDMO.ReleaseLockOnDocument(-1, issueID); - - } - - - } - /// - /// - /// - /// - /// - /// - public FileResult DownloadFile(string attachmentID, string ecnNumber) - { - //fileName = "ECNForm_71132.pdf"; - - string fileName = ecnDMO.GetFileName(attachmentID); - - string ecnFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString(); - var sDocument = Path.Combine(ecnFolderPath, fileName); - - var FDir_AppData = Functions.GetAttachmentFolder(); - if (!sDocument.StartsWith(FDir_AppData)) - { - // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder - // and block requests outside like "../web.config" - throw new HttpException(403, "Forbidden"); - } - - if (!System.IO.File.Exists(sDocument)) - { - return null; - //throw new Exception("File not found"); - } - - return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); - } - - ///// - ///// - ///// - //void CreateZipFile() + //foreach (string email in emailIst) //{ + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; + emailparams[0] = ecnNumber.ToString(); + emailparams[1] = ecnNumber.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = "TECN"; + emailparams[4] = DateTime.Now.ToString(); + //userEmail = email; - // try - // { - // using (ZipFile zip = new ZipFile()) - // { - // // note: this does not recurse directories! - // String[] filenames = System.IO.Directory.GetFiles(@"C:\Documents\Approval System\ECN-TECN"); - - // // This is just a sample, provided to illustrate the DotNetZip interface. - // // This logic does not recurse through sub-directories. - // // If you are zipping up a directory, you may want to see the AddDirectory() method, - // // which operates recursively. - // foreach (String filename in filenames) - // { - // Console.WriteLine("Adding {0}...", filename); - - // ZipEntry e = zip.AddFile(filename); - // e.Comment = "Added by Cheeso's CreateZip utility."; - // } - - // zip.Comment = String.Format("This zip archive was created by the CreateZip example application on machine '{0}'", - // System.Net.Dns.GetHostName()); - - // zip.Save(@"C:\Documents\Approval System\ECN-TECN\New.Zip"); - // } - - // } - // catch (System.Exception ex1) - // { - // System.Console.Error.WriteLine("exception: " + ex1); - // } +#if (DEBUG) + userEmail = GlobalVars.SENDER_EMAIL; +#endif + //en.SendNotificationEmailWithAttachment(emailTemplate, "rkotian1@irf.com", senderName, userEmail, null, subject, ecnFolderPath, emailparams); + if (IsITAR(ecn)) + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); + else + en.SendNotificationEmailWithAttachment(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, ecnFolderPath, emailparams); + //emailSentList += email + ","; + emailSentList = String.Join(", ", emailIst.Distinct().ToArray()); //} - /// - /// - /// - /// - /// - bool IsITAR(ECN ecn) - { - if (ecn.IsRH && !ecn.IsAU && !ecn.IsIndustrial && !ecn.IsMA) - { - return true; + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Cancellation :" + emailSentList }); + } catch { } + } + + public void NotifyTECNAutoCancellation(int ecnNumber, int tecnNumber, List attachments) { + //string ecnFolderPath = _AppSettings.AttachmentFolder + "TECNCancelledZipped\\" + TECN_PREFIX + ecnNumber.ToString() + ".zip"; + ECN ecn = ecnDMO.GetECN(tecnNumber); + string emailSentList = ""; + + List emailIst = MiscDMO.GetTECNCancelledApprovalNotifyList(ecnNumber).Distinct().ToList(); + + string emailTemplate = "TECNAutoCancelled.txt"; + string userEmail = string.Empty; + string subject = string.Empty; + subject = "TECN Conversion and Cancellation Notice - " + tecnNumber + " for " + ecn.Title + ", Converted on:" + DateTime.Now; + string senderName = "ECN"; + + //foreach (string email in emailIst) + //{ + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[6]; + emailparams[0] = tecnNumber.ToString(); + emailparams[1] = tecnNumber.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = "TECN"; + emailparams[4] = DateTime.Now.ToString(); + emailparams[5] = ecnNumber.ToString(); + //userEmail = email; + +#if (DEBUG) + userEmail = GlobalVars.SENDER_EMAIL; +#endif + + //en.SendNotificationEmailWithAttachment(emailTemplate, "rkotian1@irf.com", senderName, userEmail, null, subject, ecnFolderPath, emailparams); + if (IsITAR(ecn)) + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); + else + en.SendNotificationEmailWithAttachments(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, attachments, emailparams); + //emailSentList += email + ","; + emailSentList = String.Join(", ", emailIst.Distinct().ToArray()); + + //} + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Cancellation :" + emailSentList }); + } catch { } + } + + public void NotifyTECNExpiration(int ecnNumber, string ecnFolderPath) { + ECN ecn = ecnDMO.GetECN(ecnNumber); + //string ecnFolderPath = _AppSettings.AttachmentFolder + "TECNExpiredZipped\\" + TECN_PREFIX + ecnNumber.ToString() + ".zip"; + + string emailSentList = ""; + + List emailIst = MiscDMO.GetEmergencyTECNApprovalNotifyList(ecnNumber).Distinct().ToList(); + + string emailTemplate = "TECNExpired.txt"; + string userEmail = string.Empty; + string subject = "TECN Expiration Approved Notice - " + ecnNumber + " for " + ecn.Title + ", Expired:" + ecn.ExpirationDate; + string senderName = "ECN"; + + //foreach (string email in emailIst) + //{ + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; + emailparams[0] = ecnNumber.ToString(); + emailparams[1] = ecnNumber.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = "TECN"; + emailparams[4] = ecn.ExpirationDate.Value.ToShortDateString(); + //userEmail = email; + + //#if(DEBUG) + // userEmail = "rkotian1@infineon.com"; + //#endif + + //en.SendNotificationEmailWithAttachment(emailTemplate, "rkotian1@infineon.com", senderName, userEmail, null, subject, ecnFolderPath, emailparams); + if (IsITAR(ecn)) + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); + else + en.SendNotificationEmailWithAttachment(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, ecnFolderPath, emailparams); + + //emailSentList += email + ","; + emailSentList = String.Join(", ", emailIst.Distinct().ToArray()); + + //} + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Email", Comments = "Approvers for Expiration:" + emailSentList }); + } catch { } + } + + bool CreateZip(ECNPdf ecn) { + try { + string sourceDirectory = _AppSettings.AttachmentFolder + "ECN\\" + ecn.ECNNumber.ToString() + "\\"; + string outputFullFilePath = ""; + + string outputFileName; + if (ecn.IsTECN) { + if (ecn.ExtensionDate != null) + outputFileName = TECN_PREFIX + ecn.ECNNumber.ToString() + "_Extension.zip"; + else + outputFileName = TECN_PREFIX + ecn.ECNNumber.ToString() + ".zip"; + + outputFullFilePath = _AppSettings.AttachmentFolder + "\\ECNZipped\\" + outputFileName; + } else if (ecn.IsEmergencyTECN) // Transfer it to different folder , coz documentum does not need to have a Workflow Item created for Emergency TECN + { + outputFileName = ETECN_PREFIX + ecn.ECNNumber.ToString() + ".zip"; + outputFullFilePath = _AppSettings.AttachmentFolder + "\\E-TECNZipped\\" + outputFileName; + } else { + outputFileName = ECN_PREFIX + ecn.ECNNumber.ToString() + ".zip"; + outputFullFilePath = _AppSettings.AttachmentFolder + "\\ECNZipped\\" + outputFileName; } - else - return false; + + Zipper zip = new Zipper(); + zip.CreateZip(outputFullFilePath, sourceDirectory); + } catch (Exception ex) { + EventLogDMO.Add(new WinEventLog() { IssueID = ecn.ECNNumber, UserID = @User.Identity.Name, DocumentType = ecn.IsECN ? "ECN" : (ecn.IsEmergencyTECN ? "E-TECN" : "TECN"), OperationType = "Error", Comments = ex.Message }); + return false; + } + + return true; + } + + public void AddEECNApproval(int ecnNumber, byte step, string engUserIDs, string OpUserIDs) { + // it is always going to be the first step + step = 1; + string emailSentList = ""; + var emailArray = ""; + try { + emailArray = wfDMO.AddEECNApproval(ecnNumber, step, (int)GlobalVars.DocumentType.EECN, engUserIDs, OpUserIDs); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + step + " " + " Userid:" + engUserIDs + " - " + OpUserIDs + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddEECNApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN ", OperationType = "Error", Comments = "AddEECNApproval - " + exceptionString }); + throw new Exception(e.Message); + } + ECN ecn = ecnDMO.GetECN(ecnNumber); + string emailTemplate = "ECNAssigned.txt"; + string userEmail = string.Empty; + string subject = "E-TECN Assignment"; + string senderName = "E-TECN"; + + string[] emailIst = emailArray.Split(new char[] { '~' }); + foreach (string email in emailIst) { + if (email.Length > 0) { + subject = "E-TECN Assignment notice for Number " + ecn.ECNNumber + ", - " + ecn.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = ecnNumber.ToString(); + emailparams[1] = ecnNumber.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = "E-TECN"; + + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@infineon.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + emailSentList += email + ","; + + } + + } + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); + } catch { } + } + + public void SaveAfterSubmitByApprover(int ecnNumber, string implementationDetails) { + try { + ecnDMO.SaveAfterSubmitByApprover(ecnNumber, implementationDetails); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SaveAfterSubmitByApprover\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN ", OperationType = "Error", Comments = "SaveAfterSubmitByApprover - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public void DeleteDocument(int ecnNumber, string ecnTypeString) { + try { + ecnDMO.DeleteDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], ecnTypeString); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n DeleteDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "", OperationType = "Error", Comments = "DeleteDocument - " + exceptionString }); + throw new Exception(e.Message); + } + } + public void DeleteDocumentBySubmitter(int ecnNumber, string ecnTypeString) { + ECN ecn = ecnDMO.GetECN(ecnNumber); + int submitterId = ecn.OriginatorID; + if (submitterId == (int)Session[GlobalVars.SESSION_USERID]) { + try { + ecnDMO.DeleteDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], ecnTypeString); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n DeleteDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "", OperationType = "Error", Comments = "DeleteDocument - " + exceptionString }); + throw new Exception(e.Message); + } + } else { + } + } + + public ActionResult ReSubmitDocument(int ecnNumber, int documentType, string ecnTypeString, string oldECNTypeString, string descriptionOfChange, string reasonForChange, string categoryId = "") { + // Update ECN Type in the ECN table + + ECN ecn = new ECN(); + + int isITARCompliant = 1; + int newECNNumber = 0; + int catId = 0; + Int32.TryParse(categoryId, out catId); + try { + int appoverCount = ecnDMO.ReSubmitDocument( + ecnNumber, + (int)Session[GlobalVars.SESSION_USERID], + documentType, + out isITARCompliant, + descriptionOfChange, + reasonForChange, + ecnTypeString, + out newECNNumber, + catId); + + if (isITARCompliant == 0) // not ITAR Compliant + { + // the content gets evaluated on the client side + return Content("ITAR"); + } else { + //TODO - COPY ATTACHMENTS + Functions.CopyAttachments(_AppSettings, ecnNumber, newECNNumber); + + // Log into the Approval Log + try { + ecn = ecnDMO.GetECN(ecnNumber); + + //ecnDMO.UpdateECNType(ecnNumber, ecnTypeString); + + ApprovalLogDMO.Add(new ApprovalLog { + IssueID = ecnNumber, + DocumentTypeID = documentType, + OperationType = "Changed From " + oldECNTypeString + " To " + ecnTypeString, + UserID = (int)Session[GlobalVars.SESSION_USERID], + OperationLog = "Changed the Document Type" + }); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReSubmitDocument (ApprovalLogDMO)\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReSubmitDocument (ApprovalLogDMO)" + exceptionString }); + + } + + // Add to the Document Change Log + try { + ECNTypeChangeLogDMO.Add(new ECNTypeChangeLog { + ECNNumber = ecnNumber, + UserID = (int)Session[GlobalVars.SESSION_USERID], + ECNTypeFrom = oldECNTypeString, + ECNTypeTo = ecnTypeString + }); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReSubmitDocument (ECNTypeChangeLogDMO)\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReSubmitDocument (ECNTypeChangeLogDMO)" + exceptionString }); + + } + + //if (appoverCount > 0) + //{ + // NotifyApprovers(newECNNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, documentType, ecnTypeString); + //} + //else + //{ + // // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval + // Approve(newECNNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, "", documentType, ecnTypeString); // this is the Submit Level Approval + + //} + + if (Request.IsAjaxRequest()) { + // the content gets evaluated on the client side + return Content("Redirect~" + newECNNumber); + + } else + return Content("Invalid"); + } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Re-SubmitDocument - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public ActionResult PCRBExists(int pcrb) { + + return Content(ecnDMO.PCRBExists(pcrb).ToString()); + } + + public ActionResult CancelDocument(int ecnNumber, byte currentStep, int documentType, string ecnTypeString) { + // log the cancelled event + //EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Cancelled", Comments = "Cancelled the document" }); + // Set the ECN Current step to the last step of the document type, which is the execution step + + bool lastApproverAndLastStep = false; + int appoverCount = ecnDMO.SubmitForCancellation(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, (int)Session[GlobalVars.SESSION_USERID], documentType, ecnTypeString, (int)GlobalVars.TECNExpirationCancellation.Cancellation); + if (appoverCount > 0) { + NotifyApproversForCancellation(ecnNumber, currentStep, documentType, ecnTypeString); + } else // TODO Automatically close the + { + lastApproverAndLastStep = ApproveCancellation(ecnNumber, currentStep, "", documentType, ecnTypeString); + // automaically approve current step (Step 1) because there are no approvers in step 1 and move to the next step of approval + //Approve(ecnNumber, currentStep, "", documentType, ecnTypeString); // this is the Submit Level Approval } - + // if there are approvers dont wait for it to finish the approval loop for sending cancel notications. + if (!lastApproverAndLastStep) { + // send notifications + try { + lastApproverAndLastStep = true; + + ECNPdf ecn = new ECNPdf(); + GenerateECNPdf(ecnNumber, out ecn); + + string sourceDirectory = _AppSettings.AttachmentFolder + "ECN\\" + ecnNumber.ToString() + "\\"; + string outputFullFilePath = ""; + + string outputFileName; + outputFileName = TECN_PREFIX + ecnNumber.ToString() + ".zip"; + + outputFullFilePath = _AppSettings.AttachmentFolder + "\\TECNCancelledZipped\\" + outputFileName; + + // Create the zipped package + Zipper zip = new Zipper(); + zip.CreateZip(outputFullFilePath, sourceDirectory); + NotifyTECNCancellation(ecnNumber, outputFullFilePath); + + } catch (Exception ex) { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); + + } + + } + int trainingId = trainingDMO.GetTrainingId(ecnNumber); + trainingDMO.DeleteTraining(trainingId); + + if (Request.IsAjaxRequest()) { + // the content gets evaluated on the client side + return Content("Redirect"); + } else + return Content("Invalid"); } -} + public ActionResult CancelDocumentBySubmitter(int ecnNumber, byte currentStep, int documentType, string ecnTypeString) { + return Content("Redirect"); + } + + public bool ApproveCancellation(int ecnNumber, byte currentStep, string comments, int documentType, string ecnTypeString) { + bool lastApproverAndLastStep = false; + bool lastStep = false; + bool lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); + while (lastApprover && !lastStep) { + currentStep++; + lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); + NotifyApproversForCancellation(ecnNumber, currentStep, documentType, ecnTypeString); + } + + if (lastApprover && lastStep) { + try { + lastApproverAndLastStep = true; + + ECNPdf ecn = new ECNPdf(); + GenerateECNPdf(ecnNumber, out ecn); + + string sourceDirectory = _AppSettings.AttachmentFolder + "ECN\\" + ecnNumber.ToString() + "\\"; + string outputFullFilePath = ""; + + string outputFileName; + outputFileName = TECN_PREFIX + ecnNumber.ToString() + ".zip"; + + outputFullFilePath = _AppSettings.AttachmentFolder + "\\TECNCancelledZipped\\" + outputFileName; + + // Create the zipped package + Zipper zip = new Zipper(); + zip.CreateZip(outputFullFilePath, sourceDirectory); + NotifyTECNCancellation(ecnNumber, outputFullFilePath); + + } catch (Exception ex) { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); + + } + } + + return lastApproverAndLastStep; + } + + public void ApproveExpiration(int ecnNumber, byte currentStep, string comments, int documentType, string ecnTypeString) { + bool lastStep = false; + bool lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); + while (lastApprover && !lastStep) { + currentStep++; + lastApprover = lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); + NotifyApproversForExpiration(ecnNumber, currentStep, documentType, ecnTypeString); + } + if (lastApprover && lastStep) { + try { + ECNPdf ecn = new ECNPdf(); + GenerateECNPdf(ecnNumber, out ecn); + + string sourceDirectory = _AppSettings.AttachmentFolder + "ECN\\" + ecnNumber.ToString() + "\\"; + string outputFullFilePath = ""; + + string outputFileName; + outputFileName = TECN_PREFIX + ecnNumber.ToString() + ".zip"; + + outputFullFilePath = _AppSettings.AttachmentFolder + "\\TECNExpiredZipped\\" + outputFileName; + + Zipper zip = new Zipper(); + zip.CreateZip(outputFullFilePath, sourceDirectory); + + NotifyTECNExpiration(ecnNumber, outputFullFilePath); + } catch (Exception ex) { + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); + + } + } + } + + public void CheckCanSubmit(int ecnNumber) { + bool result = ecnDMO.CanSubmitECN(ecnNumber); + if (result) { + throw new Exception("Cannot Submit"); + } + } + + public void ReleaseLockOnDocument(int issueID) { + try { + ecnDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); + } catch (Exception e) { + try { + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument ECN\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + } catch { } + ecnDMO.ReleaseLockOnDocument(-1, issueID); + } + } + public void ReleaseLockOnDocumentAdmin(int issueID) { + try { + ecnDMO.ReleaseLockOnDocument(-1, issueID); + } catch (Exception e) { + try { + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument ECN\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + } catch { } + ecnDMO.ReleaseLockOnDocument(-1, issueID); + } + } + + public FileResult DownloadFile(string attachmentID, string ecnNumber) { + //fileName = "ECNForm_71132.pdf"; + + string fileName = ecnDMO.GetFileName(attachmentID); + + string ecnFolderPath = _AppSettings.AttachmentFolder + "ECN\\" + ecnNumber.ToString(); + var sDocument = Path.Combine(ecnFolderPath, fileName); + + var FDir_AppData = _AppSettings.AttachmentFolder; + if (!sDocument.StartsWith(FDir_AppData)) { + // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder + // and block requests outside like "../web.config" + throw new HttpException(403, "Forbidden"); + } + + if (!System.IO.File.Exists(sDocument)) { + return null; + //throw new Exception("File not found"); + } + + return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + } + + ///// + ///// + ///// + //void CreateZipFile() + //{ + // try + // { + // using (ZipFile zip = new ZipFile()) + // { + // // note: this does not recurse directories! + // String[] filenames = System.IO.Directory.GetFiles(@"C:\Documents\Approval System\ECN-TECN"); + + // // This is just a sample, provided to illustrate the DotNetZip interface. + // // This logic does not recurse through sub-directories. + // // If you are zipping up a directory, you may want to see the AddDirectory() method, + // // which operates recursively. + // foreach (String filename in filenames) + // { + // Console.WriteLine("Adding {0}...", filename); + + // ZipEntry e = zip.AddFile(filename); + // e.Comment = "Added by Cheeso's CreateZip utility."; + // } + + // zip.Comment = String.Format("This zip archive was created by the CreateZip example application on machine '{0}'", + // System.Net.Dns.GetHostName()); + + // zip.Save(@"C:\Documents\Approval System\ECN-TECN\New.Zip"); + // } + + // } + // catch (System.Exception ex1) + // { + // System.Console.Error.WriteLine("exception: " + ex1); + // } + + //} + + bool IsITAR(ECN ecn) { + if (ecn.IsRH && !ecn.IsAU && !ecn.IsIndustrial && !ecn.IsMA) { + return true; + } else + return false; + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/HomeController.cs b/Fab2ApprovalSystem/Controllers/HomeController.cs index 328faf0..a04752a 100644 --- a/Fab2ApprovalSystem/Controllers/HomeController.cs +++ b/Fab2ApprovalSystem/Controllers/HomeController.cs @@ -1,10 +1,3 @@ -using Fab2ApprovalSystem.DMO; -using Fab2ApprovalSystem.Utilities; -using Fab2ApprovalSystem.Misc; -using Fab2ApprovalSystem.Models; -using Fab2ApprovalSystem.ViewModels; -using Kendo.Mvc.Extensions; -using Kendo.Mvc.UI; using System; using System.Collections.Generic; using System.Configuration; @@ -12,808 +5,514 @@ using System.Linq; using System.Web; using System.Web.Mvc; -namespace Fab2ApprovalSystem.Controllers -{ - - [Authorize] - [SessionExpireFilter] - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - public class HomeController : Controller - { - LotDispositionDMO ldDMO = new LotDispositionDMO(); - MRB_DMO mrbDMO = new MRB_DMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); - ECN_DMO ecnDMO = new ECN_DMO(); - PartsRequestDMO prDMO = new PartsRequestDMO(); - UserUtilities userDMO = new UserUtilities(); - UserAccountDMO originalUserDMO = new UserAccountDMO(); - TrainingDMO trainingDMO = new TrainingDMO(); - MiscDMO miscDMO = new MiscDMO(); - - - /// - /// - /// - /// - /// - public ActionResult Index(string tabName) - { - ViewBag.ActiveTabName = tabName; - - return View(); - } - - /// - /// - /// - /// - public ActionResult MyTasks() - { - return View(); - } - - - public ActionResult AllDocuments() - { - return View(); - } - - - /// - /// - /// - /// - public ActionResult SpecialWorkRequestList() - { - return View(); - } - - - public ActionResult MRBList() - { - return View(); - } - - public ActionResult ECNList() - { - return View(); - } - public ActionResult TrainingList() - { - return View(); - } - - public ActionResult LotDispositionList() - { - return View(); - } - - - public ActionResult AuditList() - { - return View(); - } - - public ActionResult CorrectiveActionList() - { - return View(); - } - - /// - /// - /// - /// - /// - public ActionResult ECN_TECN(string viewOption) - { - ViewBag.ViewOption = viewOption; - return View(); - } - - - - public ActionResult ChangeControlList() - { - return View(); - } - /// - /// - /// - /// - /// - public ActionResult GetTaskList([DataSourceRequest]DataSourceRequest request, string tabName) - { - try - { - ViewBag.ActiveTabName = tabName; - List data = ldDMO.GetTaskList((int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList(); - return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - catch (Exception ex) - { - // TODO record the error - throw ex; - } - } - - public ActionResult GetMyOpenActionItems([DataSourceRequest]DataSourceRequest request, string tabName) - { - try - { - ViewBag.ActiveTabName = tabName; - List data = ldDMO.GetMyOpenActionItems((int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList(); - return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - catch (Exception ex) - { - // TODO record the error - throw ex; - } - } - - - - - public ActionResult GetDocuments([DataSourceRequest]DataSourceRequest request, string tabName) - { - ViewBag.ActiveTabName = tabName; - //IEnumerable data = ldDMO.GetLotDispositions(); - IEnumerable data = ldDMO.GetDocuments(); - return Json(data.ToDataSourceResult(request)); - } - - - /// - /// - /// - /// - /// - public ActionResult GetWorkRequests([DataSourceRequest]DataSourceRequest request) - { - IEnumerable data = ldDMO.GetWorkRequests(); - return Json(data.ToDataSourceResult(request)); - } - - - /// - /// - /// - /// - /// - public ActionResult GetChangeControlList([DataSourceRequest]DataSourceRequest request) - { - - IEnumerable data = ldDMO.GetChangeControls(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); - return Json(data.ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - public ActionResult GetAuditList([DataSourceRequest]DataSourceRequest request) - { - - IEnumerable data = ldDMO.GetAuditList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); - return Json(data.ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - public ActionResult GetCorrectiveActionList([DataSourceRequest]DataSourceRequest request) - { - - IEnumerable data = ldDMO.GetCorrectiveActionList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); - return Json(data.ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - public ActionResult GetMRBList([DataSourceRequest]DataSourceRequest request) - { - - IEnumerable data = ldDMO.GetMRBList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); - return Json(data.ToDataSourceResult(request)); - } - - - /// - /// - /// - /// - /// - public ActionResult GetLotDispositionList([DataSourceRequest]DataSourceRequest request) - { - - IEnumerable data = ldDMO.GetLotDispositionList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); - return Json(data.ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - public ActionResult GetECNList([DataSourceRequest]DataSourceRequest request) - { - - IEnumerable data = ldDMO.GetECNList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); - return Json(data.ToDataSourceResult(request)); - } - public ActionResult GetTrainingList([DataSourceRequest]DataSourceRequest request) - { - - IEnumerable data = trainingDMO.GetAllTrainings(); - return Json(data.ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - public ActionResult MyECNsTECNs(string dataType) - { - ViewBag.ActiveTabName = dataType; - return View(); - } - - /// - /// - /// - /// - /// - public ActionResult GetECN_TECNsPendingApproval([DataSourceRequest]DataSourceRequest request) - { - IEnumerable data = ecnDMO.GetECN_TECNPendingApprovals(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); - ViewBag.ViewOption = "Pending Approvals"; - Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; - return Json(data.ToDataSourceResult(request)); - - } - - - /// - /// - /// - /// - /// - public ActionResult GetMyExpiredTECNs([DataSourceRequest]DataSourceRequest request) - { - - IEnumerable data = ecnDMO.GetMyExpiredTECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); - ViewBag.ViewOption = "Expired TECNs"; - Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; - return Json(data.ToDataSourceResult(request)); - - } - public ActionResult GetAllTECNs([DataSourceRequest]DataSourceRequest request) - { - - IEnumerable data = ecnDMO.GetAllTECNs(); - ViewBag.ViewOption = "All TECNs"; - Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; - return Json(data.ToDataSourceResult(request)); - - } - - /// - /// - /// - /// - /// - public ActionResult GetMyConvertedTECNsToECNs([DataSourceRequest]DataSourceRequest request) - { - IEnumerable data = ecnDMO.GetMyConvertedTECNsToECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); - ViewBag.ViewOption = "Converted TECNs"; - Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; - return Json(data.ToDataSourceResult(request)); - - } - - - /// - /// - /// - /// - /// - public ActionResult GetMyExpiringTECNs([DataSourceRequest]DataSourceRequest request) - { - IEnumerable data = ecnDMO.GetMyExpiringTECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); - ViewBag.ViewOption = "Expiring TECNs"; - Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; - return Json(data.ToDataSourceResult(request)); - - } - - - - /// - /// - /// - /// - /// - /// - public ActionResult GetLotList([DataSourceRequest] DataSourceRequest request, int workRequestID) - { - LotTravelerDMO LotTravDMO = new LotTravelerDMO(); - return Json(LotTravDMO.GetLotListBasedOnSWRNumber(workRequestID).ToDataSourceResult(request)); - } - - /// - /// - /// - /// - - public ActionResult SetOOOStatus(int delegatedTo, DateTime startDate, DateTime endDate, string tab) - { - - if (Session[GlobalVars.SESSION_USERID] != null) - { - int returnValue = MiscDMO.EnableOOOStatus(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), delegatedTo, startDate, endDate); - if (returnValue == 3) // the delegator is already a delegator to someone else - { - return Content("3"); - } - if (startDate <= DateTime.Today) - Session[GlobalVars.OOO] = true; - - NotifyDelegation(delegatedTo, startDate, endDate); - } - - return Content(""); - } - - - /// - /// - /// - /// - public void ExpireOOOStatus(string tab) - { - if (Session[GlobalVars.SESSION_USERID] != null) - { - MiscDMO.ExpireOOOStatus(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); - Session[GlobalVars.OOO] = false; - - } - - } - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteItem([DataSourceRequest] DataSourceRequest request, IssuesViewModel issue) - { - - GlobalVars.DocumentType dType; - Enum.TryParse(issue.DocumentType, out dType); - if (dType == GlobalVars.DocumentType.MRB) - mrbDMO.DeleteMRB(issue.IssueID); - else if (dType == GlobalVars.DocumentType.LotDisposition) - ldDMO.DeleteLotDisposition(issue.IssueID); - else if (dType == GlobalVars.DocumentType.ECN) - ecnDMO.DeleteDocument(issue.IssueID, int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), "ECN"); - else if (dType == GlobalVars.DocumentType.CorrectiveAction) - ldDMO.DeleteCADocument(issue.IssueID, int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), "Corrective Action"); - - - return Json(new[] { issue }.ToDataSourceResult(request, ModelState)); - } - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteCAItem([DataSourceRequest] DataSourceRequest request, CorrectiveAction ca) - { - ldDMO.DeleteCADocument(ca.CANo, int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), "Corrective Action"); - - - return Json(new[] { ca }.ToDataSourceResult(request, ModelState)); - } - - /// - /// - /// - /// - public ActionResult About() - { - ViewBag.Message = "Your application description page."; - - return View(); - } - - /// - /// - /// - /// - public ActionResult Contact() - { - ViewBag.Message = "Your contact page."; - - return View(); - } - - #region testing purpose - public ActionResult Edit() - { - - return View(DemoHelper.Instance.ListOfModels[0]); - } - - [HttpPost] - public ActionResult Edit(TestModel editTest) - { - DemoHelper.Instance.ListOfModels[0] = editTest; - return RedirectToAction("Index"); - } - - public static void Test() - { - - string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" }; - foreach (string colorString in colorStrings) - { - GlobalVars.Colors colorValue; - if (Enum.TryParse(colorString, true, out colorValue)) - if (Enum.IsDefined(typeof(GlobalVars.Colors), colorValue) | colorValue.ToString().Contains(",")) - Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString()); - else - Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString); - else - Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString); - } - } - - #endregion - - /// - /// - /// - /// - /// - /// - /// - /// - public void DelegateDocumentApproval(int issueID, int delegateTo, string ecnTypeString, string title) - { - - var email = ""; - int delegateFrom = (int)Session[GlobalVars.SESSION_USERID]; - try - { - email = wfDMO.DelegateDocumentApproval(issueID, delegateFrom, delegateTo); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString , OperationType = "Delegation", Comments = "Delegated from - " + delegateFrom + " to " + delegateTo }); - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n DelegateApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = " + ecnTypeString + ", OperationType = "Error", Comments = "DelegateApproval - " + exceptionString }); - throw new Exception(e.Message); - } - - string emailTemplate = "DelegateApproval.txt"; - string userEmail = string.Empty; - string subject; - string senderName = ecnTypeString; - - subject = ecnTypeString + " Delegation" + " - Email would be sent to " + email + " for Number " + issueID + ", - " + title; ; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = issueID.ToString(); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = ecnTypeString; - - userEmail = email; - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Delegated to Approver: " + email }); - } - catch { } - - } - - /// - /// - /// - /// - public JsonResult GetAllUsersList() - { - - UserAccountDMO userDMO = new UserAccountDMO(); - IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); - - } - - /// - /// - /// - /// - /// - public ActionResult SaveAllDocumentsFilter(string data) - { - Session["AllDocumentsFilterData"] = data; - return new EmptyResult(); - } - - /// - /// - /// - /// - public ActionResult LoadAllDocumentsFilter() - { - return Json(Session["AllDocumentsFilterData"], JsonRequestBehavior.AllowGet); - } - - /// - /// - /// - /// - /// - public ActionResult SaveSWRFilter(string data) - { - Session["SWRFilterData"] = data; - return new EmptyResult(); - } - - /// - /// - /// - /// - public ActionResult LoadSWRFilter() - { - return Json(Session["SWRFilterData"], JsonRequestBehavior.AllowGet); - } - - /// - /// - /// - /// - /// - public ActionResult SavePCRBFilter(string data) - { - Session["PCRBFilterData"] = data; - return new EmptyResult(); - } - - /// - /// - /// - /// - public ActionResult LoadPCRBFilter() - { - return Json(Session["PCRBFilterData"], JsonRequestBehavior.AllowGet); - } - - public ActionResult PartsRequestList() - { - ViewBag.CanDeletePR = Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]; - return View(); - } - - public ActionResult GetPartsRequestList([DataSourceRequest]DataSourceRequest request) - { - IEnumerable data = prDMO.GetPartsRequestList(); - return Json(data.ToDataSourceResult(request)); - } - - public ActionResult GetMyPartsRequestsList([DataSourceRequest]DataSourceRequest request, string tabName) - { - try - { - ViewBag.ActiveTabName = tabName; - var data = prDMO.GetMyPartsRequests((int)Session[GlobalVars.SESSION_USERID]); - return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - catch (Exception ex) - { - // TODO record the error - throw ex; - } - } - - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeletePR([DataSourceRequest] DataSourceRequest request, MyPartsRequestList pr) - { - try - { - if (Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]) == false) - throw new Exception("Permission denied"); - - prDMO.DeleteDocument(pr.PRNumber, (int)Session[GlobalVars.SESSION_USERID]); - return Json(new[] { pr }.ToDataSourceResult(request, ModelState)); - } - catch (Exception ex) - { - return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, ex.Message); - } - } - - public void NotifyDelegation(int delegatedUser, DateTime startDate, DateTime endDate) - { - LoginModel delegateFrom = originalUserDMO.GetUserByID((int)Session[GlobalVars.SESSION_USERID]); - LoginModel delegateTo = originalUserDMO.GetUserByID(delegatedUser); - List emailList = new List(); - emailList.Add(delegateFrom.Email); - emailList.Add(delegateTo.Email); - - string emailTemplate = "DelegationOn.txt"; - string userEmail = string.Empty; - string subject = "Mesa Approval Delegation Notification"; - string senderName = "Mesa Approval"; - - foreach (string email in emailList) - { - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = delegateFrom.FullName; - emailparams[1] = delegateTo.FullName; - emailparams[2] = startDate.ToString("yyyy-MM-dd"); - emailparams[3] = endDate.ToString("yyyy-MM-dd"); - userEmail = email; - //#if(DEBUG) - // userEmail = GlobalVars.SENDER_EMAIL; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - } - - try - { - - //EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail }); - } - catch { } - - } - public bool ProcessOoO() - { - - - try - { - UserAccountDMO userDMO = new UserAccountDMO(); - userDMO.ProcessOoO(); - return true; - } - catch - { - return false; - } - - } - public bool ExpireOoO() - { - - - try - { - UserAccountDMO userDMO = new UserAccountDMO(); - userDMO.ExpireOoO(); - return true; - } - catch - { - return false; - } - - } - public bool ApprovalsReminderNotifications() - { - try - { - //Get list of approvals - List approveList = miscDMO.GetApprovalReminderList(); - - foreach (var item in approveList) - { - - try - { - NotifyApprover(item.AssignedEmail, item.Title, item.IssueID, item.DocType); - } - catch(Exception e) - { - EventLogDMO.Add(new WinEventLog() { IssueID = item.ApprovalKey, UserID = "SYSTEM", DocumentType = "Approval Reminders", OperationType = "Email", Comments = e.Message }); - } - //We want to update the last notification anyway so we don't continue trying on something that may be failing. - miscDMO.UpdateApprovalNotifyDate(item.ApprovalKey); - } - // List approveList = miscDMO. - return true; - } - catch - { - return false; - } - } - public void NotifyApprover(string toEmail, string title, int issueId, string docType) - { - - try - { - string emailSentList = ""; - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - //List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); - //string ecnCreatedByEmail = MiscDMO.GetEmail(ecnCreatedById); - - string emailTemplate = "ApprovalReminders.txt"; - string userEmail = string.Empty; - string subject = string.Empty; - string senderName = docType; - - subject = docType + " Approval Reminder: " + title; - - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = docType; - emailparams[1] = title; - emailparams[2] = issueId.ToString(); - userEmail = toEmail; - - //#if(DEBUG) - //string SenderEmail = "MesaFabApproval@infineon.com"; - //userEmail = "jonathan.ouellette@infineon.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, "jonathan.ouellette@infineon.com", subject, emailparams); - //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams); - //emailSentList = ecnCreatedByEmail; - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueId, UserID = @User.Identity.Name, DocumentType = docType, OperationType = "Email", Comments = "Approval reminders" }); - } - catch { } - - //EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - //string[] emailparams = new string[4]; - //emailparams[0] = issueID.ToString(); - //emailparams[1] = issueID.ToString(); - //emailparams[2] = GlobalVars.hostURL; - //emailparams[3] =Session[GlobalVars.SESSION_USERNAME].ToString(); - //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - EventLogDMO.Add(new WinEventLog() { IssueID = issueId, UserID = @User.Identity.Name, DocumentType = docType, OperationType = "Email", Comments = "Approval reminders" }); - throw e; - - } - - - } - +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.Utilities; +using Fab2ApprovalSystem.ViewModels; + +using Kendo.Mvc.Extensions; +using Kendo.Mvc.UI; + +namespace Fab2ApprovalSystem.Controllers; + +[Authorize] +[SessionExpireFilter] +[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +public class HomeController : Controller { + + MRB_DMO mrbDMO; + PartsRequestDMO prDMO; + LotDispositionDMO ldDMO; + WorkflowDMO wfDMO = new WorkflowDMO(); + ECN_DMO ecnDMO = new ECN_DMO(); + UserUtilities userDMO = new UserUtilities(); + UserAccountDMO originalUserDMO = new UserAccountDMO(); + TrainingDMO trainingDMO = new TrainingDMO(); + MiscDMO miscDMO = new MiscDMO(); + private readonly AppSettings _AppSettings; + + public HomeController(AppSettings appSettings) { + _AppSettings = appSettings; + ldDMO = new LotDispositionDMO(appSettings); + mrbDMO = new MRB_DMO(appSettings); + prDMO = new PartsRequestDMO(appSettings); } -} + + public ActionResult Index(string tabName) { + ViewBag.ActiveTabName = tabName; + + return View(); + } + + public ActionResult MyTasks() { + return View(); + } + + public ActionResult AllDocuments() { + return View(); + } + + public ActionResult SpecialWorkRequestList() { + return View(); + } + + public ActionResult MRBList() { + return View(); + } + + public ActionResult ECNList() { + return View(); + } + public ActionResult TrainingList() { + return View(); + } + + public ActionResult LotDispositionList() { + return View(); + } + + public ActionResult AuditList() { + return View(); + } + + public ActionResult CorrectiveActionList() { + return View(); + } + + public ActionResult ECN_TECN(string viewOption) { + ViewBag.ViewOption = viewOption; + return View(); + } + + public ActionResult ChangeControlList() { + return View(); + } + + public ActionResult GetTaskList([DataSourceRequest] DataSourceRequest request, string tabName) { + try { + ViewBag.ActiveTabName = tabName; + List data = ldDMO.GetTaskList((int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList(); + return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } catch (Exception ex) { + // TODO record the error + throw ex; + } + } + + public ActionResult GetMyOpenActionItems([DataSourceRequest] DataSourceRequest request, string tabName) { + try { + ViewBag.ActiveTabName = tabName; + List data = ldDMO.GetMyOpenActionItems((int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList(); + return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } catch (Exception ex) { + // TODO record the error + throw ex; + } + } + + public ActionResult GetDocuments([DataSourceRequest] DataSourceRequest request, string tabName) { + ViewBag.ActiveTabName = tabName; + //IEnumerable data = ldDMO.GetLotDispositions(); + IEnumerable data = ldDMO.GetDocuments(); + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetWorkRequests([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = ldDMO.GetWorkRequests(); + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetChangeControlList([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = ldDMO.GetChangeControls(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetAuditList([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = ldDMO.GetAuditList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetCorrectiveActionList([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = ldDMO.GetCorrectiveActionList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetMRBList([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = ldDMO.GetMRBList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetLotDispositionList([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = ldDMO.GetLotDispositionList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetECNList([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = ldDMO.GetECNList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + return Json(data.ToDataSourceResult(request)); + } + public ActionResult GetTrainingList([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = trainingDMO.GetAllTrainings(); + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult MyECNsTECNs(string dataType) { + ViewBag.ActiveTabName = dataType; + return View(); + } + + public ActionResult GetECN_TECNsPendingApproval([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = ecnDMO.GetECN_TECNPendingApprovals(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + ViewBag.ViewOption = "Pending Approvals"; + Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetMyExpiredTECNs([DataSourceRequest] DataSourceRequest request) { + + IEnumerable data = ecnDMO.GetMyExpiredTECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); + ViewBag.ViewOption = "Expired TECNs"; + Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; + return Json(data.ToDataSourceResult(request)); + } + public ActionResult GetAllTECNs([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = ecnDMO.GetAllTECNs(); + ViewBag.ViewOption = "All TECNs"; + Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetMyConvertedTECNsToECNs([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = ecnDMO.GetMyConvertedTECNsToECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); + ViewBag.ViewOption = "Converted TECNs"; + Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetMyExpiringTECNs([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = ecnDMO.GetMyExpiringTECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); + ViewBag.ViewOption = "Expiring TECNs"; + Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetLotList([DataSourceRequest] DataSourceRequest request, int workRequestID) { + LotTravelerDMO LotTravDMO = new LotTravelerDMO(_AppSettings); + return Json(LotTravDMO.GetLotListBasedOnSWRNumber(workRequestID).ToDataSourceResult(request)); + } + + /// + + public ActionResult SetOOOStatus(int delegatedTo, DateTime startDate, DateTime endDate, string tab) { + if (Session[GlobalVars.SESSION_USERID] != null) { + int returnValue = MiscDMO.EnableOOOStatus(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), delegatedTo, startDate, endDate); + if (returnValue == 3) // the delegator is already a delegator to someone else + { + return Content("3"); + } + if (startDate <= DateTime.Today) + Session[GlobalVars.OOO] = true; + + NotifyDelegation(delegatedTo, startDate, endDate); + } + + return Content(""); + } + + public void ExpireOOOStatus(string tab) { + if (Session[GlobalVars.SESSION_USERID] != null) { + MiscDMO.ExpireOOOStatus(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + Session[GlobalVars.OOO] = false; + } + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteItem([DataSourceRequest] DataSourceRequest request, IssuesViewModel issue) { + GlobalVars.DocumentType dType; + Enum.TryParse(issue.DocumentType, out dType); + if (dType == GlobalVars.DocumentType.MRB) + mrbDMO.DeleteMRB(issue.IssueID); + else if (dType == GlobalVars.DocumentType.LotDisposition) + ldDMO.DeleteLotDisposition(issue.IssueID); + else if (dType == GlobalVars.DocumentType.ECN) + ecnDMO.DeleteDocument(issue.IssueID, int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), "ECN"); + else if (dType == GlobalVars.DocumentType.CorrectiveAction) + ldDMO.DeleteCADocument(issue.IssueID, int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), "Corrective Action"); + + return Json(new[] { issue }.ToDataSourceResult(request, ModelState)); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteCAItem([DataSourceRequest] DataSourceRequest request, CorrectiveAction ca) { + ldDMO.DeleteCADocument(ca.CANo, int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), "Corrective Action"); + + return Json(new[] { ca }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult About() { + ViewBag.Message = "Your application description page."; + + return View(); + } + + public ActionResult Contact() { + ViewBag.Message = "Your contact page."; + + return View(); + } + + #region testing purpose + public ActionResult Edit() { + return View(DemoHelper.Instance.ListOfModels[0]); + } + + [HttpPost] + public ActionResult Edit(TestModel editTest) { + DemoHelper.Instance.ListOfModels[0] = editTest; + return RedirectToAction("Index"); + } + + public static void Test() { + string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" }; + foreach (string colorString in colorStrings) { + GlobalVars.Colors colorValue; + if (Enum.TryParse(colorString, true, out colorValue)) + if (Enum.IsDefined(typeof(GlobalVars.Colors), colorValue) | colorValue.ToString().Contains(",")) + Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString()); + else + Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString); + else + Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString); + } + } + + #endregion + + public void DelegateDocumentApproval(int issueID, int delegateTo, string ecnTypeString, string title) { + var email = ""; + int delegateFrom = (int)Session[GlobalVars.SESSION_USERID]; + try { + email = wfDMO.DelegateDocumentApproval(issueID, delegateFrom, delegateTo); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Delegation", Comments = "Delegated from - " + delegateFrom + " to " + delegateTo }); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n DelegateApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = " + ecnTypeString + ", OperationType = "Error", Comments = "DelegateApproval - " + exceptionString }); + throw new Exception(e.Message); + } + + string emailTemplate = "DelegateApproval.txt"; + string userEmail = string.Empty; + string subject; + string senderName = ecnTypeString; + + subject = ecnTypeString + " Delegation" + " - Email would be sent to " + email + " for Number " + issueID + ", - " + title; + ; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = issueID.ToString(); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = ecnTypeString; + + userEmail = email; + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Delegated to Approver: " + email }); + } catch { } + } + + public JsonResult GetAllUsersList() { + + UserAccountDMO userDMO = new UserAccountDMO(); + IEnumerable userlist = userDMO.GetAllUsers(); + return Json(userlist, JsonRequestBehavior.AllowGet); + } + + public ActionResult SaveAllDocumentsFilter(string data) { + Session["AllDocumentsFilterData"] = data; + return new EmptyResult(); + } + + public ActionResult LoadAllDocumentsFilter() { + return Json(Session["AllDocumentsFilterData"], JsonRequestBehavior.AllowGet); + } + + public ActionResult SaveSWRFilter(string data) { + Session["SWRFilterData"] = data; + return new EmptyResult(); + } + + public ActionResult LoadSWRFilter() { + return Json(Session["SWRFilterData"], JsonRequestBehavior.AllowGet); + } + + public ActionResult SavePCRBFilter(string data) { + Session["PCRBFilterData"] = data; + return new EmptyResult(); + } + + public ActionResult LoadPCRBFilter() { + return Json(Session["PCRBFilterData"], JsonRequestBehavior.AllowGet); + } + + public ActionResult PartsRequestList() { + ViewBag.CanDeletePR = Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]; + return View(); + } + + public ActionResult GetPartsRequestList([DataSourceRequest] DataSourceRequest request) { + IEnumerable data = prDMO.GetPartsRequestList(); + return Json(data.ToDataSourceResult(request)); + } + + public ActionResult GetMyPartsRequestsList([DataSourceRequest] DataSourceRequest request, string tabName) { + try { + ViewBag.ActiveTabName = tabName; + var data = prDMO.GetMyPartsRequests((int)Session[GlobalVars.SESSION_USERID]); + return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } catch (Exception ex) { + // TODO record the error + throw ex; + } + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeletePR([DataSourceRequest] DataSourceRequest request, MyPartsRequestList pr) { + try { + if (Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]) == false) + throw new Exception("Permission denied"); + + prDMO.DeleteDocument(pr.PRNumber, (int)Session[GlobalVars.SESSION_USERID]); + return Json(new[] { pr }.ToDataSourceResult(request, ModelState)); + } catch (Exception ex) { + return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, ex.Message); + } + } + + public void NotifyDelegation(int delegatedUser, DateTime startDate, DateTime endDate) { + LoginModel delegateFrom = originalUserDMO.GetUserByID((int)Session[GlobalVars.SESSION_USERID]); + LoginModel delegateTo = originalUserDMO.GetUserByID(delegatedUser); + List emailList = new List(); + emailList.Add(delegateFrom.Email); + emailList.Add(delegateTo.Email); + + string emailTemplate = "DelegationOn.txt"; + string userEmail = string.Empty; + string subject = "Mesa Approval Delegation Notification"; + string senderName = "Mesa Approval"; + + foreach (string email in emailList) { + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; + emailparams[0] = delegateFrom.FullName; + emailparams[1] = delegateTo.FullName; + emailparams[2] = startDate.ToString("yyyy-MM-dd"); + emailparams[3] = endDate.ToString("yyyy-MM-dd"); + userEmail = email; + //#if(DEBUG) + // userEmail = GlobalVars.SENDER_EMAIL; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + } + + try { + //EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail }); + } catch { } + } + public bool ProcessOoO() { + + try { + UserAccountDMO userDMO = new UserAccountDMO(); + userDMO.ProcessOoO(); + return true; + } catch { + return false; + } + } + public bool ExpireOoO() { + try { + UserAccountDMO userDMO = new UserAccountDMO(); + userDMO.ExpireOoO(); + return true; + } catch { + return false; + } + } + public bool ApprovalsReminderNotifications() { + try { + //Get list of approvals + List approveList = miscDMO.GetApprovalReminderList(); + + foreach (var item in approveList) { + try { + NotifyApprover(item.AssignedEmail, item.Title, item.IssueID, item.DocType); + } catch (Exception e) { + EventLogDMO.Add(new WinEventLog() { IssueID = item.ApprovalKey, UserID = "SYSTEM", DocumentType = "Approval Reminders", OperationType = "Email", Comments = e.Message }); + } + //We want to update the last notification anyway so we don't continue trying on something that may be failing. + miscDMO.UpdateApprovalNotifyDate(item.ApprovalKey); + } + // List approveList = miscDMO. + return true; + } catch { + return false; + } + } + public void NotifyApprover(string toEmail, string title, int issueId, string docType) { + try { + string emailSentList = ""; + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + //List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); + //string ecnCreatedByEmail = MiscDMO.GetEmail(ecnCreatedById); + + string emailTemplate = "ApprovalReminders.txt"; + string userEmail = string.Empty; + string subject = string.Empty; + string senderName = docType; + + subject = docType + " Approval Reminder: " + title; + + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = docType; + emailparams[1] = title; + emailparams[2] = issueId.ToString(); + userEmail = toEmail; + + //#if(DEBUG) + //string SenderEmail = "MesaFabApproval@infineon.com"; + //userEmail = "jonathan.ouellette@infineon.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, "jonathan.ouellette@infineon.com", subject, emailparams); + //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams); + //emailSentList = ecnCreatedByEmail; + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueId, UserID = @User.Identity.Name, DocumentType = docType, OperationType = "Email", Comments = "Approval reminders" }); + } catch { } + + //EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + //string[] emailparams = new string[4]; + //emailparams[0] = issueID.ToString(); + //emailparams[1] = issueID.ToString(); + //emailparams[2] = GlobalVars.hostURL; + //emailparams[3] =Session[GlobalVars.SESSION_USERNAME].ToString(); + //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + EventLogDMO.Add(new WinEventLog() { IssueID = issueId, UserID = @User.Identity.Name, DocumentType = docType, OperationType = "Email", Comments = "Approval reminders" }); + throw e; + } + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/LotDispositionController.cs b/Fab2ApprovalSystem/Controllers/LotDispositionController.cs index 73c210a..d062ded 100644 --- a/Fab2ApprovalSystem/Controllers/LotDispositionController.cs +++ b/Fab2ApprovalSystem/Controllers/LotDispositionController.cs @@ -1,493 +1,238 @@ using Fab2ApprovalSystem.DMO; -using System; -using System.Collections.Generic; -using System.Collections; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using Kendo.Mvc.Extensions; -using Kendo.Mvc.UI; -using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Misc; -using System.IO; -using System.Reflection; -using System.Configuration; +using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.ViewModels; +using Kendo.Mvc.Extensions; +using Kendo.Mvc.UI; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Configuration; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using System.Web; +using System.Web.Mvc; -namespace Fab2ApprovalSystem.Controllers -{ - [Authorize] - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - [SessionExpireFilter] - public class LotDispositionController : Controller - { - - - - - // GET: /LotDisposition/ - LotDispositionDMO ldDMO = new LotDispositionDMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); - - - // GET: /LotDisposition/Create - public ActionResult Create() - { - //excel.FileName = ""; - //var lot = +namespace Fab2ApprovalSystem.Controllers; + +[Authorize] +[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +[SessionExpireFilter] +public class LotDispositionController : Controller { + + LotDispositionDMO ldDMO; + WorkflowDMO wfDMO = new WorkflowDMO(); + private readonly AppSettings _AppSettings; + + public LotDispositionController(AppSettings appSettings) { + _AppSettings = appSettings; + ldDMO = new LotDispositionDMO(appSettings); + } + + // GET: /LotDisposition/Create + public ActionResult Create() { + //excel.FileName = ""; + //var lot = + LotDisposition lotDispo = new LotDisposition(); + try { + // insert a records to get the issueID + + lotDispo.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + ldDMO.InsertLotDisposition(lotDispo); + return RedirectToAction("Edit", new { issueID = lotDispo.IssueID.ToString() }); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\nCreat Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = lotDispo.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + return View("Error"); + } + } + + public JsonResult AddLot(Lot lot) { + Lot l = lot; + MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); + IssueWithExistingLotsViewModel issueWEL = new IssueWithExistingLotsViewModel(); + try { + + lot.LotStatusOption.LotStatusOptionID = l.LotStatusOptionID; + lot.LotStatusOption.LotStatusOption = l.LotStatusOptionName; + ldDMO.InsertLot(lot, false); + + //if (!mrbDMO.DoesMRBLotExist(lot.LotNumber)) + //{ + //get All the MRBs associated to the Parent lot + //insert the lot into the MRBChildLotNotInMRB table and NOT in the MRB Lot table for each MRB + //ldDMO.InsertChildLot_NotInTheMRB(lot.LotNumber); + + //} + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lot.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Add Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); + } + return Json(l, JsonRequestBehavior.AllowGet); + } + + public JsonResult AddLots(string lotNumbers, int issueID) { + MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); + bool existingLotUpdated; + IssueWithExistingLotsViewModel issueWEL = new IssueWithExistingLotsViewModel(); + try { + if (lotNumbers.Length > 0) { + string[] tempLots = lotNumbers.Split(new char[] { '~' }); + foreach (string lotNumber in tempLots) { + Lot l = new Lot(); + l.LotNumber = lotNumber; + l.IssueID = issueID; + l.LotStatusOption.LotStatusOptionID = (int)GlobalVars.LotStatusOption.NotAvailable; + ldDMO.InsertLot(l, true); + if (l.OpenIssueWithExistingLots != 0) { + issueWEL.LotList += l.LotNumber + "~"; + issueWEL.IssuesList += l.OpenIssueWithExistingLots + "~"; + } + + } + + //foreach (string lotNumber in tempLots) + //{ + //=================================================================== + // ONLY DO THIS PART IF THE LOT DOES NOT EXIST IN THE + //"MRBLot" TABLE AND THE "MRBChildLotNotInMRB" TABLE + //=================================================================== + + //if (!mrbDMO.DoesMRBLotExist(lotNumber)) + //{ + // //get All the MRBs associated to the Parent lot + // //insert the lot into the MRBChildLotNotInMRB table and NOT in the MRB Lot table for each MRB + // ldDMO.InsertChildLot_NotInTheMRB(lotNumber); + + //} + + // } + + } + + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddLots Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); + } + + return Json(issueWEL, JsonRequestBehavior.AllowGet); + } + + // + // GET: /LotDisposition/Edit/5 + public ActionResult Edit(int issueID) { + int isITARCompliant = 1; + try { LotDisposition lotDispo = new LotDisposition(); - try + lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + if (isITARCompliant == 0) // not ITAR Compliant { - // insert a records to get the issueID - - lotDispo.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; - ldDMO.InsertLotDisposition(lotDispo); - return RedirectToAction("Edit", new { issueID = lotDispo.IssueID.ToString() }); - } - - catch(Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); + return View("UnAuthorizedAccess"); + } else { + if (lotDispo.CloseDate != null) { + return RedirectToAction("ReadOnly", new { issueID = issueID }); } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\nCreat Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = lotDispo.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); - return View("Error"); - } - } - - - - /// - /// - /// - /// - /// - public JsonResult AddLot(Lot lot) - { - Lot l = lot; - MRB_DMO mrbDMO = new MRB_DMO(); - IssueWithExistingLotsViewModel issueWEL = new IssueWithExistingLotsViewModel(); - try - { - - lot.LotStatusOption.LotStatusOptionID = l.LotStatusOptionID; - lot.LotStatusOption.LotStatusOption = l.LotStatusOptionName; - ldDMO.InsertLot(lot, false); - - //if (!mrbDMO.DoesMRBLotExist(lot.LotNumber)) - //{ - //get All the MRBs associated to the Parent lot - //insert the lot into the MRBChildLotNotInMRB table and NOT in the MRB Lot table for each MRB - //ldDMO.InsertChildLot_NotInTheMRB(lot.LotNumber); - - //} - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lot.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Add Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - } - return Json(l, JsonRequestBehavior.AllowGet); - } - - /// - /// Add array of lots - /// - /// - /// - //public void AddLots(string lotNumbers, int issueID) - //{ - - // try - // { - // if (lotNumbers.Length > 0) - // { - // string[] tempLots = lotNumbers.Split(new char[] { '~' }); - // foreach (string lotNumber in tempLots) - // { - // Lot l = new Lot(); - // l.LotNumber = lotNumber; - // l.IssueID = issueID; - // l.LotStatusOption.LotStatusOptionID = (int)GlobalVars.LotStatusOption.NotAvailable; - // ldDMO.InsertLot(l, true); - // } - // } - - // } - // catch (Exception e) - // { - // string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - // Functions.WriteEvent(@User.Identity.Name + "\r\n AddLots Disposition\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - // EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); - // throw new Exception(e.Message); - - // } - //} - - - public JsonResult AddLots(string lotNumbers, int issueID) - { - MRB_DMO mrbDMO = new MRB_DMO(); - bool existingLotUpdated; - IssueWithExistingLotsViewModel issueWEL = new IssueWithExistingLotsViewModel(); - try - { - if (lotNumbers.Length > 0) - { - string[] tempLots = lotNumbers.Split(new char[] { '~' }); - foreach (string lotNumber in tempLots) - { - Lot l = new Lot(); - l.LotNumber = lotNumber; - l.IssueID = issueID; - l.LotStatusOption.LotStatusOptionID = (int)GlobalVars.LotStatusOption.NotAvailable; - ldDMO.InsertLot(l, true); - if (l.OpenIssueWithExistingLots != 0) - { - issueWEL.LotList += l.LotNumber + "~"; - issueWEL.IssuesList += l.OpenIssueWithExistingLots + "~"; - } - - - } - - //foreach (string lotNumber in tempLots) - //{ - //=================================================================== - // ONLY DO THIS PART IF THE LOT DOES NOT EXIST IN THE - //"MRBLot" TABLE AND THE "MRBChildLotNotInMRB" TABLE - //=================================================================== - - //if (!mrbDMO.DoesMRBLotExist(lotNumber)) - //{ - // //get All the MRBs associated to the Parent lot - // //insert the lot into the MRBChildLotNotInMRB table and NOT in the MRB Lot table for each MRB - // ldDMO.InsertChildLot_NotInTheMRB(lotNumber); - - //} - - // } - - - } - - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AddLots Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - - } - - return Json(issueWEL, JsonRequestBehavior.AllowGet); - } - - // - // GET: /LotDisposition/Edit/5 - public ActionResult Edit(int issueID) - { - int isITARCompliant = 1; - try - { - LotDisposition lotDispo = new LotDisposition(); - lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int) Session[GlobalVars.SESSION_USERID]); - - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); - } - else - { - if (lotDispo.CloseDate != null) - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - if (lotDispo.CurrentStep == 1) - { - List userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); - //ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == GlobalVars.USER_ID; }); - ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (approver == null) - ViewBag.IsApprover = "false"; - else - ViewBag.IsApprover = "true"; - - if (approver == null && (!(bool)Session[GlobalVars.IS_ADMIN]) && (int)Session[GlobalVars.SESSION_USERID] != lotDispo.OriginatorID ) - { - - //return RedirectToAction("ReadOnly", lotDispo); - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - else - { - if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN]) - || (int)Session[GlobalVars.SESSION_USERID] == lotDispo.OriginatorID) - { - lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - if (lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy == (int)Session[GlobalVars.SESSION_USERID]) - { - PopulateLotStatusOptions(); - ViewBag.OriginatorList = ldDMO.GetUserList(); - ViewBag.deps = ldDMO.GetDepartments(); - ViewBag.ResponsibilityList = ldDMO.GetResponsibilityList(); - ViewBag.ResponsibilityIssueList = ldDMO.GetResponsibilityIssueList(lotDispo.ResponsibilityID); - - return View(lotDispo); - } - else - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - } - else - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - } - } - else if (lotDispo.CurrentStep > 1) - { - - List userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); - //ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == GlobalVars.USER_ID; }); - ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (approver == null) - { - ViewBag.IsApprover = "false"; - - } - else - { - ViewBag.IsApprover = "true"; - - } - - if (approver == null && (!(bool)Session[GlobalVars.IS_ADMIN]) && (int)Session[GlobalVars.SESSION_USERID] != lotDispo.OriginatorID) - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - else - { - - //// Check the record Lock indicator - //if ((lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ViewBag.IsApprover == "false")) - //{ - // return RedirectToAction("ReadOnly", new { issueID = issueID }); - //} - //else - // return RedirectToAction("EditStep", new { issueID = issueID }); - - - if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN]) - || (int)Session[GlobalVars.SESSION_USERID] == lotDispo.OriginatorID) - { - return RedirectToAction("EditStep", new { issueID = issueID }); - - } - else - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - - } - - } + if (lotDispo.CurrentStep == 1) { + List userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); + //ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == GlobalVars.USER_ID; }); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (approver == null) + ViewBag.IsApprover = "false"; else - { - // TODO - // Check the recordlock indicator - if ((lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ViewBag.IsApprover == "false")) - { + ViewBag.IsApprover = "true"; + + if (approver == null && (!(bool)Session[GlobalVars.IS_ADMIN]) && (int)Session[GlobalVars.SESSION_USERID] != lotDispo.OriginatorID) { + //return RedirectToAction("ReadOnly", lotDispo); + return RedirectToAction("ReadOnly", new { issueID = issueID }); + } else { + if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN]) + || (int)Session[GlobalVars.SESSION_USERID] == lotDispo.OriginatorID) { + lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + if (lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy == (int)Session[GlobalVars.SESSION_USERID]) { + PopulateLotStatusOptions(); + ViewBag.OriginatorList = ldDMO.GetUserList(); + ViewBag.deps = ldDMO.GetDepartments(); + ViewBag.ResponsibilityList = ldDMO.GetResponsibilityList(); + ViewBag.ResponsibilityIssueList = ldDMO.GetResponsibilityIssueList(lotDispo.ResponsibilityID); + + return View(lotDispo); + } else { + return RedirectToAction("ReadOnly", new { issueID = issueID }); + } + } else { return RedirectToAction("ReadOnly", new { issueID = issueID }); } - else - { - lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - PopulateLotStatusOptions(); - ViewBag.OriginatorList = ldDMO.GetUserList(); - ViewBag.deps = ldDMO.GetDepartments(); - ViewBag.ResponsibilityList = ldDMO.GetResponsibilityList(); - ViewBag.ResponsibilityIssueList = ldDMO.GetResponsibilityIssueList(lotDispo.ResponsibilityID); - - return View(lotDispo); - } } - } - } + } else if (lotDispo.CurrentStep > 1) { + List userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); + //ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == GlobalVars.USER_ID; }); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (approver == null) { + ViewBag.IsApprover = "false"; - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\nEdit Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); - return View("Error"); - } - - } + } else { + ViewBag.IsApprover = "true"; + } - // - // POST: /LotDisposition/Edit/5 - /// - /// - /// - /// - [HttpPost] - public void Edit(LotDisposition lotDispo) - { - try - { - ldDMO.UpdateLotDisposition(lotDispo); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lotDispo.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n UpdatEdit Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = lotDispo.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - } + if (approver == null && (!(bool)Session[GlobalVars.IS_ADMIN]) && (int)Session[GlobalVars.SESSION_USERID] != lotDispo.OriginatorID) { + return RedirectToAction("ReadOnly", new { issueID = issueID }); + } else { - } + //// Check the record Lock indicator + //if ((lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ViewBag.IsApprover == "false")) + //{ + // return RedirectToAction("ReadOnly", new { issueID = issueID }); + //} + //else + // return RedirectToAction("EditStep", new { issueID = issueID }); - /// - /// - /// - /// - /// - public ActionResult ReadOnly(int issueID) - { - int isITARCompliant = 1; - try - { - LotDisposition lotDispo = new LotDisposition(); - lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN]) + || (int)Session[GlobalVars.SESSION_USERID] == lotDispo.OriginatorID) { + return RedirectToAction("EditStep", new { issueID = issueID }); - PopulateLotStatusOptions(); - ViewBag.OriginatorList = ldDMO.GetUserList(); - ViewBag.deps = ldDMO.GetDepartments(); - ViewBag.ResponsibilityList = ldDMO.GetResponsibilityList(); - ViewBag.ResponsibilityIssueList = ldDMO.GetResponsibilityIssueList(lotDispo.ResponsibilityID); + } else { + return RedirectToAction("ReadOnly", new { issueID = issueID }); + } + } - return View(lotDispo); - } - - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReadOnly Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - - } - } - - - /// - /// - /// - /// - /// - public ActionResult EditStep(int issueID) - { - int isITARCompliant = 1; - try - { - - - - LotDisposition lotDispo = new LotDisposition(); - lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - List userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); - ApproversListViewModel appUser = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (appUser == null) - ViewBag.IsApprover = "false"; - else - ViewBag.IsApprover = "true"; - - - // Check the recordlock indicator - - //if ((lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID])) - //{ - // return RedirectToAction("ReadOnly", new { issueID = issueID }); - //} - //else - //{ - // PopulateLotStatusOptions(); - // ViewBag.OriginatorList = ldDMO.GetUserList(); - // ViewBag.deps = ldDMO.GetDepartments(); - // ViewBag.ResponsibilityList = ldDMO.GetResponsibilityList(); - // ViewBag.ResponsibilityIssueList = ldDMO.GetResponsibilityIssueList(lotDispo.ResponsibilityID); - //} - - - if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN])) - { - lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - if (lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy == (int)Session[GlobalVars.SESSION_USERID]) - { + } else { + // TODO + // Check the recordlock indicator + if ((lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ViewBag.IsApprover == "false")) { + return RedirectToAction("ReadOnly", new { issueID = issueID }); + } else { + lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); PopulateLotStatusOptions(); ViewBag.OriginatorList = ldDMO.GetUserList(); ViewBag.deps = ldDMO.GetDepartments(); @@ -496,1174 +241,809 @@ namespace Fab2ApprovalSystem.Controllers return View(lotDispo); } - else - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - } - else - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - - - - //return View(lotDispo); - } - - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n EditStep Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - - } - - - } - - - - - - // - // GET: /LotDisposition/Delete/5 - public ActionResult Delete(int id) - { - return View(); - } - - - - /// - /// - /// - /// - /// - public JsonResult GetResponsibilityIssue(int responsibilityID) - { - List respIssue = ldDMO.GetResponsibilityIssueList(responsibilityID); - - var data = respIssue.Select(s => new SelectListItem{ Value = s.ResponsibilityIssueID.ToString(), Text = s.Issue}); - return Json(data, JsonRequestBehavior.AllowGet); - - } - - - /// - /// - /// - /// - /// - public JsonResult GetDepartments([DataSourceRequest] DataSourceRequest request) - { - - var departments = ldDMO.GetDepartments(); - return Json(departments, JsonRequestBehavior.AllowGet); - - } - - - public void PopulateLotStatusOptions() - { - var lotStatusOptions = ldDMO.GetLotStatusOptions(); - ViewData["LotStatusOptions"] = lotStatusOptions; - //ViewData["DefaultLotStatusOptions"] = lotStatusOptions.First(); - } - - - /// - /// - /// - /// - /// - /// - public ActionResult EditingCustom_Read([DataSourceRequest] DataSourceRequest request, int issueID) - { - return Json(ldDMO.GetLotDispositionLots(issueID).ToDataSourceResult(request)); - } - - - /// - /// Updates the lot tables - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult EditingCustom_Update([DataSourceRequest] DataSourceRequest request, Lot lot) - { - - if (lot != null && ModelState.IsValid) - { - ldDMO.UpdateLotDispoLot(lot); - } - - lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); - } - - - /// - /// Deletes record from the lot table - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult EditingCustom_Destroy([DataSourceRequest] DataSourceRequest request, Lot lot) - { - try - { - if (lot != null && ModelState.IsValid) - { - ldDMO.DeleteLotDispoLot(lot.LotID); - } } - catch (Exception ex) - { - // TODO - throw new Exception(ex.Message); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - - - return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); + string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\nEdit Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + return View("Error"); } + } - - // REGION ATTACHMENT - /// - /// - /// - /// - /// - /// - public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int issueID) - { - return Json(ldDMO.GetLotDispoAttachments(issueID).ToDataSourceResult(request)); - } + // + // POST: /LotDisposition/Edit/5 - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult Attachment_Destroy([DataSourceRequest] DataSourceRequest request, Attachment attachment) - { - try - { - if (attachment != null && ModelState.IsValid) - { - ldDMO.DeleteLotDispoAttachment(attachment.AttachmentID); - - } + [HttpPost] + public void Edit(LotDisposition lotDispo) { + try { + ldDMO.UpdateLotDisposition(lotDispo); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - catch (Exception e) - { - //string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - //Functions.WriteEvent(@User.Identity.Name + "\r\n AttachmentID Disposition\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - //EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); - //throw new Exception(e.Message); + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lotDispo.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdatEdit Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = lotDispo.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); + } + } + public ActionResult ReadOnly(int issueID) { + int isITARCompliant = 1; + try { + LotDisposition lotDispo = new LotDisposition(); + lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + PopulateLotStatusOptions(); + ViewBag.OriginatorList = ldDMO.GetUserList(); + ViewBag.deps = ldDMO.GetDepartments(); + ViewBag.ResponsibilityList = ldDMO.GetResponsibilityList(); + ViewBag.ResponsibilityIssueList = ldDMO.GetResponsibilityIssueList(lotDispo.ResponsibilityID); + + return View(lotDispo); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - - - return Json(new[] { attachment }.ToDataSourceResult(request, ModelState)); + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReadOnly Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); } + } - - //[AcceptVerbs(HttpVerbs.Post)] - /// - /// - /// - /// - /// - [HttpPost] - public void DeleteAttachment(int attachmentID, string fileName) - { - try - { - if (ModelState.IsValid) - { - ldDMO.DeleteLotDispoAttachment(attachmentID); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + "LotDisposition", fileName); + public ActionResult EditStep(int issueID) { + int isITARCompliant = 1; + try { - FileInfo f = new FileInfo(physicalPath); - - if (f.Exists) - f.Delete(); - - } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AttachmentID Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString }); - throw new Exception(e.Message); - - } - } - - - - /// - /// - /// - /// - /// - public JsonResult GetLotDispoAttachments(int issueID) - { - - var model = ldDMO.GetLotDispoAttachments(issueID); - return Json(model, JsonRequestBehavior.AllowGet); - } - - - /// - /// - /// - /// - /// - public ActionResult AttachSave(IEnumerable files, int issueID ) - { - // The Name of the Upload component is "files" - if (files != null) - { - foreach (var file in files) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - var fileName = Path.GetFileName(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + "LotDisposition", fileName); - - file.SaveAs(physicalPath); - Attachment attach = new Attachment() - { - IssueID = issueID, - FileName = fileName, - UserID = (int)Session[GlobalVars.SESSION_USERID], - }; - ldDMO.InsertLotDispositionAttachment(attach); - } - } - - //var model = ldDMO.GetLotDispoAttachments(issueID); - - - return Content(""); - } - - - /// - /// - /// - /// - /// - /// - public JsonResult SearchLots(string searchText, string searchBy) - { - List lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList(); - - //IEnumerable lotlist = MiscDMO.SearchLots(searchText, searchBy); - - return Json(lotlist, JsonRequestBehavior.AllowGet); - } - - - /// - /// - /// - /// - public void DeleteAllLots(int issueID) - { - // trap the error on then client side - ldDMO.DeleteAllLotDispoLot(issueID); - } - - /// - /// - /// - /// - /// - /// - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - public ActionResult LotStatusDetail(int issueID, string lotNumber, bool readonlyView, string lotLocation = "") - { - ViewBag.LotLocation = lotLocation; - var model = new ScrapLot(); - var data = ldDMO.GetLotStausDetail(issueID, lotNumber); - if (data != null) - model = data; - - model.IssueID = issueID; - model.LotNo = lotNumber; - - if (lotLocation.Equals("QDB", StringComparison.OrdinalIgnoreCase) || - lotLocation.Equals("EDB", StringComparison.OrdinalIgnoreCase)) - { - model.WaferCount = 50; - } - - if (readonlyView) - return PartialView("_ScrapReleaseReadOnly", model); + LotDisposition lotDispo = new LotDisposition(); + lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + List userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); + ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (appUser == null) + ViewBag.IsApprover = "false"; else - return PartialView("_ScrapRelease", model); + ViewBag.IsApprover = "true"; + + // Check the recordlock indicator + + //if ((lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID])) + //{ + // return RedirectToAction("ReadOnly", new { issueID = issueID }); + //} + //else + //{ + // PopulateLotStatusOptions(); + // ViewBag.OriginatorList = ldDMO.GetUserList(); + // ViewBag.deps = ldDMO.GetDepartments(); + // ViewBag.ResponsibilityList = ldDMO.GetResponsibilityList(); + // ViewBag.ResponsibilityIssueList = ldDMO.GetResponsibilityIssueList(lotDispo.ResponsibilityID); + //} + + if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN])) { + lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + if (lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy == (int)Session[GlobalVars.SESSION_USERID]) { + PopulateLotStatusOptions(); + ViewBag.OriginatorList = ldDMO.GetUserList(); + ViewBag.deps = ldDMO.GetDepartments(); + ViewBag.ResponsibilityList = ldDMO.GetResponsibilityList(); + ViewBag.ResponsibilityIssueList = ldDMO.GetResponsibilityIssueList(lotDispo.ResponsibilityID); + + return View(lotDispo); + } else { + return RedirectToAction("ReadOnly", new { issueID = issueID }); + } + } else { + return RedirectToAction("ReadOnly", new { issueID = issueID }); + } + + //return View(lotDispo); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n EditStep Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); + } + } + + // + // GET: /LotDisposition/Delete/5 + public ActionResult Delete(int id) { + return View(); + } + + public JsonResult GetResponsibilityIssue(int responsibilityID) { + List respIssue = ldDMO.GetResponsibilityIssueList(responsibilityID); + + var data = respIssue.Select(s => new SelectListItem { Value = s.ResponsibilityIssueID.ToString(), Text = s.Issue }); + return Json(data, JsonRequestBehavior.AllowGet); + } + + public JsonResult GetDepartments([DataSourceRequest] DataSourceRequest request) { + var departments = ldDMO.GetDepartments(); + return Json(departments, JsonRequestBehavior.AllowGet); + } + + public void PopulateLotStatusOptions() { + var lotStatusOptions = ldDMO.GetLotStatusOptions(); + ViewData["LotStatusOptions"] = lotStatusOptions; + //ViewData["DefaultLotStatusOptions"] = lotStatusOptions.First(); + } + + public ActionResult EditingCustom_Read([DataSourceRequest] DataSourceRequest request, int issueID) { + return Json(ldDMO.GetLotDispositionLots(issueID).ToDataSourceResult(request)); + } + + /// + /// Updates the lot tables + /// + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult EditingCustom_Update([DataSourceRequest] DataSourceRequest request, Lot lot) { + + if (lot != null && ModelState.IsValid) { + ldDMO.UpdateLotDispoLot(lot); } + lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); + } - - /// - /// - /// - /// - public void UpdateLotScrapReleaseStatus(ScrapLot sl) - { - int scrapCount = 0; - int releaseCount = 0; - int splitOfHoldCount = 0; - int closeToQDBCount = 0; - try - { - foreach (PropertyInfo pi in sl.GetType().GetProperties()) - { - if (pi.Name.ToLower().StartsWith("lot") && pi.Name.ToLower().EndsWith("state")) - { - byte currentValue = (byte)pi.GetValue(sl, null); - if (currentValue == (int)GlobalVars.LotStatusOption.Release || currentValue == (int)GlobalVars.LotStatusOption.CloseToQDB) - { - releaseCount++; - //required to update the lot status option - if (currentValue == (int)GlobalVars.LotStatusOption.CloseToQDB) - closeToQDBCount++; - } - else if (currentValue == (int)GlobalVars.LotStatusOption.Scrap) - scrapCount++; - else if (currentValue == (int)GlobalVars.LotStatusOption.SplitOffHold) - splitOfHoldCount++; - } - } + /// + /// Deletes record from the lot table + /// + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult EditingCustom_Destroy([DataSourceRequest] DataSourceRequest request, Lot lot) { + try { + if (lot != null && ModelState.IsValid) { + ldDMO.DeleteLotDispoLot(lot.LotID); - sl.ScrapCount = scrapCount; - sl.ReleaseCount = releaseCount; - sl.SplitOfHoldCount = splitOfHoldCount; - sl.CloseToQDBCount = closeToQDBCount; - - ldDMO.UpdateLotScrapReleaseStatus(sl); - ldDMO.UpdateLotStatus(sl); } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + sl.IssueID.ToString() + " LotNo:" + sl.LotNo.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Scrap Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateLotScrapReleaseStatus - " + exceptionString }); - throw new Exception(e.Message); + } catch (Exception ex) { + // TODO + throw new Exception(ex.Message); + } + return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); + } + + // REGION ATTACHMENT + + public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int issueID) { + return Json(ldDMO.GetLotDispoAttachments(issueID).ToDataSourceResult(request)); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult Attachment_Destroy([DataSourceRequest] DataSourceRequest request, Attachment attachment) { + try { + if (attachment != null && ModelState.IsValid) { + ldDMO.DeleteLotDispoAttachment(attachment.AttachmentID); + + } + } catch (Exception e) { + //string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + //Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AttachmentID Disposition\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + //EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); + //throw new Exception(e.Message); + } + + return Json(new[] { attachment }.ToDataSourceResult(request, ModelState)); + } + + //[AcceptVerbs(HttpVerbs.Post)] + + [HttpPost] + public void DeleteAttachment(int attachmentID, string fileName) { + try { + if (ModelState.IsValid) { + ldDMO.DeleteLotDispoAttachment(attachmentID); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + "LotDisposition", fileName); + + FileInfo f = new FileInfo(physicalPath); + + if (f.Exists) + f.Delete(); + + } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AttachmentID Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString }); + throw new Exception(e.Message); + } + } + + public JsonResult GetLotDispoAttachments(int issueID) { + var model = ldDMO.GetLotDispoAttachments(issueID); + return Json(model, JsonRequestBehavior.AllowGet); + } + + public ActionResult AttachSave(IEnumerable files, int issueID) { + // The Name of the Upload component is "files" + if (files != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in files) { + ldDMO.AttachSave(issueID, userId, file.FileName, file.InputStream); } } + //var model = ldDMO.GetLotDispoAttachments(issueID); - /// - /// Update the all the lots to "RELEASE" Status for a given Lot disposition document - /// - /// - public void ReleaseAll(int issueID) - { + return Content(""); + } - ScrapLot sl = new ScrapLot(); - try - { - sl.IssueID = issueID; - foreach (PropertyInfo pi in sl.GetType().GetProperties()) - { - if (pi.Name.ToLower().StartsWith("lot") && pi.Name.ToLower().EndsWith("state")) - { - //byte currentValue = (byte)pi.GetValue(sl, null); - //if (currentValue != 2) - pi.SetValue(sl, (byte)1, null); - } - } + public JsonResult SearchLots(string searchText, string searchBy) { + List lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList(); - ldDMO.UpdateLotStatusAll(sl, (int)GlobalVars.LotStatusOption.Release); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + sl.IssueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Release All Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReleaseAll - " + exceptionString }); - throw new Exception(e.Message); + //IEnumerable lotlist = MiscDMO.SearchLots(searchText, searchBy); - } + return Json(lotlist, JsonRequestBehavior.AllowGet); + } + + public void DeleteAllLots(int issueID) { + // trap the error on then client side + ldDMO.DeleteAllLotDispoLot(issueID); + } + + [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] + public ActionResult LotStatusDetail(int issueID, string lotNumber, bool readonlyView, string lotLocation = "") { + ViewBag.LotLocation = lotLocation; + var model = new ScrapLot(); + var data = ldDMO.GetLotStausDetail(issueID, lotNumber); + if (data != null) + model = data; + + model.IssueID = issueID; + model.LotNo = lotNumber; + + if (lotLocation.Equals("QDB", StringComparison.OrdinalIgnoreCase) || + lotLocation.Equals("EDB", StringComparison.OrdinalIgnoreCase)) { + model.WaferCount = 50; } - /// - /// Update the all the lots to "SCRAP" Status for a given Lot disposition document - /// - /// - public void ScrapAll(int issueID) - { - ScrapLot sl = new ScrapLot(); - try - { - sl.IssueID = issueID; - foreach (PropertyInfo pi in sl.GetType().GetProperties()) - { - if (pi.Name.ToLower().StartsWith("lot") && pi.Name.ToLower().EndsWith("state")) - { - //byte currentValue = (byte)pi.GetValue(sl, null); - //if (currentValue != 2) - pi.SetValue(sl, (byte)2, null); - } - } + if (readonlyView) + return PartialView("_ScrapReleaseReadOnly", model); + else + return PartialView("_ScrapRelease", model); + } - ldDMO.UpdateLotStatusAll(sl, (int)GlobalVars.LotStatusOption.Scrap); + public void UpdateLotScrapReleaseStatus(ScrapLot sl) { + int scrapCount = 0; + int releaseCount = 0; + int splitOfHoldCount = 0; + int closeToQDBCount = 0; + try { + foreach (PropertyInfo pi in sl.GetType().GetProperties()) { + if (pi.Name.ToLower().StartsWith("lot") && pi.Name.ToLower().EndsWith("state")) { + byte currentValue = (byte)pi.GetValue(sl, null); + if (currentValue == (int)GlobalVars.LotStatusOption.Release || currentValue == (int)GlobalVars.LotStatusOption.CloseToQDB) { + releaseCount++; + //required to update the lot status option + if (currentValue == (int)GlobalVars.LotStatusOption.CloseToQDB) + closeToQDBCount++; + } else if (currentValue == (int)GlobalVars.LotStatusOption.Scrap) + scrapCount++; + else if (currentValue == (int)GlobalVars.LotStatusOption.SplitOffHold) + splitOfHoldCount++; + } } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); + + sl.ScrapCount = scrapCount; + sl.ReleaseCount = releaseCount; + sl.SplitOfHoldCount = splitOfHoldCount; + sl.CloseToQDBCount = closeToQDBCount; + + ldDMO.UpdateLotScrapReleaseStatus(sl); + ldDMO.UpdateLotStatus(sl); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + sl.IssueID.ToString() + " LotNo:" + sl.LotNo.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Scrap Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateLotScrapReleaseStatus - " + exceptionString }); + throw new Exception(e.Message); + } + } + + /// + /// Update the all the lots to "RELEASE" Status for a given Lot disposition document + /// + public void ReleaseAll(int issueID) { + ScrapLot sl = new ScrapLot(); + try { + sl.IssueID = issueID; + foreach (PropertyInfo pi in sl.GetType().GetProperties()) { + if (pi.Name.ToLower().StartsWith("lot") && pi.Name.ToLower().EndsWith("state")) { + //byte currentValue = (byte)pi.GetValue(sl, null); + //if (currentValue != 2) + pi.SetValue(sl, (byte)1, null); } - catch - { - detailedException = e.Message; + } + + ldDMO.UpdateLotStatusAll(sl, (int)GlobalVars.LotStatusOption.Release); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + sl.IssueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Release All Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReleaseAll - " + exceptionString }); + throw new Exception(e.Message); + } + } + + /// + /// Update the all the lots to "SCRAP" Status for a given Lot disposition document + /// + public void ScrapAll(int issueID) { + ScrapLot sl = new ScrapLot(); + try { + sl.IssueID = issueID; + foreach (PropertyInfo pi in sl.GetType().GetProperties()) { + if (pi.Name.ToLower().StartsWith("lot") && pi.Name.ToLower().EndsWith("state")) { + //byte currentValue = (byte)pi.GetValue(sl, null); + //if (currentValue != 2) + pi.SetValue(sl, (byte)2, null); } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + sl.IssueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Scrap All Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ScrapAll - " + exceptionString }); - throw new Exception(e.Message); + } + + ldDMO.UpdateLotStatusAll(sl, (int)GlobalVars.LotStatusOption.Scrap); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + sl.IssueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Scrap All Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ScrapAll - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public JsonResult GetLotDispositionLotSummary(int issueID) { + return Json(ldDMO.GetLotDispositionLotSummary(issueID), JsonRequestBehavior.AllowGet); + } + + /// + public ActionResult SubmitDocument(int issueID, bool peRequired, bool mrbRequired) { + try { + int appoverCount = ldDMO.SubmitDocument(issueID, peRequired, mrbRequired, (int)Session[GlobalVars.SESSION_USERID]); + if (appoverCount > 0) + NotifyApprovers(issueID, (byte)GlobalVars.WorkFLowStepNumber.Step1); + else { + // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval + Approve(issueID, (byte)GlobalVars.WorkFLowStepNumber.Step1, ""); // this is the Submit Level Approval } - - } - - - /// - /// - /// - /// - /// - public JsonResult GetLotDispositionLotSummary(int issueID) - { - return Json(ldDMO.GetLotDispositionLotSummary(issueID), JsonRequestBehavior.AllowGet); - } - - - /// - /// - /// - /// - /// - /// - public ActionResult SubmitDocument(int issueID, bool peRequired, bool mrbRequired) - { - try - { - int appoverCount = ldDMO.SubmitDocument(issueID, peRequired, mrbRequired, (int)Session[GlobalVars.SESSION_USERID]); - if (appoverCount > 0) - NotifyApprovers(issueID, (byte)GlobalVars.WorkFLowStepNumber.Step1); - else - { - // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval - Approve(issueID, (byte)GlobalVars.WorkFLowStepNumber.Step1, ""); // this is the Submit Level Approval - - } - - - if (Request.IsAjaxRequest()) - { - return Content("Redirect"); - } - else - return Content("Invalid"); + if (Request.IsAjaxRequest()) { + return Content("Redirect"); + } else + return Content("Invalid"); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); - - Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; - return Json(new { result = "Error", issueID = issueID, detail = e.Message }, JsonRequestBehavior.AllowGet); - } + Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; + return Json(new { result = "Error", issueID = issueID, detail = e.Message }, JsonRequestBehavior.AllowGet); } + } - - /// - /// - /// - /// - /// - /// - public void Approve(int issueID, byte currentStep, string comments) - { - int isITARCompliant = 1; - try - { - bool lastStep = false; - LotDisposition ltDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + public void Approve(int issueID, byte currentStep, string comments) { + int isITARCompliant = 1; + try { + bool lastStep = false; + LotDisposition ltDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - bool lastApprover = wfDMO.Approve(issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.LotDisposition, ltDispo.WorkFlowNumber); + bool lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.LotDisposition, ltDispo.WorkFlowNumber); - while (lastApprover && !lastStep) - { - currentStep++; - lastApprover = wfDMO.Approve(issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID],(int)GlobalVars.DocumentType.LotDisposition, ltDispo.WorkFlowNumber); - NotifyApprovers(issueID, currentStep); - } + while (lastApprover && !lastStep) { + currentStep++; + lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.LotDisposition, ltDispo.WorkFlowNumber); + NotifyApprovers(issueID, currentStep); } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw new Exception(e.Message); - } - - } - - /// - /// - /// - /// - /// - /// - public void Reject(int issueID, byte currentStep, string comments) - { - try - { - if (Session[GlobalVars.SESSION_USERID] != null) - { - wfDMO.Reject(issueID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int) GlobalVars.DocumentType.LotDisposition); - NotifyRejectionToOrginator(issueID); - } - else - { - - Response.Redirect("~/Account/Login"); - } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Reject\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Reject - " + exceptionString }); - throw new Exception(e.Message); - - } - + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw new Exception(e.Message); } + } - /// - /// Get a list of Approvers and the status - /// - /// - /// - /// - /// - public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) - { - //return Json(ldDMO.GetApproversList(issueID, step).ToDataSourceResult(request)); - return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.LotDisposition).ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - /// - public JsonResult GetAllUsersList() - { - //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep); - //return Json(userList, JsonRequestBehavior.AllowGet); - - UserAccountDMO userDMO = new UserAccountDMO(); - IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); - - } - - /// - /// - /// - /// - /// - /// - public void ReAssignApproval(int issueID, int userIDs, byte step) - { - var email = ""; - try - { - email = wfDMO.ReAssignApproval(issueID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, (int)GlobalVars.DocumentType.LotDisposition); + public void Reject(int issueID, byte currentStep, string comments) { + try { + if (Session[GlobalVars.SESSION_USERID] != null) { + wfDMO.Reject(issueID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.LotDisposition); + NotifyRejectionToOrginator(issueID); + } else { + Response.Redirect("~/Account/Login"); } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); - throw new Exception(e.Message); - - } - - - string emailTemplate = "LotDispositionReAssigned.txt"; - string userEmail = string.Empty; - string subject = "Lot Disposition Re-Assignment"; - string senderName = "LotDisposition"; - - subject = "Lot Disposition Re-Assignment" + " - Email would be sent to " + email; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[3]; - emailparams[0] = issueID.ToString(); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - userEmail = email; -//#if(DEBUG) -// userEmail = "rkotian1@irf.com"; -//#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - catch { } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Reject\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Reject - " + exceptionString }); + throw new Exception(e.Message); + } + } + /// + /// Get a list of Approvers and the status + /// + public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) { + //return Json(ldDMO.GetApproversList(issueID, step).ToDataSourceResult(request)); + return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.LotDisposition).ToDataSourceResult(request)); + } + + public JsonResult GetAllUsersList() { + //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep); + //return Json(userList, JsonRequestBehavior.AllowGet); + + UserAccountDMO userDMO = new UserAccountDMO(); + IEnumerable userlist = userDMO.GetAllUsers(); + return Json(userlist, JsonRequestBehavior.AllowGet); + } + + public void ReAssignApproval(int issueID, int userIDs, byte step) { + var email = ""; + try { + email = wfDMO.ReAssignApproval(issueID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, (int)GlobalVars.DocumentType.LotDisposition); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + throw new Exception(e.Message); } - /// - /// - /// - /// - /// - /// - /// - public void ReAssignApproverByAdmin(int issueID, int reAssignApproverFrom, int reAssignApproverTo, byte step) - { - var email = ""; - try - { - email = wfDMO.ReAssignApproval(issueID, reAssignApproverFrom, reAssignApproverTo, step, (int)GlobalVars.DocumentType.LotDisposition); + string emailTemplate = "LotDispositionReAssigned.txt"; + string userEmail = string.Empty; + string subject = "Lot Disposition Re-Assignment"; + string senderName = "LotDisposition"; + subject = "Lot Disposition Re-Assignment" + " - Email would be sent to " + email; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[3]; + emailparams[0] = issueID.ToString(); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + } catch { } + } + + public void ReAssignApproverByAdmin(int issueID, int reAssignApproverFrom, int reAssignApproverTo, byte step) { + var email = ""; + try { + email = wfDMO.ReAssignApproval(issueID, reAssignApproverFrom, reAssignApproverTo, step, (int)GlobalVars.DocumentType.LotDisposition); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); - throw new Exception(e.Message); + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + throw new Exception(e.Message); + } + + string emailTemplate = "LotDispositionReAssigned.txt"; + string userEmail = string.Empty; + string subject = "Lot Disposition Re-Assignment"; + string senderName = "LotDisposition"; + + subject = "Lot Disposition Re-Assignment" + " - Email would be sent to " + email; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[3]; + emailparams[0] = issueID.ToString(); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + } catch { } + } + + #region Additional Approvers + + public JsonResult GetUserListForAdditionalAppprrovers() { + UserAccountDMO userDMO = new UserAccountDMO(); + IEnumerable userlist = userDMO.GetAllUsers(); + return Json(userlist, JsonRequestBehavior.AllowGet); + } + + public void AddAdditionalApproval(int issueID, byte step, string userIDs) { + string emailSentList = ""; + var emailArray = ""; + try { + emailArray = wfDMO.AddAdditionalApproval(issueID, userIDs, step, (int)GlobalVars.DocumentType.LotDisposition); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw new Exception(e.Message); + } + + string emailTemplate = "LotDispositionAssigned.txt"; + string userEmail = string.Empty; + string subject = "Lot Disposition Assignment"; + string senderName = "LotDisposition"; + + string[] emailIst = emailArray.Split(new char[] { '~' }); + foreach (string email in emailIst) { + if (email.Length > 0) { + //subject = "Lot Disposition Assignment" + " - Email would be sent to " + email; + subject = "Lot Disposition Assignment"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[3]; + emailparams[0] = issueID.ToString(); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + emailSentList += email + ","; } - - string emailTemplate = "LotDispositionReAssigned.txt"; - string userEmail = string.Empty; - string subject = "Lot Disposition Re-Assignment"; - string senderName = "LotDisposition"; - - subject = "Lot Disposition Re-Assignment" + " - Email would be sent to " + email; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[3]; - emailparams[0] = issueID.ToString(); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - userEmail = email; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "ReAssign Approver: " + email }); - } - catch { } - } + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); + } catch { } + } - #region Additional Approvers + #endregion - /// - /// - /// - /// - public JsonResult GetUserListForAdditionalAppprrovers() - { - UserAccountDMO userDMO = new UserAccountDMO(); - IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); - - } - - public void AddAdditionalApproval(int issueID, byte step, string userIDs) - { + public void NotifyApprovers(int issueID, byte currentStep) { + try { string emailSentList = ""; - var emailArray = ""; - try - { - emailArray = wfDMO.AddAdditionalApproval(issueID, userIDs, step, (int) GlobalVars.DocumentType.LotDisposition); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw new Exception(e.Message); - } + + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + List emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.LotDisposition).Distinct().ToList(); string emailTemplate = "LotDispositionAssigned.txt"; string userEmail = string.Empty; string subject = "Lot Disposition Assignment"; string senderName = "LotDisposition"; - string[] emailIst = emailArray.Split(new char[] { '~' }); - foreach (string email in emailIst) - { - if (email.Length > 0) - { - //subject = "Lot Disposition Assignment" + " - Email would be sent to " + email; - subject = "Lot Disposition Assignment"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[3]; - emailparams[0] = issueID.ToString(); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - userEmail =email; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - emailSentList += email + ","; - - } - - } - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); - } - catch { } - } - - #endregion - - - /// - /// - /// - /// - /// - public void NotifyApprovers(int issueID, byte currentStep) - { - try - { - string emailSentList = ""; - - //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); - List emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.LotDisposition).Distinct().ToList(); - - string emailTemplate = "LotDispositionAssigned.txt"; - string userEmail = string.Empty; - string subject = "Lot Disposition Assignment"; - string senderName = "LotDisposition"; - - foreach (string email in emailIst) - { - subject = "Lot Disposition Assignment"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[3]; - emailparams[0] = issueID.ToString(); - emailparams[1] = issueID.ToString(); - emailparams[2] = GlobalVars.hostURL; - userEmail = email; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - emailSentList += email + ","; - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); - } - catch { } - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Lot Dispo - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; - - - } - //EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - //string[] emailparams = new string[4]; - //emailparams[0] = issueID.ToString(); - //emailparams[1] = issueID.ToString(); - //emailparams[2] = GlobalVars.hostURL; - //emailparams[3] =Session[GlobalVars.SESSION_USERNAME].ToString(); - //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams); - - } - - - /// - /// - /// - /// - public void NotifyRejectionToOrginator(int issueID) - { - - List emailIst = ldDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList(); - - string emailTemplate = "LotDispositionReject.txt"; - string userEmail = string.Empty; - string subject = "Lot Disposition Rejection"; - string senderName = "LotDisposition"; - - foreach (string email in emailIst) - { - subject = "Lot Disposition Rejection"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; + foreach (string email in emailIst) { + subject = "Lot Disposition Assignment"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[3]; emailparams[0] = issueID.ToString(); emailparams[1] = issueID.ToString(); emailparams[2] = GlobalVars.hostURL; - emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString(); userEmail = email; //#if(DEBUG) // userEmail = "rkotian1@irf.com"; //#endif - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + emailSentList += email + ","; } - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Rejection: " + userEmail }); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + } catch { } + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; } - catch { } - - } - - - /// - /// - /// - /// - /// - public void UpdateReasonForDisposition(int issueID, string reasonForDisposition) - { - try - { - ldDMO.UpdateReasonForDisposition(issueID, reasonForDisposition); - } - - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim(); - Functions.WriteEvent(@User.Identity.Name + "\r\n UpdateReasonForDisposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateReasonForDisposition - " + exceptionString }); - throw new Exception(e.Message); - - } - - } - - - /// - /// - /// - /// - /// - /// - public ActionResult GetComments([DataSourceRequest] DataSourceRequest request, int issueID) - { - //return Json(ldDMO.GetApproversList(issueID, step).ToDataSourceResult(request)); - return Json(ldDMO.GetComments(issueID).ToDataSourceResult(request)); - } - - - /// - /// - /// - /// - /// - public void InsertComments(int issueID, string Comments) - { - try - { - ldDMO.InsertComments(issueID, Comments, (int)Session[GlobalVars.SESSION_USERID]); - } - - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim(); - Functions.WriteEvent(@User.Identity.Name + "\r\n UpdateCopmments\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateCopmments - " + exceptionString }); - throw new Exception(e.Message); - - } - - } - - - /// - /// - /// - /// - /// - /// - public ActionResult ExcelLotOpen(IEnumerable Lotfile, int issueID) - { - MRB_DMO mrbDMO = new MRB_DMO(); - var physicalPath = ""; - try - { - foreach (var file in Lotfile) - { - //string guid = ""; - - string fName = User.Identity.Name + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); - - //physicalPath = Path.Combine(@"C:\Websites\FabApprovalTempPipeLine", fName + "." + Path.GetExtension(file.FileName));\ - physicalPath = Path.Combine(ConfigurationManager.AppSettings["LotTempPipeLine"].ToString(), fName + "." + Path.GetExtension(file.FileName)); - file.SaveAs(physicalPath); - ExcelData x = new ExcelData(physicalPath); - var lotNumbers = x.ReadData(); - - foreach (var lotInfo in lotNumbers) - { - Lot l = new Lot(); - l.LotNumber = lotInfo.LotNo; - l.IssueID = issueID; - if (l.LotStatusOptionID == 0) - l.LotStatusOption.LotStatusOptionID = (int)GlobalVars.LotStatusOption.Release; - - ldDMO.InsertLot(l, true); - //if (!mrbDMO.DoesMRBLotExist(lotInfo.LotNo)) - //{ - // //get All the MRBs associated to the Parent lot - // //insert the lot into the MRBChildLotNotInMRB table and NOT in the MRB Lot table for each MRB - // ldDMO.InsertChildLot_NotInTheMRB(lotInfo.LotNo); - - //} - } - - FileInfo f = new FileInfo(physicalPath); - if (f.Exists) - f.Delete(); - - } - - return Content(""); - } - catch - { - FileInfo f = new FileInfo(physicalPath); - if (f.Exists) - f.Delete(); - - return Content("Incorrect File Format"); - } - - } - - /// - /// - /// - /// - public void ReleaseLockOnDocument(int issueID) - { - try - { - ldDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); - } - catch (Exception e) - { - - try - { - Functions.WriteEvent(@User.Identity.Name + "\r\n ReleaseLockOnDocument LD\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); - } - catch { } - ldDMO.ReleaseLockOnDocument(-1, issueID); - - } - } - - - public ActionResult GetFileMetaData(){ - - return Content(""); - - } - - /// - /// - /// - /// - /// - /// - public FileResult DownloadFile(string attachmentID) - { - //fileName = "ECNForm_71132.pdf"; - - string fileName = ldDMO.GetFileName(attachmentID); - - var sDocument = Path.Combine(Functions.GetAttachmentFolder() + "LotDisposition", fileName); - var FDir_AppData = Functions.GetAttachmentFolder(); - if (!sDocument.StartsWith(FDir_AppData)) - { - // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder - // and block requests outside like "../web.config" - throw new HttpException(403, "Forbidden"); - } - - if (!System.IO.File.Exists(sDocument)) - { - return null; - //throw new Exception("File not found"); - } - - return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Lot Dispo - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw e; } } -} + + public void NotifyRejectionToOrginator(int issueID) { + + List emailIst = ldDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList(); + + string emailTemplate = "LotDispositionReject.txt"; + string userEmail = string.Empty; + string subject = "Lot Disposition Rejection"; + string senderName = "LotDisposition"; + + foreach (string email in emailIst) { + subject = "Lot Disposition Rejection"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = issueID.ToString(); + emailparams[1] = issueID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString(); + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + } + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Rejection: " + userEmail }); + } catch { } + } + + public void UpdateReasonForDisposition(int issueID, string reasonForDisposition) { + try { + ldDMO.UpdateReasonForDisposition(issueID, reasonForDisposition); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateReasonForDisposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateReasonForDisposition - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public ActionResult GetComments([DataSourceRequest] DataSourceRequest request, int issueID) { + //return Json(ldDMO.GetApproversList(issueID, step).ToDataSourceResult(request)); + return Json(ldDMO.GetComments(issueID).ToDataSourceResult(request)); + } + + public void InsertComments(int issueID, string Comments) { + try { + ldDMO.InsertComments(issueID, Comments, (int)Session[GlobalVars.SESSION_USERID]); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateCopmments\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateCopmments - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public ActionResult ExcelLotOpen(IEnumerable Lotfile, int issueID) { + MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); + var physicalPath = ""; + try { + string userIdentityName = @User.Identity.Name; + string lotTempPipeLine = ConfigurationManager.AppSettings["LotTempPipeLine"].ToString(); + foreach (var file in Lotfile) { + physicalPath = ldDMO.ExcelLotOpen(issueID, userIdentityName, lotTempPipeLine, file.FileName, file.InputStream); + } + + return Content(""); + } catch { + FileInfo f = new FileInfo(physicalPath); + if (f.Exists) + f.Delete(); + + return Content("Incorrect File Format"); + } + } + + public void ReleaseLockOnDocument(int issueID) { + try { + ldDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); + } catch (Exception e) { + try { + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument LD\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + } catch { } + ldDMO.ReleaseLockOnDocument(-1, issueID); + } + } + + public ActionResult GetFileMetaData() { + return Content(""); + } + + public FileResult DownloadFile(string attachmentID) { + //fileName = "ECNForm_71132.pdf"; + + string fileName = ldDMO.GetFileName(attachmentID); + + var sDocument = Path.Combine(_AppSettings.AttachmentFolder + "LotDisposition", fileName); + var FDir_AppData = _AppSettings.AttachmentFolder; + if (!sDocument.StartsWith(FDir_AppData)) { + // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder + // and block requests outside like "../web.config" + throw new HttpException(403, "Forbidden"); + } + + if (!System.IO.File.Exists(sDocument)) { + return null; + //throw new Exception("File not found"); + } + + return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + } +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/LotTravelerController.cs b/Fab2ApprovalSystem/Controllers/LotTravelerController.cs index c70305a..1acd43f 100644 --- a/Fab2ApprovalSystem/Controllers/LotTravelerController.cs +++ b/Fab2ApprovalSystem/Controllers/LotTravelerController.cs @@ -1,2926 +1,1710 @@ -using Fab2ApprovalSystem.DMO; -using Fab2ApprovalSystem.Misc; -using Fab2ApprovalSystem.Models; -using System; +using System; using System.Collections.Generic; +using System.Configuration; +using System.IO; using System.Linq; +using System.Threading; using System.Web; using System.Web.Mvc; + +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.PdfGenerator; using Fab2ApprovalSystem.ViewModels; + using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; -using System.IO; -using System.Configuration; -using Fab2ApprovalSystem.PdfGenerator; -using System.Threading; -namespace Fab2ApprovalSystem.Controllers -{ - [Authorize] - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - [SessionExpireFilter] - public class LotTravelerController : PdfViewController - { - // - string docTypeString = "LotTraveler"; - LotTravelerDMO LotTravDMO = new LotTravelerDMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); - - /// - /// - /// - /// - public ActionResult CreateWorkRequest() - { - LTWorkRequest workRequest = new LTWorkRequest(); - try - { - workRequest.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; - LotTravDMO.InsertWorkRequest(workRequest); - return RedirectToAction("Edit", new { issueID = workRequest.ID }); - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequest.SWRNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n CreateWorkRequest - LotTraveler\r\n" + e.InnerException == null? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "CreateWorkRequest - " + exceptionString }); - throw new Exception(e.Message); +namespace Fab2ApprovalSystem.Controllers; - } +[Authorize] +[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +[SessionExpireFilter] +public class LotTravelerController : PdfViewController { + + LotTravelerDMO LotTravDMO; + string docTypeString = "LotTraveler"; + WorkflowDMO wfDMO = new WorkflowDMO(); + private readonly AppSettings _AppSettings; + + public LotTravelerController(AppSettings appSettings) { + _AppSettings = appSettings; + LotTravDMO = new LotTravelerDMO(appSettings); + } + + public ActionResult CreateWorkRequest() { + LTWorkRequest workRequest = new LTWorkRequest(); + try { + workRequest.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + LotTravDMO.InsertWorkRequest(workRequest); + return RedirectToAction("Edit", new { issueID = workRequest.ID }); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequest.SWRNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n CreateWorkRequest - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "CreateWorkRequest - " + exceptionString }); + throw new Exception(e.Message); } + } + public ActionResult Edit(int issueID) { + int isITARCompliant = 1; + Session["CreateNewRevision"] = "false"; + ViewBag.NewRevision = "false"; - - /// - /// - /// - /// - /// - public ActionResult Edit(int issueID) - { - int isITARCompliant = 1; - Session["CreateNewRevision"] = "false"; - ViewBag.NewRevision = "false"; - - - LTWorkRequest workRequest = new LTWorkRequest(); - try - { - workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); - } - if ((int)Session[GlobalVars.SESSION_USERID] == workRequest.OriginatorID) - ViewBag.IsOriginator = "true"; - else - ViewBag.IsOriginator = "false"; - - - List userList = MiscDMO.GetPendingApproversListByDocument(issueID, workRequest.CurrentStep, (int)GlobalVars.DocumentType.LotTraveler); - ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (approver == null) - ViewBag.IsApprover = "false"; - else - ViewBag.IsApprover = "true"; - - if (workRequest.CloseDate != null) - { - // LATER ON SHOULD CALL THE LOT TRAVLELER VIEW - return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); - } - - // open the view based on the Workflow step - if (workRequest.CurrentStep == 0) - { - if ((workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID])) - { - return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); - } - - - } - else if (workRequest.CurrentStep >= 1 && workRequest.CurrentStep < 3 && workRequest.CloseDate == null) // Before - { - if ((ViewBag.IsApprover == "true") || ((bool)Session[GlobalVars.IS_ADMIN])) - return RedirectToAction("WorkRequestApproval", new { issueID = issueID }); - else - return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); - } - else if (workRequest.CurrentStep == 3) - { - if ((workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ViewBag.IsApprover == "false")) - { - return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); - } - else - { - Session["CreateNewRevision"] = "true"; - ViewBag.NewRevision = "true"; - workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - return RedirectToAction("WorkRequestRevision", new { workRequestID = issueID }); - } - - // Start the versioning of the documents with the Edit Feature - // Call the Edit Form - - - - } - workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - // else do this part - ViewBag.Departments = MiscDMO.GetDepartments(); - ViewBag.AffectedModules = MiscDMO.GetModules(); - ViewBag.WorkReqRevisionList = LotTravDMO.GetWorkReqRevisions(workRequest.SWRNumber); - return View(workRequest); - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequest.SWRNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Edit WorkRequest - LotTraveler\r\n" + e.InnerException == null? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Edit WorkRequest - " + exceptionString }); - throw new Exception(e.Message); - - } - } - - /// - /// - /// - /// - /// - public ActionResult SaveRevision(LTWorkRequest model) - { - try + LTWorkRequest workRequest = new LTWorkRequest(); + try { + workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + if (isITARCompliant == 0) // not ITAR Compliant { - var data = model; - if (Session["CreateNewRevision"].ToString() == "true") - { - ViewBag.NewRevision = "false"; - Session["CreateNewRevision"] = "false"; - //Session["CurrentlyOnSamePage"] = "true"; - model.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; - int newRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - // TODO - // Send email to the Originator and Group of People - NotifyfWorkRequestRevisionChange(newRequestID); - - return Content(newRequestID.ToString()); - } - else - { - // model.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; - LotTravDMO.UpdateWorkRequest(model, (int)Session[GlobalVars.SESSION_USERID]); - return Content(""); - } + return View("UnAuthorizedAccess"); } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + model.SWRNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SaveRevision - LotTraveler\r\n" + e.InnerException == null? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = model.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "SaveRevision - " + exceptionString }); - throw new Exception(e.Message); + if ((int)Session[GlobalVars.SESSION_USERID] == workRequest.OriginatorID) + ViewBag.IsOriginator = "true"; + else + ViewBag.IsOriginator = "false"; - } - - - - - } - /// - /// - /// - /// - /// - public ActionResult WorkRequestReadOnly(int issueID) - { - int isITARCompliant = 1; - LTWorkRequest workRequest = new LTWorkRequest(); - try - { - workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - - ViewBag.Departments = MiscDMO.GetDepartments(); - ViewBag.AffectedModules = MiscDMO.GetModules(); - ViewBag.WorkReqRevisionList = LotTravDMO.GetWorkReqRevisions(workRequest.SWRNumber); - - return View(workRequest); - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n WorkRequestReadOnly - LotTraveler\r\n" + e.InnerException == null? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WorkRequestReadOnly - " + exceptionString }); - throw new Exception(e.Message); - - } - - - } - - - - /// - /// - /// - /// - /// - public ActionResult WorkRequestApproval(int issueID) - { - int isITARCompliant = 1; - LTWorkRequest workRequest = new LTWorkRequest(); - try - { - workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - List userList = MiscDMO.GetPendingApproversListByDocument(issueID, workRequest.CurrentStep, (int)GlobalVars.DocumentType.LotTraveler); - - ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (approver == null) - ViewBag.IsApprover = "false"; - else - ViewBag.IsApprover = "true"; - - //if ((workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (!((bool)Session[GlobalVars.IS_ADMIN]) && (ViewBag.IsApprover == "false")) ) - if (workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) - { - return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); - } - - - workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - ViewBag.Departments = MiscDMO.GetDepartments(); - ViewBag.AffectedModules = MiscDMO.GetModules(); - ViewBag.WorkReqRevisionList = LotTravDMO.GetWorkReqRevisions(workRequest.SWRNumber); - - return View(workRequest); - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n WorkRequestApproval - LotTraveler\r\n" + e.InnerException == null? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WorkRequestApproval - " + exceptionString }); - throw new Exception(e.Message); - - } - } - - /// - /// - /// - /// - /// - public ActionResult GetWorkRequestRevision(int workRequestID) - { - int isITARCompliant = 1; - LTWorkRequest workRequest = new LTWorkRequest(); - workRequest = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - //if (workRequest.IsCurrentRevision) - //{ - // return RedirectToAction("Edit", new { issueID = workRequestID }); - //} - return Content(""); - - } - - /// - /// - /// - /// - public ActionResult DisplayWorkRequestPDF(int workRequestID) - { - - WorkRequestPdf workRequest = new WorkRequestPdf(); - try - { - - workRequest = LotTravDMO.GetLTWorkRequestItemPDF(workRequestID); - - // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This - // requires the controller to be inherited from MyController instead of MVC's Controller. - return this.ViewPdf("", "WorkRequestPDF", workRequest); - - } - catch (Exception ex) - { - Functions.WriteEvent(@User.Identity.Name + "\r\n DisplayWorkRequestPDF - LotTraveler\r\n" + ex.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = @User.Identity.Name, DocumentType = "LotTravler", OperationType = "Generate PDF", Comments = ex.Message }); - workRequest = null; - return Content(""); - - } - - } - - - /// - /// - /// - /// - /// - public ActionResult WorkRequestRevision(int workRequestID) - { - int isITARCompliant = 1; - LTWorkRequest workRequest = new LTWorkRequest(); - workRequest = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - List userList = MiscDMO.GetPendingApproversListByDocument(workRequestID, workRequest.CurrentStep, (int)GlobalVars.DocumentType.LotTraveler); - ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + List userList = MiscDMO.GetPendingApproversListByDocument(issueID, workRequest.CurrentStep, (int)GlobalVars.DocumentType.LotTraveler); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); if (approver == null) ViewBag.IsApprover = "false"; else ViewBag.IsApprover = "true"; - if ( - (workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID] - || (ViewBag.IsApprover == "false")) - || (!workRequest.IsCurrentRevision) - || (workRequest.CloseDate != null) - ) - { - return RedirectToAction("WorkRequestReadOnly", new { issueID = workRequestID }); + if (workRequest.CloseDate != null) { + // LATER ON SHOULD CALL THE LOT TRAVLELER VIEW + return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); } - workRequest = LotTravDMO.GetLTWorkRequestItem(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - + // open the view based on the Workflow step + if (workRequest.CurrentStep == 0) { + if ((workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID])) { + return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); + } + + } else if (workRequest.CurrentStep >= 1 && workRequest.CurrentStep < 3 && workRequest.CloseDate == null) // Before + { + if ((ViewBag.IsApprover == "true") || ((bool)Session[GlobalVars.IS_ADMIN])) + return RedirectToAction("WorkRequestApproval", new { issueID = issueID }); + else + return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); + } else if (workRequest.CurrentStep == 3) { + if ((workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ViewBag.IsApprover == "false")) { + return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); + } else { + Session["CreateNewRevision"] = "true"; + ViewBag.NewRevision = "true"; + workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + return RedirectToAction("WorkRequestRevision", new { workRequestID = issueID }); + } + + // Start the versioning of the documents with the Edit Feature + // Call the Edit Form + + } + workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + // else do this part + ViewBag.Departments = MiscDMO.GetDepartments(); + ViewBag.AffectedModules = MiscDMO.GetModules(); + ViewBag.WorkReqRevisionList = LotTravDMO.GetWorkReqRevisions(workRequest.SWRNumber); + return View(workRequest); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequest.SWRNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Edit WorkRequest - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Edit WorkRequest - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public ActionResult SaveRevision(LTWorkRequest model) { + try { + var data = model; + if (Session["CreateNewRevision"].ToString() == "true") { + ViewBag.NewRevision = "false"; + Session["CreateNewRevision"] = "false"; + //Session["CurrentlyOnSamePage"] = "true"; + model.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + int newRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + // TODO + // Send email to the Originator and Group of People + NotifyfWorkRequestRevisionChange(newRequestID); + + return Content(newRequestID.ToString()); + } else { + // model.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + LotTravDMO.UpdateWorkRequest(model, (int)Session[GlobalVars.SESSION_USERID]); + return Content(""); + } + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + model.SWRNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SaveRevision - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = model.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "SaveRevision - " + exceptionString }); + throw new Exception(e.Message); + } + } + + public ActionResult WorkRequestReadOnly(int issueID) { + int isITARCompliant = 1; + LTWorkRequest workRequest = new LTWorkRequest(); + try { + workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); ViewBag.Departments = MiscDMO.GetDepartments(); ViewBag.AffectedModules = MiscDMO.GetModules(); ViewBag.WorkReqRevisionList = LotTravDMO.GetWorkReqRevisions(workRequest.SWRNumber); return View(workRequest); - + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n WorkRequestReadOnly - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WorkRequestReadOnly - " + exceptionString }); + throw new Exception(e.Message); } + } - [HttpPost] - public ActionResult Edit(LTWorkRequest model) - { - try - { - Session["CreateNewRevision"] = "false"; - var data = model; - LotTravDMO.UpdateWorkRequest(model, (int)Session[GlobalVars.SESSION_USERID]); - } - catch(Exception ex) - { - return Content(ex.Message); + public ActionResult WorkRequestApproval(int issueID) { + int isITARCompliant = 1; + LTWorkRequest workRequest = new LTWorkRequest(); + try { + workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + List userList = MiscDMO.GetPendingApproversListByDocument(issueID, workRequest.CurrentStep, (int)GlobalVars.DocumentType.LotTraveler); + + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (approver == null) + ViewBag.IsApprover = "false"; + else + ViewBag.IsApprover = "true"; + + //if ((workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (!((bool)Session[GlobalVars.IS_ADMIN]) && (ViewBag.IsApprover == "false")) ) + if (workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) { + return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); } - return Content("Successfully Saved"); + workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ViewBag.Departments = MiscDMO.GetDepartments(); + ViewBag.AffectedModules = MiscDMO.GetModules(); + ViewBag.WorkReqRevisionList = LotTravDMO.GetWorkReqRevisions(workRequest.SWRNumber); + + return View(workRequest); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n WorkRequestApproval - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WorkRequestApproval - " + exceptionString }); + throw new Exception(e.Message); } - /// - /// - /// - /// - /// - /// - public JsonResult GetBaseFlowLocations(string baseFlow) - { - List loclist = LotTravDMO.GetBaseFlowLocations(baseFlow); - return Json(loclist, JsonRequestBehavior.AllowGet); - + } + + public ActionResult GetWorkRequestRevision(int workRequestID) { + int isITARCompliant = 1; + LTWorkRequest workRequest = new LTWorkRequest(); + workRequest = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + //if (workRequest.IsCurrentRevision) + //{ + // return RedirectToAction("Edit", new { issueID = workRequestID }); + //} + return Content(""); + } + + public ActionResult DisplayWorkRequestPDF(int workRequestID) { + WorkRequestPdf workRequest = new WorkRequestPdf(); + try { + workRequest = LotTravDMO.GetLTWorkRequestItemPDF(workRequestID); + + // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This + // requires the controller to be inherited from MyController instead of MVC's Controller. + return this.ViewPdf("", "WorkRequestPDF", workRequest); + } catch (Exception ex) { + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n DisplayWorkRequestPDF - LotTraveler\r\n" + ex.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = @User.Identity.Name, DocumentType = "LotTravler", OperationType = "Generate PDF", Comments = ex.Message }); + workRequest = null; + return Content(""); + } + } + + public ActionResult WorkRequestRevision(int workRequestID) { + int isITARCompliant = 1; + LTWorkRequest workRequest = new LTWorkRequest(); + workRequest = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + List userList = MiscDMO.GetPendingApproversListByDocument(workRequestID, workRequest.CurrentStep, (int)GlobalVars.DocumentType.LotTraveler); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (approver == null) + ViewBag.IsApprover = "false"; + else + ViewBag.IsApprover = "true"; + + if ( + (workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID] + || (ViewBag.IsApprover == "false")) + || (!workRequest.IsCurrentRevision) + || (workRequest.CloseDate != null) + ) { + return RedirectToAction("WorkRequestReadOnly", new { issueID = workRequestID }); } - /// - /// - /// - /// - /// - public JsonResult GetMaterialRecord(int materialID) - { - LTMaterial ltMaterial = LotTravDMO.GetMaterialRecord(materialID); - return Json(ltMaterial, JsonRequestBehavior.AllowGet); + workRequest = LotTravDMO.GetLTWorkRequestItem(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + ViewBag.Departments = MiscDMO.GetDepartments(); + ViewBag.AffectedModules = MiscDMO.GetModules(); + ViewBag.WorkReqRevisionList = LotTravDMO.GetWorkReqRevisions(workRequest.SWRNumber); + + return View(workRequest); + } + + [HttpPost] + public ActionResult Edit(LTWorkRequest model) { + try { + Session["CreateNewRevision"] = "false"; + var data = model; + LotTravDMO.UpdateWorkRequest(model, (int)Session[GlobalVars.SESSION_USERID]); + } catch (Exception ex) { + return Content(ex.Message); } + return Content("Successfully Saved"); + } + /// + /// + /// + public JsonResult GetBaseFlowLocations(string baseFlow) { + List loclist = LotTravDMO.GetBaseFlowLocations(baseFlow); + return Json(loclist, JsonRequestBehavior.AllowGet); + } - /// - /// - /// - /// - /// - /// - public JsonResult GetBaseFlowOperations(string baseFlow, string location) - { - List operationslist = LotTravDMO.GetBaseFlowOperations(baseFlow, location); - return Json(operationslist, JsonRequestBehavior.AllowGet); - } + public JsonResult GetMaterialRecord(int materialID) { + LTMaterial ltMaterial = LotTravDMO.GetMaterialRecord(materialID); + return Json(ltMaterial, JsonRequestBehavior.AllowGet); + } + public JsonResult GetBaseFlowOperations(string baseFlow, string location) { + List operationslist = LotTravDMO.GetBaseFlowOperations(baseFlow, location); + return Json(operationslist, JsonRequestBehavior.AllowGet); + } - /// - /// - /// - /// - /// - /// - public ActionResult GetMaterialDetails([DataSourceRequest] DataSourceRequest request, int workRequestID) - { - return Json(LotTravDMO.GetMaterialDetails(workRequestID).ToDataSourceResult(request)); - } + public ActionResult GetMaterialDetails([DataSourceRequest] DataSourceRequest request, int workRequestID) { + return Json(LotTravDMO.GetMaterialDetails(workRequestID).ToDataSourceResult(request)); + } - /// - /// - /// - /// - public JsonResult GetPartNumbers() - { - List operationslist = LotTravDMO.GetPartNumbers(); - return Json(operationslist, JsonRequestBehavior.AllowGet); - } + public JsonResult GetPartNumbers() { + List operationslist = LotTravDMO.GetPartNumbers(); + return Json(operationslist, JsonRequestBehavior.AllowGet); + } - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult InsertMaterialDetail([DataSourceRequest] DataSourceRequest request, LTMaterialViewModel model) - { - try - { - string s = Session["CreateNewRevision"].ToString(); - if (model != null && ModelState.IsValid) - { - LotTravDMO.InsertMaterialDetail(model, (int)Session[GlobalVars.SESSION_USERID]); - } - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - catch(Exception ex) - { - //throw new Exception(ex.Message); - return this.Json(new DataSourceResult - { - Errors = ex.Message - }); - } - } - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult UpdateMaterialDetail([DataSourceRequest] DataSourceRequest request, LTMaterialViewModel model) - { - try - { - if (model != null && ModelState.IsValid) - { - LotTravDMO.UpdateMaterialDetail(model, (int)Session[GlobalVars.SESSION_USERID]); - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - catch (Exception ex) - { - //throw new Exception(ex.Message); - return this.Json(new DataSourceResult - { - Errors = ex.Message - }); + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult InsertMaterialDetail([DataSourceRequest] DataSourceRequest request, LTMaterialViewModel model) { + try { + string s = Session["CreateNewRevision"].ToString(); + if (model != null && ModelState.IsValid) { + LotTravDMO.InsertMaterialDetail(model, (int)Session[GlobalVars.SESSION_USERID]); } + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } catch (Exception ex) { + //throw new Exception(ex.Message); + return this.Json(new DataSourceResult { + Errors = ex.Message + }); } + } - /// - /// - /// - /// - /// - public ActionResult AddMaterialDetailRevision(LTWorkRequest model) - { - var modelMaterialDetail = model.LTMaterial; - int previousMaterialID = model.LTMaterial.ID; - int newWorkRequestID = model.ID; - if (Session["CreateNewRevision"].ToString() == "true") - { - Session["CreateNewRevision"] = "false"; + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult UpdateMaterialDetail([DataSourceRequest] DataSourceRequest request, LTMaterialViewModel model) { + try { + if (model != null && ModelState.IsValid) { + LotTravDMO.UpdateMaterialDetail(model, (int)Session[GlobalVars.SESSION_USERID]); + } - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - modelMaterialDetail.LTWorkRequestID = newWorkRequestID; + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } catch (Exception ex) { + //throw new Exception(ex.Message); + return this.Json(new DataSourceResult { + Errors = ex.Message + }); + } + } + public ActionResult AddMaterialDetailRevision(LTWorkRequest model) { + var modelMaterialDetail = model.LTMaterial; + int previousMaterialID = model.LTMaterial.ID; + int newWorkRequestID = model.ID; + if (Session["CreateNewRevision"].ToString() == "true") { + Session["CreateNewRevision"] = "false"; - // Any update will be a new entry + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + modelMaterialDetail.LTWorkRequestID = newWorkRequestID; + + // Any update will be a new entry + LotTravDMO.InsertMaterialDetail(modelMaterialDetail, (int)Session[GlobalVars.SESSION_USERID]); + // TODO + NotifyfWorkRequestRevisionChange(newWorkRequestID); + } else { + if (modelMaterialDetail != null && ModelState.IsValid) { LotTravDMO.InsertMaterialDetail(modelMaterialDetail, (int)Session[GlobalVars.SESSION_USERID]); - // TODO - NotifyfWorkRequestRevisionChange(newWorkRequestID); } - else - { + } - if (modelMaterialDetail != null && ModelState.IsValid) - { - LotTravDMO.InsertMaterialDetail(modelMaterialDetail, (int)Session[GlobalVars.SESSION_USERID]); + return Content(newWorkRequestID.ToString()); + } + + /// + /// For the Revison + /// + public ActionResult UpdateMaterialDetailRevision(LTWorkRequest model) { + var modelMaterialDetail = model.LTMaterial; + int previousMaterialID = model.LTMaterial.ID; + int newWorkRequestID = model.ID; + + if (Session["CreateNewRevision"].ToString() == "true") { + Session["CreateNewRevision"] = "false"; + + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + modelMaterialDetail.LTWorkRequestID = newWorkRequestID; + + // Any update will be a new entry + LotTravDMO.UpdateMaterialDetailRevision(modelMaterialDetail, previousMaterialID); + // TODO + // Send email to the Originator and Group of People + NotifyfWorkRequestRevisionChange(newWorkRequestID); + } else { + if (modelMaterialDetail != null && ModelState.IsValid) { + LotTravDMO.UpdateMaterialDetail(modelMaterialDetail, (int)Session[GlobalVars.SESSION_USERID]); + } + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); + return Content(newWorkRequestID.ToString()); + } + + public ActionResult DeleteMaterialDetail([DataSourceRequest] DataSourceRequest request, LTMaterialViewModel model) { + try { + if (model != null && ModelState.IsValid) { + LotTravDMO.DeleteMaterialDetail(model.ID); + + } + } catch (Exception e) { + //string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + //Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AttachmentID Disposition\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + //EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); + //throw new Exception(e.Message); + } + + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult DeleteMaterialDetailRevision(LTWorkRequest model) { + var modelMaterialDetail = model.LTMaterial; + int newWorkRequestID = model.ID; + + if (Session["CreateNewRevision"].ToString() == "true") { + Session["CreateNewRevision"] = "false"; + + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + modelMaterialDetail.LTWorkRequestID = newWorkRequestID; + + // Any update will be a new entry + LotTravDMO.DeleteMaterialDetailRevision(modelMaterialDetail.ID); + // TODO + // Send email to the Originator and Group of People + NotifyfWorkRequestRevisionChange(newWorkRequestID); + } else { + if (modelMaterialDetail != null && ModelState.IsValid) { + LotTravDMO.DeleteMaterialDetail(modelMaterialDetail.ID); + } + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); + return Content(newWorkRequestID.ToString()); + } + + public ActionResult GetHoldSteps([DataSourceRequest] DataSourceRequest request, int workRequestID) { + return Json(LotTravDMO.GetHoldSteps(workRequestID).ToDataSourceResult(request)); + } + + public ActionResult InsertHoldStep([DataSourceRequest] DataSourceRequest request, LTHoldStep model) { + if (model != null && ModelState.IsValid) { + model.UpdatedBy = (int)Session[GlobalVars.SESSION_USERID]; + LotTravDMO.InsertHoldStep(model); + } + + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult UpdateHoldStepRevision(LTWorkRequest model) { + var holdStepModel = model.LTHoldStep; + int newWorkRequestID = model.ID; + + if (Session["CreateNewRevision"].ToString() == "true") { + Session["CreateNewRevision"] = "false"; + + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + holdStepModel.LTWorkRequestID = newWorkRequestID; + + // Any update will be a new entry + LotTravDMO.UpdateHoldStepRevision(holdStepModel); + // TODO + // Send email to the Originator and Group of People + NotifyfWorkRequestRevisionChange(newWorkRequestID); + } else { + if (holdStepModel != null && ModelState.IsValid) { + holdStepModel.UpdatedBy = (int)Session[GlobalVars.SESSION_USERID]; + LotTravDMO.UpdateHoldStep(holdStepModel); + } + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); + return Content(newWorkRequestID.ToString()); + } + + public ActionResult InsertHoldStepRevision(LTWorkRequest model) { + var holdStepModel = model.LTHoldStep; + int newWorkRequestID = model.ID; + + if (Session["CreateNewRevision"].ToString() == "true") { + Session["CreateNewRevision"] = "false"; + + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + holdStepModel.LTWorkRequestID = newWorkRequestID; + + // Any update will be a new entry + LotTravDMO.InsertHoldStepRevision(holdStepModel); + // TODO + // Send email to the Originator and Group of People + NotifyfWorkRequestRevisionChange(newWorkRequestID); + } else { + if (holdStepModel != null && ModelState.IsValid) { + holdStepModel.UpdatedBy = (int)Session[GlobalVars.SESSION_USERID]; + LotTravDMO.InsertHoldStep(holdStepModel); + } + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); + return Content(newWorkRequestID.ToString()); + } + + public ActionResult DeleteHoldStepRevision(LTWorkRequest model) { + var holdStepModel = model.LTHoldStep; + int newWorkRequestID = model.ID; + + if (Session["CreateNewRevision"].ToString() == "true") { + Session["CreateNewRevision"] = "false"; + + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + holdStepModel.LTWorkRequestID = newWorkRequestID; + + // Any update will be a new entry + LotTravDMO.DeleteHoldStepRevision(holdStepModel.ID); + // TODO + // Send email to the Originator and Group of People + NotifyfWorkRequestRevisionChange(newWorkRequestID); + } else { + if (holdStepModel != null && ModelState.IsValid) { + + LotTravDMO.DeleteHoldStep(holdStepModel.ID, (int)Session[GlobalVars.SESSION_USERID]); + } + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); + return Content(newWorkRequestID.ToString()); + } + + public void UpdateHoldStep(LTHoldStep model) { + if (model != null && ModelState.IsValid) { + LotTravDMO.UpdateHoldStep(model); + } + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteHoldStep([DataSourceRequest] DataSourceRequest request, LTHoldStep model) { + try { + if (model != null && ModelState.IsValid) { + LotTravDMO.DeleteHoldStep(model.ID, (int)Session[GlobalVars.SESSION_USERID]); + + } + } catch (Exception ex) { + //throw new Exception(ex.Message); + return this.Json(new DataSourceResult { + Errors = ex.Message + }); + } + + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult GetHoldStep(int holdStepID) { + var model = new LTHoldStep(); + model = LotTravDMO.GetHoldStep(holdStepID); + + return PartialView("_HoldStepAttachments", model); + } + + public ActionResult GetHoldStepRevision(int holdStepID) { + var model = new LTHoldStep(); + model = LotTravDMO.GetHoldStep(holdStepID); + + return PartialView("_HoldStepAttachmentsRevision", model); + } + + public ActionResult GetLotTravHoldStepRevision(int ltHoldStepID) { + var model = new LTLotTravelerHoldSteps(); + model = LotTravDMO.GetLotTravHoldStep(ltHoldStepID); + return PartialView("_LotTravHoldStepAttachRev", model); + } + + public ActionResult GetHoldStepAttachments([DataSourceRequest] DataSourceRequest request, int holdStepID) { + //var model = LotTravDMO.GetHoldStepAttachemnts(holdStepID); + //return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + + return Json(LotTravDMO.GetHoldStepAttachemnts(holdStepID).ToDataSourceResult(request)); + } + + public ActionResult GetLTHoldStepAttachments([DataSourceRequest] DataSourceRequest request, int ltHoldStepID) { + //var model = LotTravDMO.GetHoldStepAttachemnts(holdStepID); + //return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + + return Json(LotTravDMO.GetLotTravHoldStepAttachemnts(ltHoldStepID).ToDataSourceResult(request)); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteHoldStepAttachment([DataSourceRequest] DataSourceRequest request, LTWorkRequestAttachment model) { + try { + if (model != null && ModelState.IsValid) { + LotTravDMO.DeleteWorkRequestAttachment(model.ID); + + } + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + model.ID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AttachmentID Work Request\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); + } + + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult GetWorkRequestAttachments([DataSourceRequest] DataSourceRequest request, int workRequestID) { + return Json(LotTravDMO.GetWorkRequestAttachments(workRequestID).ToDataSourceResult(request)); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult UpdateWorkRequestAttachment([DataSourceRequest] DataSourceRequest request, LTWorkRequestAttachment model) { + if (model != null && ModelState.IsValid) { + LotTravDMO.UpdateWorkRequestAttachment(model); + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + /// + /// + /// + public ActionResult UpdateWorkRequestAttachmentRevision(LTWorkRequest model) { + var wrAttachmentDetail = model.WorkRequestAttachment; + int previousWorkRequestAttachmentID = model.WorkRequestAttachment.ID; + int newWorkRequestID = model.ID; + + if (Session["CreateNewRevision"].ToString() == "true") { + Session["CreateNewRevision"] = "false"; + + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + wrAttachmentDetail.WorkRequestID = newWorkRequestID; + + // Any update will be a new entry + LotTravDMO.UpdateWorkRequestAttachmentRevision(wrAttachmentDetail, previousWorkRequestAttachmentID); + // TODO + // Send email to the Originator and Group of People + NotifyfWorkRequestRevisionChange(newWorkRequestID); + } else { + if (wrAttachmentDetail != null && ModelState.IsValid) { + LotTravDMO.UpdateWorkRequestAttachment(wrAttachmentDetail); + } + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); + return Content(newWorkRequestID.ToString()); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteWorkRequestAttachment([DataSourceRequest] DataSourceRequest request, LTWorkRequestAttachment model) { + try { + if (model != null && ModelState.IsValid) { + LotTravDMO.DeleteWorkRequestAttachment(model.ID); + + } + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + model.ID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AttachmentID WorkRequiest\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); + } + + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + public ActionResult DeleteWorkRequestAttachmentRevision(LTWorkRequest model) { + var wrAttachmentDetail = model.WorkRequestAttachment; + int previousWorkRequestAttachmentID = model.WorkRequestAttachment.ID; + int newWorkRequestID = model.ID; + + if (Session["CreateNewRevision"].ToString() == "true") { + Session["CreateNewRevision"] = "false"; + + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + wrAttachmentDetail.WorkRequestID = newWorkRequestID; + + // Any update will be a new entry + LotTravDMO.DeleteWorkRequestAttachmentRevision(wrAttachmentDetail.ID); + // TODO + // Send email to the Originator and Group of People + NotifyfWorkRequestRevisionChange(newWorkRequestID); + } else { + if (wrAttachmentDetail != null && ModelState.IsValid) { + LotTravDMO.DeleteWorkRequestAttachment(wrAttachmentDetail.ID); + } + } + + //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; + //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); + return Content(newWorkRequestID.ToString()); + } + + public ActionResult AttachSaveWorkRequest(IEnumerable files, int workRequestID, int currentRevision, int swrNo, string comments, string docType) { + // The Name of the Upload component is "files" + if (files != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in files) { + LotTravDMO.AttachSaveWorkRequest(workRequestID, swrNo, comments, docType, userId, file.FileName, file.InputStream); + } + } + return Content(""); + } + + public ActionResult AttachSaveWorkRequestRevision(IEnumerable files, int workRequestID, int currentRevision, int swrNo, string revComments, string docType, string attachComments) { + bool newRevision = false; + int newWorkRequestID = -1; + int isITARCompliant = 1; + LTWorkRequest model = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + model.RevisionComments = revComments; + + if (Session["CreateNewRevision"].ToString() == "true") { + newRevision = true; + Session["CreateNewRevision"] = "false"; + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + + // Send email to the Originator and Group of People + NotifyfWorkRequestRevisionChange(newWorkRequestID); + } + + // The Name of the Upload component is "files" + if (files != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in files) { + LotTravDMO.AttachSaveWorkRequestRevision(workRequestID, swrNo, docType, attachComments, newRevision, userId, file.FileName, file.InputStream); + } + } + return Content(""); + } + + public ActionResult HoldStepAttachSave(IEnumerable HoldStepAttachment, int holdStepID, int currentRevision, int swrNo, string docType, string comments) { + // The Name of the Upload component is "files" + try { + if (HoldStepAttachment != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in HoldStepAttachment) { + LotTravDMO.HoldStepAttachSave(holdStepID, swrNo, docType, comments, userId, file.FileName, file.InputStream); } } - - return Content(newWorkRequestID.ToString()); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "HoldStep=" + holdStepID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = holdStepID, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "HoldStep Attachment - " + exceptionString }); + throw new Exception(e.Message); } - /// - /// For the Revison - /// - /// - /// - /// - - public ActionResult UpdateMaterialDetailRevision(LTWorkRequest model) - { - var modelMaterialDetail = model.LTMaterial; - int previousMaterialID = model.LTMaterial.ID; - int newWorkRequestID = model.ID; + //var model = ldDMO.GetLotDispoAttachments(issueID); - if (Session["CreateNewRevision"].ToString() == "true") - { - Session["CreateNewRevision"] = "false"; + return Content(""); + } - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - modelMaterialDetail.LTWorkRequestID = newWorkRequestID; + public ActionResult HoldStepAttachSaveRev(IEnumerable HoldStepAttachment, int workRequestID, int holdStepID, int currentRevision, int swrNo, string docType, string comments, string revComments) { + // The Name of the Upload component is "files" + bool newRevision = false; + int newWorkRequestID = -1; + int isITARCompliant = 1; + LTWorkRequest model = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + model.RevisionComments = revComments; + if (Session["CreateNewRevision"].ToString() == "true") { + newRevision = true; + Session["CreateNewRevision"] = "false"; + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - // Any update will be a new entry - LotTravDMO.UpdateMaterialDetailRevision(modelMaterialDetail, previousMaterialID); - // TODO - // Send email to the Originator and Group of People - NotifyfWorkRequestRevisionChange(newWorkRequestID); - } - else - { + NotifyfWorkRequestRevisionChange(newWorkRequestID); + } - if (modelMaterialDetail != null && ModelState.IsValid) - { - LotTravDMO.UpdateMaterialDetail(modelMaterialDetail, (int)Session[GlobalVars.SESSION_USERID]); + try { + if (HoldStepAttachment != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in HoldStepAttachment) { + LotTravDMO.HoldStepAttachSaveRev(holdStepID, swrNo, docType, comments, newRevision, userId, file.FileName, file.InputStream); } } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); - return Content(newWorkRequestID.ToString()); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "HoldStep=" + holdStepID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = holdStepID, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "HoldStep Attachment - " + exceptionString }); + throw new Exception(e.Message); } - public ActionResult DeleteMaterialDetail([DataSourceRequest] DataSourceRequest request, LTMaterialViewModel model) - { - try + //var model = ldDMO.GetLotDispoAttachments(issueID); + + return Content(""); + } + + public int GetRevisedWrkReqIDFromHoldStepID(int prevHoldStepID) { + return LotTravDMO.GetRevisedWrkReqIDFromHoldStepID(prevHoldStepID); + } + + public int GetRevisedWrkReqIDFromPreviousWrkReqID(int prevWorkRequestID) { + return LotTravDMO.GetRevisedWrkReqIDFromPreviousWrkReqID(prevWorkRequestID); + } + + public JsonResult GetWorkRequestAttachDetail(int wrAttachmentID) { + LTWorkRequestAttachment data = LotTravDMO.GetWorkRequestAttachDetail(wrAttachmentID); + return Json(data, JsonRequestBehavior.AllowGet); + } + + public ActionResult SubmitDocument(int workRequestID, int documentType) { + int isITARCompliant = 1; + LTWorkRequest ltWR = new LTWorkRequest(); + try { + int appoverCount = LotTravDMO.SubmitDocument(workRequestID, (int)Session[GlobalVars.SESSION_USERID], documentType, out isITARCompliant); + if (isITARCompliant == 0) // not ITAR Compliant { - if (model != null && ModelState.IsValid) - { - LotTravDMO.DeleteMaterialDetail(model.ID); + return View("UnAuthorizedAccess"); + } else { + if (appoverCount > 0) { + NotifyApprovers(workRequestID, (byte)GlobalVars.WorkFLowStepNumber.Step1, documentType); + } else { + // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval + Approve(workRequestID, (byte)GlobalVars.WorkFLowStepNumber.Step1, "", documentType); // this is the Submit Level Approval } - } - catch (Exception e) - { - //string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - //Functions.WriteEvent(@User.Identity.Name + "\r\n AttachmentID Disposition\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - //EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); - //throw new Exception(e.Message); - } + ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - /// - /// - /// - /// - /// - public ActionResult DeleteMaterialDetailRevision(LTWorkRequest model) - { - var modelMaterialDetail = model.LTMaterial; - int newWorkRequestID = model.ID; - - if (Session["CreateNewRevision"].ToString() == "true") - { - Session["CreateNewRevision"] = "false"; - - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - modelMaterialDetail.LTWorkRequestID = newWorkRequestID; - - - // Any update will be a new entry - LotTravDMO.DeleteMaterialDetailRevision(modelMaterialDetail.ID); - // TODO - // Send email to the Originator and Group of People - NotifyfWorkRequestRevisionChange(newWorkRequestID); - } - else - { - - if (modelMaterialDetail != null && ModelState.IsValid) - { - LotTravDMO.DeleteMaterialDetail(modelMaterialDetail.ID); - } - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); - return Content(newWorkRequestID.ToString()); - } - - /// - /// - /// - /// - /// - /// - public ActionResult GetHoldSteps([DataSourceRequest] DataSourceRequest request, int workRequestID) - { - return Json(LotTravDMO.GetHoldSteps(workRequestID).ToDataSourceResult(request)); - } - - - //public ActionResult InsertUpdateHoldStep([DataSourceRequest] DataSourceRequest request, LTHoldStep model) - //{ - // if (model != null && ModelState.IsValid) - // { - // LotTravDMO.InsertUpdateHoldStep(model); - // } - - - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - - - //public ActionResult UpdateHoldStep([DataSourceRequest] DataSourceRequest request, LTHoldStep model) - //{ - // if (model != null && ModelState.IsValid) - // { - // LotTravDMO.UpdateHoldStep(model); - // } - - - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - - - public ActionResult InsertHoldStep([DataSourceRequest] DataSourceRequest request, LTHoldStep model) - { - if (model != null && ModelState.IsValid) - { - model.UpdatedBy = (int)Session[GlobalVars.SESSION_USERID]; - LotTravDMO.InsertHoldStep(model); - } - - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - - /// - /// - /// - /// - /// - /// - public ActionResult UpdateHoldStepRevision(LTWorkRequest model) - { - var holdStepModel = model.LTHoldStep; - int newWorkRequestID = model.ID; - - if (Session["CreateNewRevision"].ToString() == "true") - { - Session["CreateNewRevision"] = "false"; - - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - holdStepModel.LTWorkRequestID = newWorkRequestID; - - - // Any update will be a new entry - LotTravDMO.UpdateHoldStepRevision(holdStepModel); - // TODO - // Send email to the Originator and Group of People - NotifyfWorkRequestRevisionChange(newWorkRequestID); - } - else - { - - if (holdStepModel != null && ModelState.IsValid) - { - holdStepModel.UpdatedBy = (int)Session[GlobalVars.SESSION_USERID]; - LotTravDMO.UpdateHoldStep(holdStepModel); - } - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); - return Content(newWorkRequestID.ToString()); - } - - - public ActionResult InsertHoldStepRevision(LTWorkRequest model) - { - var holdStepModel = model.LTHoldStep; - int newWorkRequestID = model.ID; - - if (Session["CreateNewRevision"].ToString() == "true") - { - Session["CreateNewRevision"] = "false"; - - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - holdStepModel.LTWorkRequestID = newWorkRequestID; - - - // Any update will be a new entry - LotTravDMO.InsertHoldStepRevision(holdStepModel); - // TODO - // Send email to the Originator and Group of People - NotifyfWorkRequestRevisionChange(newWorkRequestID); - } - else - { - - if (holdStepModel != null && ModelState.IsValid) - { - holdStepModel.UpdatedBy = (int)Session[GlobalVars.SESSION_USERID]; - LotTravDMO.InsertHoldStep(holdStepModel); - } - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); - return Content(newWorkRequestID.ToString()); - } - - - /// - /// - /// - /// - /// - public ActionResult DeleteHoldStepRevision(LTWorkRequest model) - { - var holdStepModel = model.LTHoldStep; - int newWorkRequestID = model.ID; - - if (Session["CreateNewRevision"].ToString() == "true") - { - Session["CreateNewRevision"] = "false"; - - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - holdStepModel.LTWorkRequestID = newWorkRequestID; - - - // Any update will be a new entry - LotTravDMO.DeleteHoldStepRevision(holdStepModel.ID); - // TODO - // Send email to the Originator and Group of People - NotifyfWorkRequestRevisionChange(newWorkRequestID); - } - else - { - - if (holdStepModel != null && ModelState.IsValid) - { - - LotTravDMO.DeleteHoldStep(holdStepModel.ID, (int)Session[GlobalVars.SESSION_USERID]); - } - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); - return Content(newWorkRequestID.ToString()); - } - - /// - /// - /// - /// - public void UpdateHoldStep(LTHoldStep model) - { - if (model != null && ModelState.IsValid) - { - LotTravDMO.UpdateHoldStep(model); - } - } - - - - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteHoldStep([DataSourceRequest] DataSourceRequest request, LTHoldStep model) - { - try - { - if (model != null && ModelState.IsValid) - { - LotTravDMO.DeleteHoldStep(model.ID, (int)Session[GlobalVars.SESSION_USERID]); - - } - } - catch (Exception ex) - { - //throw new Exception(ex.Message); - return this.Json(new DataSourceResult - { - Errors = ex.Message - }); - } - - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - /// - /// - /// - /// - /// - public ActionResult GetHoldStep(int holdStepID) - { - var model = new LTHoldStep(); - model = LotTravDMO.GetHoldStep(holdStepID); - - return PartialView("_HoldStepAttachments", model); - } - - /// - /// - /// - /// - /// - public ActionResult GetHoldStepRevision(int holdStepID) - { - var model = new LTHoldStep(); - model = LotTravDMO.GetHoldStep(holdStepID); - - return PartialView("_HoldStepAttachmentsRevision", model); - } - - - /// - /// - /// - /// - /// - public ActionResult GetLotTravHoldStepRevision(int ltHoldStepID) - { - var model = new LTLotTravelerHoldSteps(); - model = LotTravDMO.GetLotTravHoldStep(ltHoldStepID); - return PartialView("_LotTravHoldStepAttachRev", model); - } - - /// - /// - /// - /// - /// - public ActionResult GetHoldStepAttachments([DataSourceRequest] DataSourceRequest request, int holdStepID) - { - - //var model = LotTravDMO.GetHoldStepAttachemnts(holdStepID); - //return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - - return Json(LotTravDMO.GetHoldStepAttachemnts(holdStepID).ToDataSourceResult(request)); - - } - - /// - /// - /// - /// - /// - /// - public ActionResult GetLTHoldStepAttachments([DataSourceRequest] DataSourceRequest request, int ltHoldStepID) - { - - //var model = LotTravDMO.GetHoldStepAttachemnts(holdStepID); - //return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - - return Json(LotTravDMO.GetLotTravHoldStepAttachemnts(ltHoldStepID).ToDataSourceResult(request)); - - } - - - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteHoldStepAttachment([DataSourceRequest] DataSourceRequest request, LTWorkRequestAttachment model) - { - try - { - if (model != null && ModelState.IsValid) - { - LotTravDMO.DeleteWorkRequestAttachment(model.ID); - - } - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + model.ID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AttachmentID Work Request\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - - } - - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - - /// - /// - /// - /// - /// - /// - public ActionResult GetWorkRequestAttachments([DataSourceRequest] DataSourceRequest request, int workRequestID) - { - return Json(LotTravDMO.GetWorkRequestAttachments(workRequestID).ToDataSourceResult(request)); - } - - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult UpdateWorkRequestAttachment([DataSourceRequest] DataSourceRequest request, LTWorkRequestAttachment model) - { - - if (model != null && ModelState.IsValid) - { - LotTravDMO.UpdateWorkRequestAttachment(model); - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - /// - /// - /// - /// - /// - public ActionResult UpdateWorkRequestAttachmentRevision(LTWorkRequest model) - { - var wrAttachmentDetail = model.WorkRequestAttachment; - int previousWorkRequestAttachmentID = model.WorkRequestAttachment.ID; - int newWorkRequestID = model.ID; - - if (Session["CreateNewRevision"].ToString() == "true") - { - Session["CreateNewRevision"] = "false"; - - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - wrAttachmentDetail.WorkRequestID = newWorkRequestID; - - - // Any update will be a new entry - LotTravDMO.UpdateWorkRequestAttachmentRevision(wrAttachmentDetail, previousWorkRequestAttachmentID); - // TODO - // Send email to the Originator and Group of People - NotifyfWorkRequestRevisionChange(newWorkRequestID); - } - else - { - - if (wrAttachmentDetail != null && ModelState.IsValid) - { - LotTravDMO.UpdateWorkRequestAttachment(wrAttachmentDetail); - } - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); - return Content(newWorkRequestID.ToString()); - - } - - - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteWorkRequestAttachment([DataSourceRequest] DataSourceRequest request, LTWorkRequestAttachment model) - { - try - { - if (model != null && ModelState.IsValid) - { - LotTravDMO.DeleteWorkRequestAttachment(model.ID); - - } - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + model.ID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AttachmentID WorkRequiest\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - - } - - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - } - - - /// - /// - /// - /// - /// - public ActionResult DeleteWorkRequestAttachmentRevision( LTWorkRequest model) - { - var wrAttachmentDetail = model.WorkRequestAttachment; - int previousWorkRequestAttachmentID = model.WorkRequestAttachment.ID; - int newWorkRequestID = model.ID; - - if (Session["CreateNewRevision"].ToString() == "true") - { - Session["CreateNewRevision"] = "false"; - - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - wrAttachmentDetail.WorkRequestID = newWorkRequestID; - - - // Any update will be a new entry - LotTravDMO.DeleteWorkRequestAttachmentRevision(wrAttachmentDetail.ID); - // TODO - // Send email to the Originator and Group of People - NotifyfWorkRequestRevisionChange(newWorkRequestID); - } - else - { - - if (wrAttachmentDetail != null && ModelState.IsValid) - { - LotTravDMO.DeleteWorkRequestAttachment(wrAttachmentDetail.ID); - } - } - - //lot.LotStatusOptionID = lot.LotStatusOption.LotStatusOptionID; - //return Json(new[] { modelMaterialDetail }.ToDataSourceResult(request, ModelState)); - return Content(newWorkRequestID.ToString()); - } - - /// - /// - /// - /// - /// - /// - /// - /// - public ActionResult AttachSaveWorkRequest(IEnumerable files, int workRequestID, int currentRevision, int swrNo, string comments, string docType) - { - // The Name of the Upload component is "files" - if (files != null) - { - foreach (var file in files) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - // TODO - //int currentRevision = 1; - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var SWRPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo; - di = new DirectoryInfo(SWRPhysicalPath); - if (!di.Exists) - di.Create(); - - //var SWR_RevPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision; - var SWR_RevPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo ; - di = new DirectoryInfo(SWR_RevPhysicalPath); - if (!di.Exists) - di.Create(); - - var guid = Guid.NewGuid().ToString(); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\", guid + fileExtension); - - - - file.SaveAs(physicalPath); - LTWorkRequestAttachment attach = new LTWorkRequestAttachment() - { - WorkRequestID = workRequestID, - FileGUID = guid, - LTHoldStepID = -1, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID], - DocType = docType, - Comments = comments - - }; - - - LotTravDMO.InsertWorkRequestAttachment(attach); - } - } - return Content(""); - } - - - public ActionResult AttachSaveWorkRequestRevision(IEnumerable files, int workRequestID, int currentRevision, int swrNo, string revComments, string docType, string attachComments) - { - - bool newRevision = false; - int newWorkRequestID = -1; - int isITARCompliant = 1; - LTWorkRequest model = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - model.RevisionComments = revComments; - - if (Session["CreateNewRevision"].ToString() == "true") - { - newRevision = true; - Session["CreateNewRevision"] = "false"; - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - - // Send email to the Originator and Group of People - NotifyfWorkRequestRevisionChange(newWorkRequestID); - } - - // The Name of the Upload component is "files" - if (files != null) - { - foreach (var file in files) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - // TODO - //int currentRevision = 1; - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var SWRPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo; - di = new DirectoryInfo(SWRPhysicalPath); - if (!di.Exists) - di.Create(); - - //var SWR_RevPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision; - var SWR_RevPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo; - di = new DirectoryInfo(SWR_RevPhysicalPath); - if (!di.Exists) - di.Create(); - - var guid = Guid.NewGuid().ToString(); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\", guid + fileExtension); - - - - file.SaveAs(physicalPath); - LTWorkRequestAttachment attach = new LTWorkRequestAttachment() - { - WorkRequestID = workRequestID, - FileGUID = guid, - LTHoldStepID = -1, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID], - DocType = docType, - Comments = attachComments - }; - - - // LotTravDMO.InsertWorkRequestAttachment(attach); - if (newRevision) - LotTravDMO.InsertWorkRequestAttachmentRevision(attach); - else - LotTravDMO.InsertWorkRequestAttachment(attach); - } - } - return Content(""); - } - - - /// - /// - /// - /// - /// - /// - /// - /// - /// - public ActionResult HoldStepAttachSave(IEnumerable HoldStepAttachment, int holdStepID, int currentRevision, int swrNo, string docType, string comments) - { - // The Name of the Upload component is "files" - try - { - if (HoldStepAttachment != null) - { - foreach (var file in HoldStepAttachment) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - // TODO - //int currentRevision = 1; - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var SWRPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo; - di = new DirectoryInfo(SWRPhysicalPath); - if (!di.Exists) - di.Create(); - - //var SWR_RevPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision; - var SWR_RevPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo ; - di = new DirectoryInfo(SWR_RevPhysicalPath); - if (!di.Exists) - di.Create(); - - var guid = Guid.NewGuid().ToString(); - //var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision + @"\", guid + fileExtension); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\", guid + fileExtension); - - - - file.SaveAs(physicalPath); - LTWorkRequestAttachment attach = new LTWorkRequestAttachment() - { - FileGUID = guid, - LTHoldStepID = holdStepID, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID], - DocType = docType, - Comments = comments - }; - - LotTravDMO.InsertLotHoldStepAttachment(attach); - } - } - } - catch(Exception e) - { - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "HoldStep=" + holdStepID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = holdStepID, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "HoldStep Attachment - " + exceptionString }); - throw new Exception(e.Message); - } - - //var model = ldDMO.GetLotDispoAttachments(issueID); - - - return Content(""); - } - - - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public ActionResult HoldStepAttachSaveRev(IEnumerable HoldStepAttachment, int workRequestID, int holdStepID, int currentRevision, int swrNo, string docType, string comments, string revComments) - { - // The Name of the Upload component is "files" - bool newRevision = false; - int newWorkRequestID = -1; - int isITARCompliant = 1; - LTWorkRequest model = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - model.RevisionComments = revComments; - - if (Session["CreateNewRevision"].ToString() == "true") - { - newRevision = true; - Session["CreateNewRevision"] = "false"; - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - - NotifyfWorkRequestRevisionChange(newWorkRequestID); - } - - try - { - if (HoldStepAttachment != null) - { - foreach (var file in HoldStepAttachment) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - - // TODO - //int currentRevision = 1; - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var SWRPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo; - di = new DirectoryInfo(SWRPhysicalPath); - if (!di.Exists) - di.Create(); - - //var SWR_RevPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision; - var SWR_RevPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo; - di = new DirectoryInfo(SWR_RevPhysicalPath); - if (!di.Exists) - di.Create(); - - var guid = Guid.NewGuid().ToString(); - //var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision + @"\", guid + fileExtension); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\", guid + fileExtension); - - - - file.SaveAs(physicalPath); - LTWorkRequestAttachment attach = new LTWorkRequestAttachment() - { - FileGUID = guid, - LTHoldStepID = holdStepID, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID], - DocType = docType, - Comments = comments - }; - if (newRevision) - LotTravDMO.InsertLotHoldStepAttachmentRevision(attach); - else - LotTravDMO.InsertLotHoldStepAttachment(attach); - - } - } - } - catch (Exception e) - { - - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "HoldStep=" + holdStepID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = holdStepID, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "HoldStep Attachment - " + exceptionString }); - throw new Exception(e.Message); - } - - //var model = ldDMO.GetLotDispoAttachments(issueID); - - - return Content(""); - } - - /// - /// - /// - /// - /// - public int GetRevisedWrkReqIDFromHoldStepID(int prevHoldStepID) - { - return LotTravDMO.GetRevisedWrkReqIDFromHoldStepID(prevHoldStepID); - } - - - /// - /// - /// - /// - /// - public int GetRevisedWrkReqIDFromPreviousWrkReqID(int prevWorkRequestID) - { - return LotTravDMO.GetRevisedWrkReqIDFromPreviousWrkReqID(prevWorkRequestID); - } - - /// - /// - /// - /// - /// - public JsonResult GetWorkRequestAttachDetail(int wrAttachmentID) - { - LTWorkRequestAttachment data = LotTravDMO.GetWorkRequestAttachDetail(wrAttachmentID); - return Json(data, JsonRequestBehavior.AllowGet); - } - - /// - /// - /// - /// - /// - /// - public ActionResult SubmitDocument(int workRequestID, int documentType) - { - int isITARCompliant = 1; - LTWorkRequest ltWR = new LTWorkRequest(); - try - { - - int appoverCount = LotTravDMO.SubmitDocument(workRequestID, (int)Session[GlobalVars.SESSION_USERID], documentType, out isITARCompliant); - if (isITARCompliant == 0) // not ITAR Compliant - { - return View("UnAuthorizedAccess"); - } + List userList = MiscDMO.GetPendingApproversListByDocument(workRequestID, ltWR.CurrentStep, (int)documentType); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + if (approver == null) + ViewBag.IsApprover = "false"; else - { + ViewBag.IsApprover = "true"; - if (appoverCount > 0) - { - NotifyApprovers(workRequestID, (byte)GlobalVars.WorkFLowStepNumber.Step1, documentType); - } - else - { - // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval - Approve(workRequestID, (byte)GlobalVars.WorkFLowStepNumber.Step1, "", documentType); // this is the Submit Level Approval - - } - - ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - List userList = MiscDMO.GetPendingApproversListByDocument(workRequestID, ltWR.CurrentStep, (int)documentType); - ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); - if (approver == null) - ViewBag.IsApprover = "false"; - else - ViewBag.IsApprover = "true"; - - - if ((int)Session[GlobalVars.SESSION_USERID] == ltWR.OriginatorID) - ViewBag.IsOriginator = "true"; - else - ViewBag.IsOriginator = "false"; - - - if (Request.IsAjaxRequest()) - { - // the content gets evaluated on the client side - return Content("Redirect"); - } - else - return Content("Invalid"); - - //return View(ltWR); - } - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); - throw new Exception(e.Message); - - } - } - - /// - /// - /// - /// - /// - /// - public void Approve(int workRequestID, byte currentStep, string comments, int documentType) - { - LTWorkRequest ltWR = new LTWorkRequest(); - int isITAR = 1; - ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITAR, (int)Session[GlobalVars.SESSION_USERID]); - try - { - - bool lastStep = false; - bool lastApprover = wfDMO.Approve(workRequestID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType, ltWR.WorkFlowNumber); - - while (lastApprover && !lastStep) - { - currentStep++; - lastApprover = wfDMO.Approve(workRequestID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType, ltWR.WorkFlowNumber); - - //if (currentStep == 3 && (!lastStep)) // add orginator to the last step - //{ - // int isITARCompliant = 1; - // ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - // wfDMO.AddAdditionalApproval(workRequestID, ltWR.OriginatorID.ToString(), currentStep, documentType); - //} - - NotifyApprovers(workRequestID, currentStep, documentType); - } - - if (lastApprover && lastStep) - { - // Send email to the Originator and different groups - NotifyApprovalOfWorkRequest(workRequestID); - } - - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw new Exception(e.Message); - } - - } - - /// - /// - /// - /// - /// - /// - /// - public void Reject(int workRequestID, byte currentStep, string comments, int docType) - { - LTWorkRequest ltWR = new LTWorkRequest(); - int isITARCompliant = 1; - ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - try - { - - if (Session[GlobalVars.SESSION_USERID] != null) - { - wfDMO.Reject(workRequestID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); - NotifyRejectionToOrginator(workRequestID); - } + if ((int)Session[GlobalVars.SESSION_USERID] == ltWR.OriginatorID) + ViewBag.IsOriginator = "true"; else - { + ViewBag.IsOriginator = "false"; - Response.Redirect("~/Account/Login"); - } + if (Request.IsAjaxRequest()) { + // the content gets evaluated on the client side + return Content("Redirect"); + } else + return Content("Invalid"); + + //return View(ltWR); } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Reject\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Reject - " + exceptionString }); - throw new Exception(e.Message); - - } - + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + throw new Exception(e.Message); } + } - // TODO ====================================== + public void Approve(int workRequestID, byte currentStep, string comments, int documentType) { + LTWorkRequest ltWR = new LTWorkRequest(); + int isITAR = 1; + ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITAR, (int)Session[GlobalVars.SESSION_USERID]); + try { + bool lastStep = false; + bool lastApprover = wfDMO.Approve(_AppSettings, workRequestID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType, ltWR.WorkFlowNumber); - /// - /// - /// - /// - public void NotifyRejectionToOrginator(int workRequestID) - { + while (lastApprover && !lastStep) { + currentStep++; + lastApprover = wfDMO.Approve(_AppSettings, workRequestID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType, ltWR.WorkFlowNumber); - List emailIst = LotTravDMO.GetRejectionOrginatorEmailList(workRequestID).Distinct().ToList(); - int isITARCompliant = 0; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + //if (currentStep == 3 && (!lastStep)) // add orginator to the last step + //{ + // int isITARCompliant = 1; + // ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + // wfDMO.AddAdditionalApproval(workRequestID, ltWR.OriginatorID.ToString(), currentStep, documentType); + //} - string emailTemplate = "WorkRequestReject.txt"; - string userEmail = string.Empty; - string subject = "Work Request Rejection"; - string senderName = "Work Request"; - - foreach (string email in emailIst) - { - subject = "Work Request Rejection notice for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = ltWR.SWRNumber.ToString(); - emailparams[1] = workRequestID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString(); - emailparams[4] = "Work Request"; - userEmail = email; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif - - // en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - try - { - //emailSentList += email + ","; - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - - } - catch - { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Lot Traveler Notify Rejection:" + email }); - } + NotifyApprovers(workRequestID, currentStep, documentType); } - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Rejection: " + userEmail }); + if (lastApprover && lastStep) { + // Send email to the Originator and different groups + NotifyApprovalOfWorkRequest(workRequestID); } - catch { } + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw new Exception(e.Message); } + } - /// - /// - /// - /// - /// - /// - /// - public void NotifyApprovers(int workRequestID, byte currentStep, int documentType) - { - string emailSentList = ""; - int isITARCompliant = 0; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - - List emailIst = MiscDMO.GetApproverEmailListByDocument(workRequestID, currentStep, documentType).Distinct().ToList(); - - string emailTemplate = "WorkRequestAssigned.txt"; - string userEmail = string.Empty; - string subject = "Work Request Assignment"; - var senderName = ""; - - - foreach (string email in emailIst) - { - subject = "Work Request Assignment notice for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = ltWR.SWRNumber.ToString(); - emailparams[1] = workRequestID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = "Work Request"; - userEmail = email; -#if(DEBUG) - userEmail = "rkotian1@irf.com"; -#endif - - //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - //emailSentList += email + ","; - try - { - emailSentList += email + ","; - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - - } - catch - { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WR Notify Approvers:" + email }); - } + public void Reject(int workRequestID, byte currentStep, string comments, int docType) { + LTWorkRequest ltWR = new LTWorkRequest(); + int isITARCompliant = 1; + ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + try { + if (Session[GlobalVars.SESSION_USERID] != null) { + wfDMO.Reject(workRequestID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); + NotifyRejectionToOrginator(workRequestID); + } else { + Response.Redirect("~/Account/Login"); } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); - } - catch { } - - - + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Reject\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Reject - " + exceptionString }); + throw new Exception(e.Message); } + } + // TODO ====================================== - /// - /// - /// - /// - /// - /// - public void NotifyApprovalOfWorkRequest(int workRequestID) - { - string emailSentList = ""; - int isITARCompliant = 0; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + public void NotifyRejectionToOrginator(int workRequestID) { + List emailIst = LotTravDMO.GetRejectionOrginatorEmailList(workRequestID).Distinct().ToList(); + int isITARCompliant = 0; + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - List emailIst = MiscDMO.GetWorkRequestApprovedNotifyList((int)GlobalVars.NotificationType.WorkRequest, workRequestID, (int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList(); - - string emailTemplate = "WorkRequestApproval.txt"; - string userEmail = string.Empty; - string subject = "Work Request Approval"; - var senderName = ""; + string emailTemplate = "WorkRequestReject.txt"; + string userEmail = string.Empty; + string subject = "Work Request Rejection"; + string senderName = "Work Request"; - - foreach (string email in emailIst) - { - subject = "Work Request Approval notice for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = ltWR.SWRNumber.ToString(); - emailparams[1] = workRequestID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = "Work Request"; - userEmail = email; -#if(DEBUG) - userEmail = "rkotian1@irf.com"; -#endif - - //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - //emailSentList += email + ","; - try - { - emailSentList += email + ","; - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - - } - catch - { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Lot Traveler Approval Notification:" + email }); - } - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Approvers for WorkRequest: " + emailSentList }); - } - catch { } - - - - } - - - /// - /// - /// - /// - public void NotifyfWorkRequestRevisionChange(int workRequestID) - { - string emailSentList = ""; - int isITARCompliant = 0; - int currentUserID = (int)Session[GlobalVars.SESSION_USERID]; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, currentUserID); - - List emailIst = MiscDMO.GetWorkRequestRevisionNotifyList((int)GlobalVars.NotificationType.WorkRequest, workRequestID, currentUserID).Distinct().ToList(); - - string emailTemplate = "WorkRequestRevisionChange.txt"; - string userEmail = string.Empty; - string subject = "Work Request Revision Change"; - var senderName = ""; - - - foreach (string email in emailIst) - { - subject = "Work Request Revision Change notice for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = ltWR.SWRNumber.ToString(); - emailparams[1] = workRequestID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = "Work Request"; - userEmail = email; -#if(DEBUG) - userEmail = "rkotian1@irf.com"; -#endif - - //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - //emailSentList += email + ","; - try - { - emailSentList += email + ","; - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - - } - catch - { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WR Revision Change Notification:" + email }); - } - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Work Request Revision Change for :" + emailSentList }); - } - catch { } - - - - } - - /// - /// - /// - /// - public void NotifyLotTravelerRevisionChange(int ltLotID, int revisionNumber) - { - string emailSentList = ""; - var data = LotTravDMO.GetLotTravelerHeaderForReadOnly(ltLotID, revisionNumber); - int currentUserID = (int)Session[GlobalVars.SESSION_USERID]; - List emailIst = MiscDMO.GetLotTravelerCreationAndRevisionNotifyList(ltLotID, data.LTWorkRequestID, currentUserID).Distinct().ToList(); - - string emailTemplate = "LotTravelerRevisionChange.txt"; - string userEmail = string.Empty; - string subject = "Lot Traveler Revision Change"; - var senderName = ""; - - - foreach (string email in emailIst) - { - subject = "Lot Traveler Revision for SWR# " + data.SWRNumber + ", Lot# " + data.LotNumber + " - " + data.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = data.SWRNumber.ToString(); - emailparams[1] = data.LTWorkRequestID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = data.LotNumber; - userEmail = email; -#if(DEBUG) - userEmail = "rkotian1@irf.com"; -#endif - - //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - //emailSentList += email + ","; - try - { - emailSentList += email + ","; - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - - } - catch - { - EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Lot Traveler Revision Notification:" + email }); - } - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Email", Comments = "Lot Traveler Revision Change Notification:" + emailSentList }); - } - catch { } - - - - } - - - /// - /// - /// - /// - /// - public void NotifyLotTravelerCreation(int ltLotID, int revisionNumber) - { - string emailSentList = ""; - var data = LotTravDMO.GetLotTravelerHeaderForReadOnly(ltLotID, revisionNumber); - int currentUserID = (int)Session[GlobalVars.SESSION_USERID]; - List emailIst = MiscDMO.GetLotTravelerCreationAndRevisionNotifyList(ltLotID, data.LTWorkRequestID, currentUserID).Distinct().ToList(); - - string emailTemplate = "LotTravelerCreation.txt"; - string userEmail = string.Empty; - string subject = "Lot Traveler Revision Change"; - var senderName = ""; - - - foreach (string email in emailIst) - { - subject = "Lot Traveler created for SWR# " + data.SWRNumber + ", Lot# " + data.LotNumber + " - " + data.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = data.SWRNumber.ToString(); - emailparams[1] = data.LTWorkRequestID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = data.LotNumber; - userEmail = email; -#if(DEBUG) - userEmail = "rkotian1@irf.com"; -#endif - try - { - emailSentList += email + ","; - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - - } - catch - { - EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Lot Traveler Creation Email Notification:" + email }); - } - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Email", Comments = "Lot Traveler Revision Change Notification:" + emailSentList }); - } - catch { } - - - - } - - - - - - /// - /// - /// - /// - /// - /// - /// - public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int workRequestID, byte step) - { - - return Json(MiscDMO.GetApproversListByDocument(workRequestID, step, (int)GlobalVars.DocumentType.LotTraveler).ToDataSourceResult(request)); - } - - /// - /// - /// - /// - public void ReleaseLockOnDocument(int workRequestID) - { - LotTravDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], workRequestID); - - } - - /// - /// - /// - /// - public void ReleaseLockOnLotTravelerUpdateDoc(int lotID) - { - try - { - LotTravDMO.ReleaseLockOnLotTravelerUpdateDoc((int)Session[GlobalVars.SESSION_USERID], lotID); - } - catch - { - //TODO - // unlock the current revision of the Lot traveler - LotTravDMO.ReleaseLockOnLotTravelerUpdateDoc(-1, lotID); - } - - } - - - - /// - /// - /// - /// - public JsonResult GetAllUsersList() - { - //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep); - //return Json(userList, JsonRequestBehavior.AllowGet); - - UserAccountDMO userDMO = new UserAccountDMO(); - IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); - - } - - /// - /// - /// - /// - /// - /// - /// - /// - public void ReAssignApproverByAdmin(int workRequestID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType) - { - var email = ""; - int isITARCompliant = 0; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - try - { - - email = wfDMO.ReAssignApproval(workRequestID, reAssignApproverFrom, reAssignApproverTo, step, docType); - - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); - throw new Exception(e.Message); - - } - - - string emailTemplate = "WorkRequestReAssigned.txt"; - string userEmail = string.Empty; - string subject; - string senderName = "Work Request"; - - subject = "Work Request Re-Assignment" + " - Email would be sent to " + email + " for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; ; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = ltWR.SWRNumber.ToString(); - emailparams[1] = workRequestID.ToString(); // goes into the link + foreach (string email in emailIst) { + subject = "Work Request Rejection notice for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; + emailparams[0] = ltWR.SWRNumber.ToString(); + emailparams[1] = workRequestID.ToString(); emailparams[2] = GlobalVars.hostURL; - emailparams[3] = "Work Request"; - + emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString(); + emailparams[4] = "Work Request"; userEmail = email; //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; + // userEmail = "rkotian1@irf.com"; //#endif - //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - - try - { + // en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + try { //emailSentList += email + ","; - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + } catch { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Lot Traveler Notify Rejection:" + email }); } - catch - { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "ReAssign Approver Notification:" + email }); - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "ReAssign Approver: " + email }); - } - catch { } - } + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Rejection: " + userEmail }); + } catch { } + } - /// - /// - /// - /// - /// - /// - /// - - public void ReAssignApproval(int workRequestID, int userIDs, byte step, int docType) - { - var email = ""; - int isITARCompliant = 0; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - try - { - email = wfDMO.ReAssignApproval(workRequestID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, docType); + public void NotifyApprovers(int workRequestID, byte currentStep, int documentType) { + string emailSentList = ""; + int isITARCompliant = 0; + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); - throw new Exception(e.Message); + List emailIst = MiscDMO.GetApproverEmailListByDocument(workRequestID, currentStep, documentType).Distinct().ToList(); - } + string emailTemplate = "WorkRequestAssigned.txt"; + string userEmail = string.Empty; + string subject = "Work Request Assignment"; + var senderName = ""; - - - string emailTemplate = "WorkRequestReAssigned.txt"; - string userEmail = string.Empty; - string subject = "Work Request Re-Assignment"; - string senderName = "Work Request"; - - subject = "Work Request Re-Assignment" + " - Email would be sent to " + email + " for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; ; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + foreach (string email in emailIst) { + subject = "Work Request Assignment notice for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); string[] emailparams = new string[4]; emailparams[0] = ltWR.SWRNumber.ToString(); emailparams[1] = workRequestID.ToString(); emailparams[2] = GlobalVars.hostURL; emailparams[3] = "Work Request"; userEmail = email; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif +#if (DEBUG) + userEmail = "rkotian1@irf.com"; +#endif //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - try - { - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + //emailSentList += email + ","; + try { + emailSentList += email + ","; + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + } catch { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WR Notify Approvers:" + email }); } - catch - { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "ReAssign Approval Notification:" + email }); - } - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "ReAssign Approver: " + email }); - } - catch { } - } - /// - /// - /// - /// - /// - /// - /// - /// - public void AddAdditionalApproval(int workRequestID, byte step, string userIDs, int docType) - { - string emailSentList = ""; - var emailArray = ""; - int isITARCompliant = 0; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - try - { - emailArray = wfDMO.AddAdditionalApproval(workRequestID, userIDs, step, docType); + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + } catch { } + } + + public void NotifyApprovalOfWorkRequest(int workRequestID) { + string emailSentList = ""; + int isITARCompliant = 0; + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + + List emailIst = MiscDMO.GetWorkRequestApprovedNotifyList((int)GlobalVars.NotificationType.WorkRequest, workRequestID, (int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList(); + + string emailTemplate = "WorkRequestApproval.txt"; + string userEmail = string.Empty; + string subject = "Work Request Approval"; + var senderName = ""; + + foreach (string email in emailIst) { + subject = "Work Request Approval notice for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = ltWR.SWRNumber.ToString(); + emailparams[1] = workRequestID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = "Work Request"; + userEmail = email; +#if (DEBUG) + userEmail = "rkotian1@irf.com"; +#endif + + //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + //emailSentList += email + ","; + try { + emailSentList += email + ","; + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + + } catch { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Lot Traveler Approval Notification:" + email }); } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw new Exception(e.Message); + } + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Approvers for WorkRequest: " + emailSentList }); + } catch { } + } + + public void NotifyfWorkRequestRevisionChange(int workRequestID) { + string emailSentList = ""; + int isITARCompliant = 0; + int currentUserID = (int)Session[GlobalVars.SESSION_USERID]; + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, currentUserID); + + List emailIst = MiscDMO.GetWorkRequestRevisionNotifyList((int)GlobalVars.NotificationType.WorkRequest, workRequestID, currentUserID).Distinct().ToList(); + + string emailTemplate = "WorkRequestRevisionChange.txt"; + string userEmail = string.Empty; + string subject = "Work Request Revision Change"; + var senderName = ""; + + foreach (string email in emailIst) { + subject = "Work Request Revision Change notice for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = ltWR.SWRNumber.ToString(); + emailparams[1] = workRequestID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = "Work Request"; + userEmail = email; +#if (DEBUG) + userEmail = "rkotian1@irf.com"; +#endif + + //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + //emailSentList += email + ","; + try { + emailSentList += email + ","; + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + + } catch { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WR Revision Change Notification:" + email }); } - - + } - string emailTemplate = "WorkRequestAssigned.txt"; - string userEmail = string.Empty; - string subject = "Work Request Assignment"; - string senderName = "Work Request"; + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Work Request Revision Change for :" + emailSentList }); + } catch { } + } + public void NotifyLotTravelerRevisionChange(int ltLotID, int revisionNumber) { + string emailSentList = ""; + var data = LotTravDMO.GetLotTravelerHeaderForReadOnly(ltLotID, revisionNumber); + int currentUserID = (int)Session[GlobalVars.SESSION_USERID]; + List emailIst = MiscDMO.GetLotTravelerCreationAndRevisionNotifyList(ltLotID, data.LTWorkRequestID, currentUserID).Distinct().ToList(); - string[] emailIst = emailArray.Split(new char[] { '~' }); - foreach (string email in emailIst) - { - if (email.Length > 0) - { - //subject = "Lot Disposition Assignment" + " - Email would be sent to " + email; - subject = "Work Request Assignment notice for Number " + workRequestID + ", - " + ltWR.Title; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[4]; - emailparams[0] = ltWR.SWRNumber.ToString(); - emailparams[1] = workRequestID.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = "Work Request"; + string emailTemplate = "LotTravelerRevisionChange.txt"; + string userEmail = string.Empty; + string subject = "Lot Traveler Revision Change"; + var senderName = ""; - userEmail = email; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif + foreach (string email in emailIst) { + subject = "Lot Traveler Revision for SWR# " + data.SWRNumber + ", Lot# " + data.LotNumber + " - " + data.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = data.SWRNumber.ToString(); + emailparams[1] = data.LTWorkRequestID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = data.LotNumber; + userEmail = email; +#if (DEBUG) + userEmail = "rkotian1@irf.com"; +#endif - //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - //emailSentList += email + ","; - try - { - emailSentList += email + ","; - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + //emailSentList += email + ","; + try { + emailSentList += email + ","; + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - } - catch - { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Addtional Approver Notification:" + email }); - } + } catch { + EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Lot Traveler Revision Notification:" + email }); + } + } + try { + EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Email", Comments = "Lot Traveler Revision Change Notification:" + emailSentList }); + } catch { } + } + + public void NotifyLotTravelerCreation(int ltLotID, int revisionNumber) { + string emailSentList = ""; + var data = LotTravDMO.GetLotTravelerHeaderForReadOnly(ltLotID, revisionNumber); + int currentUserID = (int)Session[GlobalVars.SESSION_USERID]; + List emailIst = MiscDMO.GetLotTravelerCreationAndRevisionNotifyList(ltLotID, data.LTWorkRequestID, currentUserID).Distinct().ToList(); + + string emailTemplate = "LotTravelerCreation.txt"; + string userEmail = string.Empty; + string subject = "Lot Traveler Revision Change"; + var senderName = ""; + + foreach (string email in emailIst) { + subject = "Lot Traveler created for SWR# " + data.SWRNumber + ", Lot# " + data.LotNumber + " - " + data.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = data.SWRNumber.ToString(); + emailparams[1] = data.LTWorkRequestID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = data.LotNumber; + userEmail = email; +#if (DEBUG) + userEmail = "rkotian1@irf.com"; +#endif + try { + emailSentList += email + ","; + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + + } catch { + EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Lot Traveler Creation Email Notification:" + email }); + } + } + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Email", Comments = "Lot Traveler Revision Change Notification:" + emailSentList }); + } catch { } + } + + public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int workRequestID, byte step) { + return Json(MiscDMO.GetApproversListByDocument(workRequestID, step, (int)GlobalVars.DocumentType.LotTraveler).ToDataSourceResult(request)); + } + + public void ReleaseLockOnDocument(int workRequestID) { + LotTravDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], workRequestID); + } + + public void ReleaseLockOnLotTravelerUpdateDoc(int lotID) { + try { + LotTravDMO.ReleaseLockOnLotTravelerUpdateDoc((int)Session[GlobalVars.SESSION_USERID], lotID); + } catch { + //TODO + // unlock the current revision of the Lot traveler + LotTravDMO.ReleaseLockOnLotTravelerUpdateDoc(-1, lotID); + } + } + + public JsonResult GetAllUsersList() { + //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep); + //return Json(userList, JsonRequestBehavior.AllowGet); + + UserAccountDMO userDMO = new UserAccountDMO(); + IEnumerable userlist = userDMO.GetAllUsers(); + return Json(userlist, JsonRequestBehavior.AllowGet); + } + + public void ReAssignApproverByAdmin(int workRequestID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType) { + var email = ""; + int isITARCompliant = 0; + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + try { + email = wfDMO.ReAssignApproval(workRequestID, reAssignApproverFrom, reAssignApproverTo, step, docType); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + throw new Exception(e.Message); + } + + string emailTemplate = "WorkRequestReAssigned.txt"; + string userEmail = string.Empty; + string subject; + string senderName = "Work Request"; + + subject = "Work Request Re-Assignment" + " - Email would be sent to " + email + " for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; + ; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = ltWR.SWRNumber.ToString(); + emailparams[1] = workRequestID.ToString(); // goes into the link + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = "Work Request"; + + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + + try { + //emailSentList += email + ","; + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + } catch { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "ReAssign Approver Notification:" + email }); + } + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + } catch { } + } + + public void ReAssignApproval(int workRequestID, int userIDs, byte step, int docType) { + var email = ""; + int isITARCompliant = 0; + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + try { + email = wfDMO.ReAssignApproval(workRequestID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, docType); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + throw new Exception(e.Message); + } + + string emailTemplate = "WorkRequestReAssigned.txt"; + string userEmail = string.Empty; + string subject = "Work Request Re-Assignment"; + string senderName = "Work Request"; + + subject = "Work Request Re-Assignment" + " - Email would be sent to " + email + " for Number " + ltWR.SWRNumber + ", - " + ltWR.Title; + ; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = ltWR.SWRNumber.ToString(); + emailparams[1] = workRequestID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = "Work Request"; + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + try { + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + } catch { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "ReAssign Approval Notification:" + email }); + } + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + } catch { } + } + + public void AddAdditionalApproval(int workRequestID, byte step, string userIDs, int docType) { + string emailSentList = ""; + var emailArray = ""; + int isITARCompliant = 0; + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + try { + emailArray = wfDMO.AddAdditionalApproval(workRequestID, userIDs, step, docType); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw new Exception(e.Message); + } + + string emailTemplate = "WorkRequestAssigned.txt"; + string userEmail = string.Empty; + string subject = "Work Request Assignment"; + string senderName = "Work Request"; + + string[] emailIst = emailArray.Split(new char[] { '~' }); + foreach (string email in emailIst) { + if (email.Length > 0) { + //subject = "Lot Disposition Assignment" + " - Email would be sent to " + email; + subject = "Work Request Assignment notice for Number " + workRequestID + ", - " + ltWR.Title; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[4]; + emailparams[0] = ltWR.SWRNumber.ToString(); + emailparams[1] = workRequestID.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = "Work Request"; + + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + //en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + //emailSentList += email + ","; + try { + emailSentList += email + ","; + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + + } catch { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Addtional Approver Notification:" + email }); } } - try - { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); - } - catch { } - } - /// - /// - /// - /// - /// - /// - public JsonResult AddLots(string lotNumbers, int workRequestID) - { - IssueWithExistingLotsViewModel issueWEL = new IssueWithExistingLotsViewModel(); - try - { - if (lotNumbers.Length > 0) - { - string[] tempLots = lotNumbers.Split(new char[] { '~' }); - foreach (string lotNumber in tempLots) - { - LTLot l = new LTLot(); - l.LotNumber = lotNumber; - l.WorkRequestID = workRequestID; - l.LotUploadedBy = (int)Session[GlobalVars.SESSION_USERID]; - LotTravDMO.InsertLot(l); - if (l.WRWithExistingLot != 0) - { - issueWEL.LotList += l.LotNumber + "~"; - issueWEL.IssuesList += l.WRWithExistingLot.ToString() + "~"; - } + } + try { + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); + } catch { } + } + + public JsonResult AddLots(string lotNumbers, int workRequestID) { + IssueWithExistingLotsViewModel issueWEL = new IssueWithExistingLotsViewModel(); + try { + if (lotNumbers.Length > 0) { + string[] tempLots = lotNumbers.Split(new char[] { '~' }); + foreach (string lotNumber in tempLots) { + LTLot l = new LTLot(); + l.LotNumber = lotNumber; + l.WorkRequestID = workRequestID; + l.LotUploadedBy = (int)Session[GlobalVars.SESSION_USERID]; + LotTravDMO.InsertLot(l); + if (l.WRWithExistingLot != 0) { + issueWEL.LotList += l.LotNumber + "~"; + issueWEL.IssuesList += l.WRWithExistingLot.ToString() + "~"; } } - - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + workRequestID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AddLots Work Request\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - } - return Json(issueWEL, JsonRequestBehavior.AllowGet); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + workRequestID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddLots Work Request\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); } - /// - /// - /// - /// - /// - /// - public JsonResult SearchLots(string searchText, string searchBy) - { - List lotlist = MiscDMO.SearchLTLots(searchText, searchBy).Select(x => x.LotNumber).ToList(); + return Json(issueWEL, JsonRequestBehavior.AllowGet); + } - //IEnumerable lotlist = MiscDMO.SearchLots(searchText, searchBy); + public JsonResult SearchLots(string searchText, string searchBy) { + List lotlist = MiscDMO.SearchLTLots(searchText, searchBy).Select(x => x.LotNumber).ToList(); - return Json(lotlist, JsonRequestBehavior.AllowGet); - } + //IEnumerable lotlist = MiscDMO.SearchLots(searchText, searchBy); - /// - /// - /// - /// - /// - public JsonResult SearchParts(string searchText) - { - List partList = MiscDMO.SearchLTParts(searchText.Trim()).Select(x => x.WIPPartData).ToList(); - return Json(partList, JsonRequestBehavior.AllowGet); - } + return Json(lotlist, JsonRequestBehavior.AllowGet); + } - /// - /// - /// - /// - /// - /// - public ActionResult GetLotList([DataSourceRequest] DataSourceRequest request,int workRequestID) - { - return Json(LotTravDMO.GetLotList(workRequestID).ToDataSourceResult(request)); - } + public JsonResult SearchParts(string searchText) { + List partList = MiscDMO.SearchLTParts(searchText.Trim()).Select(x => x.WIPPartData).ToList(); + return Json(partList, JsonRequestBehavior.AllowGet); + } - /// - /// - /// - /// - /// - public void CreateTaveler(int ltLotID, int workRequestID) - { - try - { - LotTravDMO.CreateTraveler(ltLotID, workRequestID, (int)Session[GlobalVars.SESSION_USERID]); - - // Thread.Sleep(10000); + public ActionResult GetLotList([DataSourceRequest] DataSourceRequest request, int workRequestID) { + return Json(LotTravDMO.GetLotList(workRequestID).ToDataSourceResult(request)); + } + + public void CreateTaveler(int ltLotID, int workRequestID) { + try { + LotTravDMO.CreateTraveler(ltLotID, workRequestID, (int)Session[GlobalVars.SESSION_USERID]); + + // Thread.Sleep(10000); NotifyLotTravelerCreation(ltLotID, -1); + } catch (Exception ex) { + EventLogDMO.Add(new WinEventLog() { IssueID = workRequestID, UserID = @User.Identity.Name, DocumentType = "LotTraveler", OperationType = "CreateTaveler", Comments = ex.Message }); + throw new Exception(ex.Message); + } + } - } - catch(Exception ex) - { - EventLogDMO.Add(new WinEventLog() { IssueID = workRequestID, UserID = @User.Identity.Name, DocumentType = "LotTraveler", OperationType = "CreateTaveler", Comments = ex.Message }); - throw new Exception(ex.Message); - } + public JsonResult GetLotTravelerHeader(int ltLotID) { + LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); + data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); + //data.Revisions = LotTravDMO.GetLotTravRevisions(ltLotID).Select(s => new SelectListItem { Value = s.ID.ToString(), Text = s.RevisionNumber.ToString() }).ToList(); + return Json(data, JsonRequestBehavior.AllowGet); + } + public ActionResult GetLotTravRevisions(int ltLotID) { + //return Json(LotTravDMO.GetLotTravRevisions(ltLotID).ToDataSourceResult(request)); + return Json(LotTravDMO.GetLotTravRevisions(ltLotID), JsonRequestBehavior.AllowGet); + } + public ActionResult DisplayLotTraveler(int ltLotID) { + LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); + data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); + + ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); + ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); + + if (data.RecordLockIndicator && data.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) { + // redirect to a readonly Lot Travler + return Content("Readonly" + "~" + data.LotTravCurrentRevision.ToString()); + } else + return Content("Update"); + } + + public ActionResult LotTravelerUpdate(int ltLotID) { + + LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); + data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); + + if (data.TravelerClosedDate != null) { + return RedirectToAction("LotTravelerReadOnly", new { ltLotID = ltLotID, revisionNumber = -1 }); } + ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); + ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); - /// - /// - /// - /// - /// - public JsonResult GetLotTravelerHeader(int ltLotID) - { - LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); - data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); - //data.Revisions = LotTravDMO.GetLotTravRevisions(ltLotID).Select(s => new SelectListItem { Value = s.ID.ToString(), Text = s.RevisionNumber.ToString() }).ToList(); - return Json(data, JsonRequestBehavior.AllowGet); + Session["CreateLotTravNewRevision"] = "true"; + return View(data); + } + + /// + /// / + /// + public ActionResult LotTravelerReadonly(int ltLotID, int revisionNumber) { + LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); + data = LotTravDMO.GetLotTravelerHeaderForReadOnly(ltLotID, revisionNumber); + + if (data.IsCurrentRevision && (!data.RecordLockIndicator)) { + return RedirectToAction("LotTravelerUpdate", new { ltLotID = ltLotID }); } - - /// - /// - /// - /// - /// - /// - public ActionResult GetLotTravRevisions(int ltLotID) - { - //return Json(LotTravDMO.GetLotTravRevisions(ltLotID).ToDataSourceResult(request)); - return Json(LotTravDMO.GetLotTravRevisions(ltLotID), JsonRequestBehavior.AllowGet); - } - - - /// - /// - /// - /// - /// - public ActionResult DisplayLotTraveler(int ltLotID) - { - LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); - data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); - - ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); - ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); - - if (data.RecordLockIndicator && data.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) - { - // redirect to a readonly Lot Travler - return Content("Readonly" + "~" + data.LotTravCurrentRevision.ToString()); - } - else - return Content("Update"); - - } - - - /// - /// - /// - /// - /// - public ActionResult LotTravelerUpdate(int ltLotID) - { - - LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); - data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); - - if (data.TravelerClosedDate != null) - { - return RedirectToAction("LotTravelerReadOnly", new { ltLotID = ltLotID, revisionNumber = -1 }); - } - - ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); - ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); - - Session["CreateLotTravNewRevision"] = "true"; - return View(data); - - } - - /// - /// / - /// - /// - /// - /// - public ActionResult LotTravelerReadonly(int ltLotID, int revisionNumber) - { - LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); - data = LotTravDMO.GetLotTravelerHeaderForReadOnly(ltLotID, revisionNumber); - - if (data.IsCurrentRevision && (!data.RecordLockIndicator)) - { - return RedirectToAction("LotTravelerUpdate", new { ltLotID = ltLotID }); - } - - ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); - ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); - return View(data); - - } - - - - public ActionResult DisplayLotTravelerForExecute(int ltLotID) - { - LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); - data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); - ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); - ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); - - if (data.RecordLockIndicator && data.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) - { - // redirect to a readonly Lot Travler - return Content("Readonly" + "~" + data.LotTravCurrentRevision.ToString()); - } - else - return Content("Execute"); - - } - - /// - /// - /// - /// - /// - public ActionResult LotTravelerExecute(int ltLotID) - { - - LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); - data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); - ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); - ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); - - - return View(data); - - } - - - public ActionResult GetLotTravHoldSteps([DataSourceRequest] DataSourceRequest request, int LotID) - { - return Json(LotTravDMO.GetLotTravHoldSteps(LotID).ToDataSourceResult(request)); - } - - - /// - /// - /// - /// - /// - /// - public ActionResult GetLotTravHoldStepsPending([DataSourceRequest] DataSourceRequest request, int LotID) - { - return Json(LotTravDMO.GetLotTravHoldStepsPending(LotID).ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - /// - public ActionResult GetLotTravHoldStepsCompleted([DataSourceRequest] DataSourceRequest request, int LotID) - { - return Json(LotTravDMO.GetLotTravHoldStepsCompleted(LotID).ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - /// - public void UpdateLotTravlerExecution(int currentHoldStepID, string taskComments, bool taskcompleted) - { - LotTravDMO.UpdateLotTravlerExecution(currentHoldStepID, taskComments, taskcompleted, (int)Session[GlobalVars.SESSION_USERID]); - - } - - /// - /// - /// - /// - /// - /// - /// - public ActionResult GetLotTravHoldStepsByRevision([DataSourceRequest] DataSourceRequest request, int LotID, int revisionNumber) - { - return Json(LotTravDMO.GetLotTravelerHolStepsByRevision(LotID, revisionNumber).ToDataSourceResult(request)); - } - - /// - /// - /// - /// - public ActionResult UpdateLotTravHoldStepRevision(LTLotTravelerHoldSteps ltHoldStepObj) - { - int prevLotTravRevID = ltHoldStepObj.LotTravelerRevisionID; - int newLotTravRevID = 1; - try - { - if (Session["CreateLotTravNewRevision"].ToString() == "true") - { - // Create a new Revision - Session["CreateLotTravNewRevision"] = "false"; - - //int result = LotTravDMO.CanAddLocationOperation(ltHoldStepObj); - //if (result == -1) - //{ - // Session["CreateLotTravNewRevision"] = "true"; - // throw new Exception("Cannot set to this Hold Step as the step has already been passed in the Mfg Process."); - //} - - newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); - - try - { - - LotTravDMO.UpdateRevisedLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); - } - catch - { - - LotTravDMO.RestoreLotTravToPrevRevision(prevLotTravRevID, newLotTravRevID); - throw new Exception("There was a problem while creating the revision, Please try againm,. \n If the problem persist please contact the Site Administrator"); - } - - // send a notification - // - 1 indicates to return the current revision - NotifyLotTravelerRevisionChange(ltHoldStepObj.LTLotID, -1); - } - else - { - int result = LotTravDMO.UpdateLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); - if (result == -1) - { - throw new Exception("Cannot add the Hold Step as the step has already been passed in the Mfg Process."); - } - } - } - catch (Exception ex) - { - return Content(ex.Message); - } - - return Content(GlobalVars.SUCCESS); - } - - /// - /// - /// - /// - public ActionResult InsertLotTravHoldStepRevision(LTLotTravelerHoldSteps ltHoldStepObj) - { - int prevLotTravRevID = ltHoldStepObj.LotTravelerRevisionID; - int newLotTravRevID = -1; - try - { - if (Session["CreateLotTravNewRevision"].ToString() == "true") - { - // Create a new Revision - Session["CreateLotTravNewRevision"] = "false"; - - int result = LotTravDMO.CanAddLocationOperation(ltHoldStepObj); - if (result == -1) - { - Session["CreateLotTravNewRevision"] = "true"; - throw new Exception("Cannot add the Hold Step as the step has already been passed in the Mfg Process."); - } - newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); - ltHoldStepObj.LotTravelerRevisionID = newLotTravRevID; - - try - { - - LotTravDMO.InsertLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); - } - catch - { - //roll back the revision creation - LotTravDMO.RestoreLotTravToPrevRevision(prevLotTravRevID, newLotTravRevID); - throw new Exception("There was a problem while creating the revision, Please logout and log back and then retry. \n If the problem persist please contact the Site Administrator"); - } - - - // send a notification - // - 1 indicates to return the current revision - NotifyLotTravelerRevisionChange(ltHoldStepObj.LTLotID, -1); - - - } - else - { - int result = LotTravDMO.InsertLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); - if (result == -1) - { - throw new Exception("Cannot add the Hold Step as the step has already been passed in the Mfg Process."); - } - } - } - catch (Exception ex) - { - return Content(ex.Message); - } - - return Content(GlobalVars.SUCCESS); - } - - /// - /// - /// - /// - public ActionResult DeleteLotTravHoldStepRevision(LTLotTravelerHoldSteps ltHoldStepObj) - { - int prevLotTravRevID = ltHoldStepObj.LotTravelerRevisionID; - int newLotTravRevID = -1; - try - { - //int newLotTravRevisionAttribID = 0; - if (Session["CreateLotTravNewRevision"].ToString() == "true") - { - // Create a new Revision - Session["CreateLotTravNewRevision"] = "false"; - newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); - - try - { - LotTravDMO.DeleteLotTravHoldStepRevision(ltHoldStepObj.ID); - } - catch - { - //roll back the revision creation - LotTravDMO.RestoreLotTravToPrevRevision(prevLotTravRevID, newLotTravRevID); - throw new Exception("There was a problem while creating the revision, Please logout and log back and then retry. \n If the problem persist please contact the Site Administrator"); - } - - - - // send a notification - // - 1 indicates to return the current revision - NotifyLotTravelerRevisionChange(ltHoldStepObj.LTLotID, -1); - } - else - { - LotTravDMO.DeleteLotTravHoldStep(ltHoldStepObj.ID); - } - } - catch(Exception ex) - { - return Content(ex.Message); - } - - - return Content(GlobalVars.SUCCESS); - } - - - /// - /// - /// - /// - public void DeleteLot(int ltLotID) - { - LotTravDMO.DeleteLot(ltLotID); - } - - /// - public ActionResult DisplayLotTravlerPdf(int ltLotID, int revisionNumber) - { - //DateTime? expDt; - LotTravelerPdf traveler = new LotTravelerPdf(); - try - { - - traveler = LotTravDMO.GetLotTravlerPdf(ltLotID, revisionNumber); - - // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This - // requires the controller to be inherited from MyController instead of MVC's Controller. - return this.ViewPdf("", "LotTravelerPDF", traveler); - - } - catch (Exception ex) - { - EventLogDMO.Add(new WinEventLog() { IssueID = traveler.SWRNumber, UserID = @User.Identity.Name, DocumentType = "LotTraveler", OperationType = "Generate PDF", Comments = ex.Message }); - traveler = null; - return Content(""); - - } - - - } - - /// - /// - /// - /// - /// - /// - public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int swrNumber) - { - return Json(LotTravDMO.GetWorkReqApprovalLogHistory(swrNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - - /// - /// - /// - /// - /// - /// - public ActionResult GetWorkRequestRevisionHistory([DataSourceRequest] DataSourceRequest request, int swrNumber) - { - return Json(LotTravDMO.GetWorkReqRevisionHistory(swrNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - - - - /// - /// - /// - /// - /// - /// - public ActionResult GetLotTravelerRevisionHistory([DataSourceRequest] DataSourceRequest request, int lotID) - { - return Json(LotTravDMO.GetLotTravelerRevisionHistory(lotID).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - - - - /// - /// - /// - /// - /// - /// - /// - /// - /// - public ActionResult LotTravHoldStepAttachSaveRev(IEnumerable LotTravHoldStepAttachment, int ltHoldStepID, int swrNo, string docType, string revComments) - { - // The Name of the Upload component is "files" - - int prevLotTravRevID = -1 ; - int newLotTravRevID = -1; - - bool newRevision = false; - LTLotTravelerHoldSteps model = LotTravDMO.GetLotTravHoldStep(ltHoldStepID); - prevLotTravRevID = model.LotTravelerRevisionID; - - model.RevisionComments = revComments; - - if (Session["CreateLotTravNewRevision"].ToString() == "true") - { + ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); + ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); + return View(data); + } + + public ActionResult DisplayLotTravelerForExecute(int ltLotID) { + LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); + data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); + ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); + ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); + + if (data.RecordLockIndicator && data.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) { + // redirect to a readonly Lot Travler + return Content("Readonly" + "~" + data.LotTravCurrentRevision.ToString()); + } else + return Content("Execute"); + } + + public ActionResult LotTravelerExecute(int ltLotID) { + LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); + data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); + ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); + ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); + + return View(data); + } + + public ActionResult GetLotTravHoldSteps([DataSourceRequest] DataSourceRequest request, int LotID) { + return Json(LotTravDMO.GetLotTravHoldSteps(LotID).ToDataSourceResult(request)); + } + + public ActionResult GetLotTravHoldStepsPending([DataSourceRequest] DataSourceRequest request, int LotID) { + return Json(LotTravDMO.GetLotTravHoldStepsPending(LotID).ToDataSourceResult(request)); + } + + public ActionResult GetLotTravHoldStepsCompleted([DataSourceRequest] DataSourceRequest request, int LotID) { + return Json(LotTravDMO.GetLotTravHoldStepsCompleted(LotID).ToDataSourceResult(request)); + } + + public void UpdateLotTravlerExecution(int currentHoldStepID, string taskComments, bool taskcompleted) { + LotTravDMO.UpdateLotTravlerExecution(currentHoldStepID, taskComments, taskcompleted, (int)Session[GlobalVars.SESSION_USERID]); + } + + public ActionResult GetLotTravHoldStepsByRevision([DataSourceRequest] DataSourceRequest request, int LotID, int revisionNumber) { + return Json(LotTravDMO.GetLotTravelerHolStepsByRevision(LotID, revisionNumber).ToDataSourceResult(request)); + } + + public ActionResult UpdateLotTravHoldStepRevision(LTLotTravelerHoldSteps ltHoldStepObj) { + int prevLotTravRevID = ltHoldStepObj.LotTravelerRevisionID; + int newLotTravRevID = 1; + try { + if (Session["CreateLotTravNewRevision"].ToString() == "true") { // Create a new Revision - newRevision = true; Session["CreateLotTravNewRevision"] = "false"; - newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(model, (int)Session[GlobalVars.SESSION_USERID]); - model.LotTravelerRevisionID = newLotTravRevID; - - } + //int result = LotTravDMO.CanAddLocationOperation(ltHoldStepObj); + //if (result == -1) + //{ + // Session["CreateLotTravNewRevision"] = "true"; + // throw new Exception("Cannot set to this Hold Step as the step has already been passed in the Mfg Process."); + //} + newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); - try - { - if (LotTravHoldStepAttachment != null) - { - foreach (var file in LotTravHoldStepAttachment) - { - // Some browsers send file names with full path. - // We are only interested in the file name. + try { - // TODO - //int currentRevision = 1; - var fileName = Path.GetFileName(file.FileName); - var fileExtension = Path.GetExtension(file.FileName); - //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); - DirectoryInfo di; - var SWRPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo; - di = new DirectoryInfo(SWRPhysicalPath); - if (!di.Exists) - di.Create(); + LotTravDMO.UpdateRevisedLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + } catch { - //var SWR_RevPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision; - var SWR_RevPhysicalPath = Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo; - di = new DirectoryInfo(SWR_RevPhysicalPath); - if (!di.Exists) - di.Create(); + LotTravDMO.RestoreLotTravToPrevRevision(prevLotTravRevID, newLotTravRevID); + throw new Exception("There was a problem while creating the revision, Please try againm,. \n If the problem persist please contact the Site Administrator"); + } - var guid = Guid.NewGuid().ToString(); - //var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision + @"\", guid + fileExtension); - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"LotTraveler\" + swrNo + @"\", guid + fileExtension); - - - - file.SaveAs(physicalPath); - LTLotTravAttachment attach = new LTLotTravAttachment() - { - FileGUID = guid, - LTLotTravHoldStepID = ltHoldStepID, - LotTravelerRevisionID = newLotTravRevID, - FileName = fileName, - UploadedByID = (int)Session[GlobalVars.SESSION_USERID], - DocType = docType - }; - if (newRevision) - { - try - { - LotTravDMO.InsertLotTravLotHoldStepAttachmentRevision(attach); - } - catch - { - //roll back the revision creation - LotTravDMO.RestoreLotTravToPrevRevision(prevLotTravRevID, newLotTravRevID); - throw new Exception("There was a problem while creating the revision, Please logout and log back and then retry. \n If the problem persist please contact the Site Administrator"); - } - - - - } - else - LotTravDMO.InsertLotTravLotHoldStepAttachment(attach); - - } - - // send a notification - // - 1 indicates to return the current revision - if (newRevision) - { - NotifyLotTravelerRevisionChange(model.LTLotID, -1); - } + // send a notification + // - 1 indicates to return the current revision + NotifyLotTravelerRevisionChange(ltHoldStepObj.LTLotID, -1); + } else { + int result = LotTravDMO.UpdateLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + if (result == -1) { + throw new Exception("Cannot add the Hold Step as the step has already been passed in the Mfg Process."); } } - catch (Exception e) - { + } catch (Exception ex) { + return Content(ex.Message); + } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "LotTravHoldStep=" + ltHoldStepID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Attachment \r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltHoldStepID, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "Lot Traveler HoldStep Attachment - " + exceptionString }); - throw new Exception(e.Message); + return Content(GlobalVars.SUCCESS); + } + + public ActionResult InsertLotTravHoldStepRevision(LTLotTravelerHoldSteps ltHoldStepObj) { + int prevLotTravRevID = ltHoldStepObj.LotTravelerRevisionID; + int newLotTravRevID = -1; + try { + if (Session["CreateLotTravNewRevision"].ToString() == "true") { + // Create a new Revision + Session["CreateLotTravNewRevision"] = "false"; + + int result = LotTravDMO.CanAddLocationOperation(ltHoldStepObj); + if (result == -1) { + Session["CreateLotTravNewRevision"] = "true"; + throw new Exception("Cannot add the Hold Step as the step has already been passed in the Mfg Process."); + } + newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + ltHoldStepObj.LotTravelerRevisionID = newLotTravRevID; + + try { + + LotTravDMO.InsertLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + } catch { + //roll back the revision creation + LotTravDMO.RestoreLotTravToPrevRevision(prevLotTravRevID, newLotTravRevID); + throw new Exception("There was a problem while creating the revision, Please logout and log back and then retry. \n If the problem persist please contact the Site Administrator"); + } + + // send a notification + // - 1 indicates to return the current revision + NotifyLotTravelerRevisionChange(ltHoldStepObj.LTLotID, -1); + + } else { + int result = LotTravDMO.InsertLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + if (result == -1) { + throw new Exception("Cannot add the Hold Step as the step has already been passed in the Mfg Process."); + } } + } catch (Exception ex) { + return Content(ex.Message); + } - //var model = ldDMO.GetLotDispoAttachments(issueID); + return Content(GlobalVars.SUCCESS); + } + public ActionResult DeleteLotTravHoldStepRevision(LTLotTravelerHoldSteps ltHoldStepObj) { + int prevLotTravRevID = ltHoldStepObj.LotTravelerRevisionID; + int newLotTravRevID = -1; + try { + //int newLotTravRevisionAttribID = 0; + if (Session["CreateLotTravNewRevision"].ToString() == "true") { + // Create a new Revision + Session["CreateLotTravNewRevision"] = "false"; + newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + try { + LotTravDMO.DeleteLotTravHoldStepRevision(ltHoldStepObj.ID); + } catch { + //roll back the revision creation + LotTravDMO.RestoreLotTravToPrevRevision(prevLotTravRevID, newLotTravRevID); + throw new Exception("There was a problem while creating the revision, Please logout and log back and then retry. \n If the problem persist please contact the Site Administrator"); + } + + // send a notification + // - 1 indicates to return the current revision + NotifyLotTravelerRevisionChange(ltHoldStepObj.LTLotID, -1); + } else { + LotTravDMO.DeleteLotTravHoldStep(ltHoldStepObj.ID); + } + } catch (Exception ex) { + return Content(ex.Message); + } + + return Content(GlobalVars.SUCCESS); + } + + public void DeleteLot(int ltLotID) { + LotTravDMO.DeleteLot(ltLotID); + } + + /// + public ActionResult DisplayLotTravlerPdf(int ltLotID, int revisionNumber) { + //DateTime? expDt; + LotTravelerPdf traveler = new LotTravelerPdf(); + try { + traveler = LotTravDMO.GetLotTravlerPdf(ltLotID, revisionNumber); + + // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This + // requires the controller to be inherited from MyController instead of MVC's Controller. + return this.ViewPdf("", "LotTravelerPDF", traveler); + } catch (Exception ex) { + EventLogDMO.Add(new WinEventLog() { IssueID = traveler.SWRNumber, UserID = @User.Identity.Name, DocumentType = "LotTraveler", OperationType = "Generate PDF", Comments = ex.Message }); + traveler = null; return Content(""); } + } + public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int swrNumber) { + return Json(LotTravDMO.GetWorkReqApprovalLogHistory(swrNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } - /// - /// - /// - /// - /// - public bool IsWorkRequestDocLockedByUser(int workRequestID ) - { - int result = LotTravDMO.IsWorkRequestDocLockedByUser(workRequestID, (int)Session[GlobalVars.SESSION_USERID]); - if (result == 0) - return false; - else - return true; + public ActionResult GetWorkRequestRevisionHistory([DataSourceRequest] DataSourceRequest request, int swrNumber) { + return Json(LotTravDMO.GetWorkReqRevisionHistory(swrNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } + + public ActionResult GetLotTravelerRevisionHistory([DataSourceRequest] DataSourceRequest request, int lotID) { + return Json(LotTravDMO.GetLotTravelerRevisionHistory(lotID).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } + + public ActionResult LotTravHoldStepAttachSaveRev(IEnumerable LotTravHoldStepAttachment, int ltHoldStepID, int swrNo, string docType, string revComments) { + // The Name of the Upload component is "files" + + int prevLotTravRevID = -1; + int newLotTravRevID = -1; + + bool newRevision = false; + LTLotTravelerHoldSteps model = LotTravDMO.GetLotTravHoldStep(ltHoldStepID); + prevLotTravRevID = model.LotTravelerRevisionID; + + model.RevisionComments = revComments; + + if (Session["CreateLotTravNewRevision"].ToString() == "true") { + // Create a new Revision + newRevision = true; + Session["CreateLotTravNewRevision"] = "false"; + newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + model.LotTravelerRevisionID = newLotTravRevID; } - /// - /// - /// - /// - public ActionResult CloseTraveler(int ltLotID, string reason) - { - int result = LotTravDMO.CloseTraveler(ltLotID, (int)Session[GlobalVars.SESSION_USERID], reason); - - if (result == 1) - return Content("C"); - else - return Content("O"); - } - - - - /// - /// - /// - /// - /// - /// - public FileResult DownloadFile(string fileGuid, string swrNumber, int typeOfDoc) - { - - string fileName = LotTravDMO.GetFileName(fileGuid, typeOfDoc); - - string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); - - string ecnFolderPath = Functions.GetAttachmentFolder() + "LotTraveler\\" + swrNumber.ToString(); - var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); - - var FDir_AppData = Functions.GetAttachmentFolder(); - if (!sDocument.StartsWith(FDir_AppData)) - { - // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder - // and block requests outside like "../web.config" - throw new HttpException(403, "Forbidden"); - } - - if (!System.IO.File.Exists(sDocument)) - { - return null; - //throw new Exception("File not found"); - } - - return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); - } - - [HttpPost] - public void ReAssignOriginatorByAdmin(int workRequestID, string comments, int newOriginatorId) - { - if (Session[GlobalVars.IS_ADMIN] == null) - throw new Exception("Permission denied"); - - try - { - LotTravDMO.ReassignOriginator(workRequestID, newOriginatorId, comments, (int)Session[GlobalVars.SESSION_USERID]); - } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); + try { + if (LotTravHoldStepAttachment != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in LotTravHoldStepAttachment) { + LotTravDMO.LotTravHoldStepAttachSaveRev(ltHoldStepID, swrNo, docType, prevLotTravRevID, newLotTravRevID, newRevision, userId, file.FileName, file.InputStream); } - catch - { - detailedException = e.Message; + + // send a notification + // - 1 indicates to return the current revision + if (newRevision) { + NotifyLotTravelerRevisionChange(model.LTLotID, -1); } - string exceptionString = e.Message.ToString().Trim(); - if (exceptionString.Length > 450) exceptionString = exceptionString.Substring(0, 450); - Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignOriginatorByAdmin\r\n" + workRequestID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = workRequestID, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "ReAssignOriginatorByAdmin - " + exceptionString }); - throw new Exception(e.Message); } + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "LotTravHoldStep=" + ltHoldStepID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Attachment \r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltHoldStepID, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "Lot Traveler HoldStep Attachment - " + exceptionString }); + throw new Exception(e.Message); + } + + //var model = ldDMO.GetLotDispoAttachments(issueID); + + return Content(""); + } + + public bool IsWorkRequestDocLockedByUser(int workRequestID) { + int result = LotTravDMO.IsWorkRequestDocLockedByUser(workRequestID, (int)Session[GlobalVars.SESSION_USERID]); + if (result == 0) + return false; + else + return true; + } + + public ActionResult CloseTraveler(int ltLotID, string reason) { + int result = LotTravDMO.CloseTraveler(ltLotID, (int)Session[GlobalVars.SESSION_USERID], reason); + + if (result == 1) + return Content("C"); + else + return Content("O"); + } + + public FileResult DownloadFile(string fileGuid, string swrNumber, int typeOfDoc) { + string fileName = LotTravDMO.GetFileName(fileGuid, typeOfDoc); + + string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); + + string ecnFolderPath = _AppSettings.AttachmentFolder + "LotTraveler\\" + swrNumber.ToString(); + var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); + + var FDir_AppData = _AppSettings.AttachmentFolder; + if (!sDocument.StartsWith(FDir_AppData)) { + // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder + // and block requests outside like "../web.config" + throw new HttpException(403, "Forbidden"); + } + + if (!System.IO.File.Exists(sDocument)) { + return null; + //throw new Exception("File not found"); + } + + return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + } + + [HttpPost] + public void ReAssignOriginatorByAdmin(int workRequestID, string comments, int newOriginatorId) { + if (Session[GlobalVars.IS_ADMIN] == null) + throw new Exception("Permission denied"); + + try { + LotTravDMO.ReassignOriginator(workRequestID, newOriginatorId, comments, (int)Session[GlobalVars.SESSION_USERID]); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim(); + if (exceptionString.Length > 450) + exceptionString = exceptionString.Substring(0, 450); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignOriginatorByAdmin\r\n" + workRequestID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = workRequestID, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "ReAssignOriginatorByAdmin - " + exceptionString }); + throw new Exception(e.Message); } } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/MRBController.cs b/Fab2ApprovalSystem/Controllers/MRBController.cs index b0a3719..4fef16b 100644 --- a/Fab2ApprovalSystem/Controllers/MRBController.cs +++ b/Fab2ApprovalSystem/Controllers/MRBController.cs @@ -1,1718 +1,812 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.ViewModels; + using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; -using Fab2ApprovalSystem.Models; -using Fab2ApprovalSystem.DMO; -using Fab2ApprovalSystem.Misc; -using System.IO; -using System.Text; + +using System; +using System.Collections.Generic; using System.Configuration; -using Fab2ApprovalSystem.ViewModels; -using System.Dynamic; -using System.Web.Script.Serialization; -using System.Threading; using System.Diagnostics; +using System.Dynamic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Web; +using System.Web.Mvc; +using System.Web.Script.Serialization; -namespace Fab2ApprovalSystem.Controllers -{ - [Authorize] - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - [SessionExpireFilter] - public class MRBController : Controller - { - MRB_DMO mrbDMO = new MRB_DMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); - CredentialsStorage credentialsStorage = new CredentialsStorage(); +namespace Fab2ApprovalSystem.Controllers; - // - // GET: /MRB/ - public ActionResult Index() - { - return View(); - } +[Authorize] +[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +[SessionExpireFilter] +public class MRBController : Controller { - // - // GET: /MRB/Details/5 - public ActionResult Details(int id) - { - return View(); - } + MRB_DMO mrbDMO; + WorkflowDMO wfDMO = new WorkflowDMO(); + CredentialsStorage credentialsStorage = new CredentialsStorage(); + private readonly AppSettings _AppSettings; - // - // GET: /MRB/Create - public ActionResult Create() - { - MRB mrb = new MRB(); - MRB_DMO mrbDMO = new MRB_DMO(); - mrb.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; - mrbDMO.InsertMRB(mrb); + public MRBController(AppSettings appSettings) { + _AppSettings = appSettings; + mrbDMO = new MRB_DMO(appSettings); + } + // + // GET: /MRB/ + public ActionResult Index() { + return View(); + } - // Automatically Submit the Document as soon as an MRB is created - try - { - PopulateCloseToQDB(); - mrbDMO.SubmitDocument(mrb.MRBNumber, (int)Session[GlobalVars.SESSION_USERID]); - //if (appoverCount > 0) - // NotifyApprovers(mrb.MRBNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1); + // + // GET: /MRB/Details/5 + public ActionResult Details(int id) { + return View(); + } + // + // GET: /MRB/Create + public ActionResult Create() { + MRB mrb = new MRB(); + MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); + mrb.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + mrbDMO.InsertMRB(mrb); - //if (Request.IsAjaxRequest()) - //{ - // return Content("Redirect"); - //} - //else - // return Content("Invalid"); - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + mrb.MRBNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument - MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); - throw new Exception(e.Message); + // Automatically Submit the Document as soon as an MRB is created + try { + PopulateCloseToQDB(); + mrbDMO.SubmitDocument(mrb.MRBNumber, (int)Session[GlobalVars.SESSION_USERID]); + //if (appoverCount > 0) + // NotifyApprovers(mrb.MRBNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1); - } - - - return RedirectToAction("Edit", new { IssueID = mrb.MRBNumber }); - } - - // - // POST: /MRB/Create - [HttpPost] - public ActionResult Create(FormCollection collection) - { - try - { - // TODO: Add insert logic here - - return RedirectToAction("Index"); - } - catch - { - return View(); - } - } - - // - // GET: /MRB/Edit/5 - public ActionResult Edit(int issueID) - { - string jwt = Session["JWT"].ToString(); - string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); - string refreshToken = Session["RefreshToken"].ToString(); - string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); - string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? - "https://localhost:7255"; - string mrbUrl = $"{wasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=/mrb/{issueID}"; - - return Redirect(mrbUrl); - } - - // - // POST: /MRB/Edit/5 - [HttpPost] - public void Edit(MRB mrb) - { - try - { - mrbDMO.UpdateMRB(mrb); - - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + mrb.MRBNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n UpdateEdit MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - } - } - - - /// - /// - /// - /// - /// - public ActionResult ReadOnly(int issueID) - { - string jwt = Session["JWT"].ToString(); - string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); - string refreshToken = Session["RefreshToken"].ToString(); - string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); - string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? - "https://localhost:7255"; - string mrbUrl = $"{wasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=/mrb/{issueID}"; - - return Redirect(mrbUrl); - } - - // - // GET: /MRB/Delete/5 - public ActionResult Delete(int id) - { - return View(); - } - - // - // POST: /MRB/Delete/5 - [HttpPost] - public ActionResult Delete(int id, FormCollection collection) - { - try - { - // TODO: Add delete logic here - - return RedirectToAction("Index"); - } - catch - { - return View(); - } - } - - /// - /// - /// - /// - /// - /// - public JsonResult SearchLots(string searchText, string searchBy) - { - //IEnumerable lotlist = MiscDMO.SearchLots(searchText, searchBy); - List lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList(); - return Json(lotlist, JsonRequestBehavior.AllowGet); - } - - - /// - /// - /// - /// - /// - /// - public ActionResult GetMRBLots([DataSourceRequest] DataSourceRequest request, int mrbNumber) - { - return Json(mrbDMO.GetMRBLots(mrbNumber).ToDataSourceResult(request)); - } - - [HttpGet] - public ActionResult GetTools() - { - return Json(mrbDMO.GetTools(), JsonRequestBehavior.AllowGet); - } - - - /// - /// Updates the lot tables - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult UpdateMRBLot([DataSourceRequest] DataSourceRequest request, Lot lot) - { - - //try + //if (Request.IsAjaxRequest()) //{ - // // RJK - // //routine to cascade the "dispo type" to all the child lots in SPN - - // MRB mrbInfo = mrbDMO.GetToolIssueStartEndDateData(lot.MRBNumber); - - // if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) - // { - // bool existingLotUpdated; - // Lot l = new Lot(); - // l.LotNumber = lot.LotNumber; - // if (lot.DispoType.ToString().Trim().Length == 1) - // { - // l.DispoType = lot.DispoType; - // } - // l.MRBNumber = lot.MRBNumber; - // // check if the lot was sent to SPN - // bool lotSentToSPN = mrbDMO.IsLotSentToSPN(l.LotNumber, l.MRBNumber); - // //only get the child lots if it has been sent to SPN to set the MRB Flag - // if (lotSentToSPN) - // { - // if (!mrbDMO.GetChildLotsFromSPNForDispoTypeUpdate(l.MRBNumber, l.LotNumber, mrbInfo.ToolCSV, mrbInfo.IssueStartDate, mrbInfo.IssueEndDate, lot.DispoType)) - // { - // //warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n", l.LotNumber); - // } - // } - - // } - - + // return Content("Redirect"); //} - //catch(Exception e) - //{ - // // ignore the error - // string s = e.InnerException.ToString(); - //} - - - if (lot != null && ModelState.IsValid) - { - mrbDMO.UpdateMRBLot(lot); - } - - return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); + //else + // return Content("Invalid"); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + mrb.MRBNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + throw new Exception(e.Message); } + return RedirectToAction("Edit", new { IssueID = mrb.MRBNumber }); + } - /// - /// Deletes record from the lot table - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteMRBLot([DataSourceRequest] DataSourceRequest request, Lot lot) - { - try - { - if (lot != null && ModelState.IsValid) - { - mrbDMO.DeleteMRBLot(lot.LotID); + // + // POST: /MRB/Create + [HttpPost] + public ActionResult Create(FormCollection collection) { + try { + // TODO: Add insert logic here - } - } - catch (Exception ex) - { - // TODO - throw new Exception(ex.Message); - } + return RedirectToAction("Index"); + } catch { + return View(); + } + } + // + // GET: /MRB/Edit/5 + public ActionResult Edit(int issueID) { + string jwt = Session["JWT"].ToString(); + string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); + string refreshToken = Session["RefreshToken"].ToString(); + string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); + string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? + "https://localhost:7255"; + string mrbUrl = $"{wasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=/mrb/{issueID}"; - return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); + return Redirect(mrbUrl); + } + + // + // POST: /MRB/Edit/5 + [HttpPost] + public void Edit(MRB mrb) { + try { + mrbDMO.UpdateMRB(mrb); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + mrb.MRBNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateEdit MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); + } + } + + public ActionResult ReadOnly(int issueID) { + string jwt = Session["JWT"].ToString(); + string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); + string refreshToken = Session["RefreshToken"].ToString(); + string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); + string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? + "https://localhost:7255"; + string mrbUrl = $"{wasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=/mrb/{issueID}"; + + return Redirect(mrbUrl); + } + + // + // GET: /MRB/Delete/5 + public ActionResult Delete(int id) { + return View(); + } + + // + // POST: /MRB/Delete/5 + [HttpPost] + public ActionResult Delete(int id, FormCollection collection) { + try { + // TODO: Add delete logic here + + return RedirectToAction("Index"); + } catch { + return View(); + } + } + + public JsonResult SearchLots(string searchText, string searchBy) { + //IEnumerable lotlist = MiscDMO.SearchLots(searchText, searchBy); + List lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList(); + return Json(lotlist, JsonRequestBehavior.AllowGet); + } + + public ActionResult GetMRBLots([DataSourceRequest] DataSourceRequest request, int mrbNumber) { + return Json(mrbDMO.GetMRBLots(mrbNumber).ToDataSourceResult(request)); + } + + [HttpGet] + public ActionResult GetTools() { + return Json(mrbDMO.GetTools(), JsonRequestBehavior.AllowGet); + } + + /// + /// Updates the lot tables + /// + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult UpdateMRBLot([DataSourceRequest] DataSourceRequest request, Lot lot) { + //try + //{ + // // RJK + // //routine to cascade the "dispo type" to all the child lots in SPN + + // MRB mrbInfo = mrbDMO.GetToolIssueStartEndDateData(lot.MRBNumber); + + // if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) + // { + // bool existingLotUpdated; + // Lot l = new Lot(); + // l.LotNumber = lot.LotNumber; + // if (lot.DispoType.ToString().Trim().Length == 1) + // { + // l.DispoType = lot.DispoType; + // } + // l.MRBNumber = lot.MRBNumber; + // // check if the lot was sent to SPN + // bool lotSentToSPN = mrbDMO.IsLotSentToSPN(l.LotNumber, l.MRBNumber); + // //only get the child lots if it has been sent to SPN to set the MRB Flag + // if (lotSentToSPN) + // { + // if (!mrbDMO.GetChildLotsFromSPNForDispoTypeUpdate(l.MRBNumber, l.LotNumber, mrbInfo.ToolCSV, mrbInfo.IssueStartDate, mrbInfo.IssueEndDate, lot.DispoType)) + // { + // //warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n", l.LotNumber); + // } + // } + + // } + + //} + //catch(Exception e) + //{ + // // ignore the error + // string s = e.InnerException.ToString(); + //} + + if (lot != null && ModelState.IsValid) { + mrbDMO.UpdateMRBLot(lot); } - /// - /// - /// - /// - public void DeleteAllMRBLots(int issueID) - { - // trap the error on then client side - mrbDMO.DeleteAllMRBLot(issueID); + return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); + } + + /// + /// Deletes record from the lot table + /// + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteMRBLot([DataSourceRequest] DataSourceRequest request, Lot lot) { + try { + if (lot != null && ModelState.IsValid) { + mrbDMO.DeleteMRBLot(lot.LotID); + + } + } catch (Exception ex) { + // TODO + throw new Exception(ex.Message); } + return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); + } - /// - /// - /// - /// - /// - public JsonResult AddLot(Lot lot) - { - // This is to add a manually entered lot + public void DeleteAllMRBLots(int issueID) { + // trap the error on then client side + mrbDMO.DeleteAllMRBLot(issueID); + } - Lot l = lot; + public JsonResult AddLot(Lot lot) { + // This is to add a manually entered lot - try - { - bool existingRowUpdated; - mrbDMO.InsertLot(lot, false, out existingRowUpdated); - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lot.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Add Lot Disposition\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - throw new Exception(e.Message); - } - return Json(l, JsonRequestBehavior.AllowGet); + Lot l = lot; + + try { + bool existingRowUpdated; + mrbDMO.InsertLot(lot, false, out existingRowUpdated); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lot.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Add Lot Disposition\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + throw new Exception(e.Message); } + return Json(l, JsonRequestBehavior.AllowGet); + } + public ActionResult AddLots(string lotNumbers, int mrbNumber) { + // This is for adding lot(s) via search - /// - /// - /// - /// - /// - public ActionResult AddLots(string lotNumbers, int mrbNumber) - { - // This is for adding lot(s) via search - - try - { - var warnings = new StringBuilder(); - - if (lotNumbers.Length > 0) - { - string[] tempLots = lotNumbers.Split(new char[] { '~' }); - foreach (string lotNumber in tempLots) - { - bool existingRowUpdated; - Lot l = new Lot(); - l.LotNumber = lotNumber; - l.MRBNumber = mrbNumber; - mrbDMO.InsertLot(l, true, out existingRowUpdated); - - - //if (!existingRowUpdated) - //{ - // if (!mrbDMO.InsertLotSplitsAffectedByIncident(mrbNumber, l.LotNumber)) - // { - // warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n", l.LotNumber); - // } - //} - } - - //warnings.Append("No tool info, split lots will NOT be automatically searched and uploaded \n please make sure to include all the child lots in the MRB"); - } - - return Content(warnings.ToString()); - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRBNumber=" + mrbNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AddLots MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", DocumentType = "MRB", Comments = exceptionString }); - - Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; - return Content(e.Message); - } - } - - #region ATTACHMENT - /// - /// - /// - /// - /// - /// - public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int mrbNumber) - { - return Json(mrbDMO.GetMRBAttachments(mrbNumber).ToDataSourceResult(request)); - } - - - /// - /// - /// - /// - /// - [HttpPost] - public void DeleteAttachment(int attachmentID) - { - try - { - if (ModelState.IsValid) - { - var attachment = mrbDMO.GetMRBAttachment(attachmentID); - - if (attachment == null) return; - - String fileName = attachment.Path; - if (String.IsNullOrEmpty(fileName)) fileName = attachment.FileName; - - mrbDMO.DeleteMRBAttachment(attachmentID); - - if (!String.IsNullOrWhiteSpace(fileName)) - { - var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + "MRB", fileName); - - FileInfo f = new FileInfo(physicalPath); - - if (f.Exists) - f.Delete(); - } - } - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n AttachmentID MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString }); - throw new Exception(e.Message); - - } - } - - /// - /// - /// - /// - /// - public ActionResult AttachSave(IEnumerable files, int mrbNumber) - { - var errorList = new List(); - - // The Name of the Upload component is "files" - if (files != null) - { - foreach (var file in files) - { - - // Some browsers send file names with full path. - // We are only interested in the file name. - var fileName = Path.GetFileName(file.FileName); - string physicalFileName; - string physicalPath; - - // Check to see if this filename is in use - var attachments = mrbDMO.GetMRBAttachments(mrbNumber); - if (attachments.Count() > 0) - { - if (attachments.Where(a => String.Equals(a.FileName, fileName, StringComparison.OrdinalIgnoreCase)).Count() > 0) - { - // This filename is used on this MRB - // So we want to delete those records so the new record replaces them - foreach (var a in attachments) - { - mrbDMO.DeleteMRBAttachment(a.AttachmentID); - - physicalFileName = a.Path; - if (String.IsNullOrEmpty(physicalFileName)) physicalFileName = a.FileName; - physicalPath = Path.Combine(Functions.GetAttachmentFolder() + "MRB", physicalFileName); - - if (System.IO.File.Exists(physicalPath)) - System.IO.File.Delete(physicalPath); - } - } - } - - physicalFileName = mrbNumber.ToString() + "_" + Guid.NewGuid().ToString() + System.IO.Path.GetExtension(fileName); - physicalPath = Path.Combine(Functions.GetAttachmentFolder() + "MRB", physicalFileName); - - file.SaveAs(physicalPath); - MRBAttachment attach = new MRBAttachment() - { - MRBNumber = mrbNumber, - FileName = fileName, - Path = physicalFileName, -#if(DEBUG) - UserID = 114, -#endif - -#if(!DEBUG) - UserID = (int)Session[GlobalVars.SESSION_USERID], -#endif - }; - mrbDMO.InsertMRBAttachment(attach); - } - } - - //var model = mrbDMO.GetMRBAttachments(mrbNumber); - - - return Json(new { errors = errorList }); - } - - - #endregion - - - public ActionResult ExcelLotOpen(IEnumerable Lotfile, int mrbNumber) - { + try { var warnings = new StringBuilder(); - var physicalPath = ""; - try - { - var dispos = mrbDMO.GetDispositions(mrbNumber); - foreach (var file in Lotfile) - { - //string guid = ""; + if (lotNumbers.Length > 0) { + string[] tempLots = lotNumbers.Split(new char[] { '~' }); + foreach (string lotNumber in tempLots) { + bool existingRowUpdated; + Lot l = new Lot(); + l.LotNumber = lotNumber; + l.MRBNumber = mrbNumber; + mrbDMO.InsertLot(l, true, out existingRowUpdated); - string fName = User.Identity.Name + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); + //if (!existingRowUpdated) + //{ + // if (!mrbDMO.InsertLotSplitsAffectedByIncident(mrbNumber, l.LotNumber)) + // { + // warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n", l.LotNumber); + // } + //} + } - IEnumerable lotNumbers; + //warnings.Append("No tool info, split lots will NOT be automatically searched and uploaded \n please make sure to include all the child lots in the MRB"); + } - try - { - physicalPath = Path.Combine(ConfigurationManager.AppSettings["LotTempPipeLine"].ToString(), fName + "." + Path.GetExtension(file.FileName)); - file.SaveAs(physicalPath); - ExcelData x = new ExcelData(physicalPath); - lotNumbers = x.ReadData(); - } - catch (Exception ex) - { - throw new Exception(String.Format("Invalid file format for {0}: {1}", file.FileName, ex.Message)); - } + return Content(warnings.ToString()); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRBNumber=" + mrbNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddLots MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", DocumentType = "MRB", Comments = exceptionString }); - // Get Tool, Issue Start and End Date + Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; + return Content(e.Message); + } + } - MRB mrbInfo = mrbDMO.GetToolIssueStartEndDateData(mrbNumber, null); + #region ATTACHMENT - foreach (var lotInfo in lotNumbers) - { - if (lotInfo.LotDispo.Length == 1) - { - if (dispos.Count(d => d.DispositionType.Trim().ToUpper() == lotInfo.LotDispo.Trim().ToUpper()) == 0) - { - throw new Exception(String.Format("Invalid lot disposition {0} for lot no {1}", - lotInfo.LotDispo, lotInfo.LotNo)); - } - } - } - // RJK - 12/17 - // Only find the child Splits when a Tool or a list of Tools is provided - if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) - { - foreach (var lotInfo in lotNumbers) - { - bool existingLotUpdated; - Lot l = new Lot(); - l.LotNumber = lotInfo.LotNo; - if (lotInfo.LotDispo.Length == 1) - { - l.DispoType = lotInfo.LotDispo[0]; - } - l.MRBNumber = mrbNumber; - mrbDMO.InsertLot(l, true, out existingLotUpdated); - // cannot do the check below , because what if the parent lot had splits after the prior lot split analysis - //if (!existingLotUpdated) - //{ - if (!mrbDMO.InsertLotSplitsAffectedByIncident(mrbNumber, l.LotNumber, mrbInfo.ToolCSV, mrbInfo.IssueStartDate, mrbInfo.IssueEndDate)) - { - warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n Uploaded without Lot Genealogy tracing", l.LotNumber); - } - //} - } + public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int mrbNumber) { + return Json(mrbDMO.GetMRBAttachments(mrbNumber).ToDataSourceResult(request)); + } - // Not required - Will be using each lot's Insert Date time stamp, - // as lot could be added using search functionality - // mrbDMO.UpdateLastLotSplitAnalysisTime(mrbNumber); + [HttpPost] + public void DeleteAttachment(int attachmentID) { + try { + if (ModelState.IsValid) { + var attachment = mrbDMO.GetMRBAttachment(attachmentID); + if (attachment == null) + return; - } - else - { - // RJK - 12/17 - // Only find the child Splits when a Tool or a list of Tools is provided - foreach (var lotInfo in lotNumbers) - { - bool existingLotUpdated; - Lot l = new Lot(); - l.LotNumber = lotInfo.LotNo; - if (lotInfo.LotDispo.Length == 1) - { - l.DispoType = lotInfo.LotDispo[0]; - } - l.MRBNumber = mrbNumber; - // do not insert any new lots when importing from excel - mrbDMO.InsertLot(l, true, out existingLotUpdated); - //mrbDMO.UpdateLotDispoType(mrbNumber, l.LotNumber, l.DispoType); + String fileName = attachment.Path; + if (String.IsNullOrEmpty(fileName)) + fileName = attachment.FileName; + mrbDMO.DeleteMRBAttachment(attachmentID); - //if (!existingLotUpdated) - //{ - // if (!mrbDMO.InsertLotSplitsAffectedByIncident(mrbNumber, l.LotNumber, mrbInfo.ToolCSV, mrbInfo.IssueStartDate, mrbInfo.IssueEndDate)) - // { - // warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n", l.LotNumber); - // } - //} - } - } + if (!String.IsNullOrWhiteSpace(fileName)) { + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + "MRB", fileName); FileInfo f = new FileInfo(physicalPath); + if (f.Exists) f.Delete(); - } - - return Content(warnings.ToString()); } - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + mrbNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n MRB Excel\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); - + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AttachmentID MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString }); + throw new Exception(e.Message); + } + } + public ActionResult AttachSave(IEnumerable files, int mrbNumber) { + var errorList = new List(); - FileInfo f = new FileInfo(physicalPath); - if (f.Exists) - f.Delete(); - - Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; - return Content(e.Message); + // The Name of the Upload component is "files" + if (files != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in files) { + mrbDMO.AttachSave(mrbNumber, userId, file.FileName, file.InputStream); } - } - /// - /// - /// - /// - /// - public ActionResult ImportAddQDBFlag(IEnumerable AddQDBFlag, string operation) - { - //string path = Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch()); - var physicalPath = ""; - try - { - IEnumerable lotDataList = null; + //var model = mrbDMO.GetMRBAttachments(mrbNumber); - foreach (var file in AddQDBFlag) - { - var guid = Guid.NewGuid().ToString(); + return Json(new { errors = errorList }); + } - //string fName = User.Identity.Name + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); + #endregion - //physicalPath = Path.Combine(@"C:\Websites\FabApprovalTempPipeLine", guid + "." + Path.GetExtension(file.FileName)); - physicalPath = Path.Combine(ConfigurationManager.AppSettings["LotTempPipeLine"].ToString(), guid + "." + Path.GetExtension(file.FileName)); - file.SaveAs(physicalPath); - ExcelData x = new ExcelData(physicalPath); - lotDataList = x.ReadQDBFlagData(); + public ActionResult ExcelLotOpen(IEnumerable Lotfile, int mrbNumber) { + var warnings = new StringBuilder(); + var physicalPath = ""; + try { + string userIdentityName = @User.Identity.Name; + var dispos = mrbDMO.GetDispositions(mrbNumber); + string lotTempPipeLine = ConfigurationManager.AppSettings["LotTempPipeLine"].ToString(); - foreach (string lotData in lotDataList) - { - mrbDMO.InsertMRB_QDB_HoldFlag(guid, lotData, operation); - } - - FileInfo f = new FileInfo(physicalPath); - if (f.Exists) - f.Delete(); - - - if (SendQDBFlagToSPN(guid)) - mrbDMO.UpdateMRB_QDB_HoldFlag(guid, true); - else - { - mrbDMO.UpdateMRB_QDB_HoldFlag(guid, false); - return Content("Problems while uploading to SPN"); - } - - - - } - - return Content(""); - } - catch - { - FileInfo f = new FileInfo(physicalPath); - if (f.Exists) - f.Delete(); - - return Content("Incorrect File Format/Data"); + foreach (var file in Lotfile) { + physicalPath = mrbDMO.ExcelLotOpen(mrbNumber, warnings, dispos, userIdentityName, lotTempPipeLine, file.FileName, file.InputStream); } + return Content(warnings.ToString()); + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + mrbNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n MRB Excel\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + + FileInfo f = new FileInfo(physicalPath); + if (f.Exists) + f.Delete(); + + Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; + return Content(e.Message); } + } - - /// - /// - /// - /// - /// - /// - public ActionResult ImportRemoveQDBFlag(IEnumerable RemoveQDBFlag, string operation) - { - var physicalPath = ""; - try - { - IEnumerable lotDataList = null; - - foreach (var file in RemoveQDBFlag) - { - var guid = Guid.NewGuid().ToString(); - - //string fName = User.Identity.Name + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); - - //physicalPath = Path.Combine(@"C:\Websites\FabApprovalTempPipeLine", guid + "." + Path.GetExtension(file.FileName)); - physicalPath = Path.Combine(ConfigurationManager.AppSettings["LotTempPipeLine"].ToString(), guid + "." + Path.GetExtension(file.FileName)); - file.SaveAs(physicalPath); - ExcelData x = new ExcelData(physicalPath); - lotDataList = x.ReadQDBFlagData(); - - foreach (string lotData in lotDataList) - { - mrbDMO.InsertMRB_QDB_HoldFlag(guid, lotData, operation); - } - - FileInfo f = new FileInfo(physicalPath); - if (f.Exists) - f.Delete(); - - - //Send the data to SPN - if (SendQDBFlagToSPN(guid)) - mrbDMO.UpdateMRB_QDB_HoldFlag(guid, true); - else - { - mrbDMO.UpdateMRB_QDB_HoldFlag(guid, false); - return Content("Problems while uploading to SPN"); - } - - } - - return Content(""); - } - catch - { - FileInfo f = new FileInfo(physicalPath); - if (f.Exists) - f.Delete(); - - return Content("Incorrect File Format/Data"); - } - - } - - - /// - /// - /// - /// - /// - /// - - public ActionResult GetContainmentActions([DataSourceRequest] DataSourceRequest request, int mrbNumber) - { - return Json(mrbDMO.GetContainmentActions(mrbNumber).ToDataSourceResult(request)); - } - - /// - /// - /// - /// - /// - /// - //[AcceptVerbs(HttpVerbs.Post)] - //public ActionResult UpdateContainmentAction([DataSourceRequest] DataSourceRequest request, ContainmentActionObj model) - //{ - // if (model != null && ModelState.IsValid) - // { - // mrbDMO.UpdateContainmentAction(model); - // } - - - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - - ///// - ///// - ///// - ///// - ///// - ///// - //[AcceptVerbs(HttpVerbs.Post)] - //public ActionResult InsertContainmentAction([DataSourceRequest] DataSourceRequest request, ContainmentActionObj model) - //{ - - // if (model != null && ModelState.IsValid) - // { - // mrbDMO.InsertContainmentAction(model); - // } - - - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - - - - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult UpdateContainmentAction(ContainmentActionObj model) - { - if (model != null && ModelState.IsValid) - { - mrbDMO.UpdateContainmentAction(model); + public ActionResult ImportAddQDBFlag(IEnumerable AddQDBFlag, string operation) { + //string path = Server.MapPath("/FTPBatch/" + ConfigurationManager.AppSettings["FTPSPNBatchFileName"]); + var physicalPath = ""; + try { + string message; + string c = Server.MapPath("/FTPBatch/"); + string userIdentityName = @User.Identity.Name; + string b = Server.MapPath("/FTPBatch/" + ConfigurationManager.AppSettings["FTPSPNBatchFileName"]); + string a = Server.MapPath("/FTPBatch/" + ConfigurationManager.AppSettings["FTPSPNBatchFileName_Test"]); + foreach (var file in AddQDBFlag) { + message = mrbDMO.ImportAddQDBFlag(operation, out physicalPath, userIdentityName, a, b, c, file.FileName, file.InputStream); + if (string.IsNullOrEmpty(message)) + continue; + return Content(message); } return Content(""); + } catch { + FileInfo f = new FileInfo(physicalPath); + if (f.Exists) + f.Delete(); + + return Content("Incorrect File Format/Data"); } + } - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult InsertContainmentAction(ContainmentActionObj model) - { - - if (model != null && ModelState.IsValid) - { - mrbDMO.InsertContainmentAction(model); + public ActionResult ImportRemoveQDBFlag(IEnumerable RemoveQDBFlag, string operation) { + var physicalPath = ""; + try { + string message; + string c = Server.MapPath("/FTPBatch/"); + string userIdentityName = @User.Identity.Name; + string b = Server.MapPath("/FTPBatch/" + ConfigurationManager.AppSettings["FTPSPNBatchFileName"]); + string a = Server.MapPath("/FTPBatch/" + ConfigurationManager.AppSettings["FTPSPNBatchFileName_Test"]); + foreach (var file in RemoveQDBFlag) { + message = mrbDMO.ImportRemoveQDBFlag(operation, out physicalPath, userIdentityName, a, b, c, file.FileName, file.InputStream); + if (string.IsNullOrEmpty(message)) + continue; + return Content(message); } - return Content(""); + } catch { + FileInfo f = new FileInfo(physicalPath); + if (f.Exists) + f.Delete(); + + return Content("Incorrect File Format/Data"); + } + } + + public ActionResult GetContainmentActions([DataSourceRequest] DataSourceRequest request, int mrbNumber) { + return Json(mrbDMO.GetContainmentActions(mrbNumber).ToDataSourceResult(request)); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult UpdateContainmentAction(ContainmentActionObj model) { + if (model != null && ModelState.IsValid) { + mrbDMO.UpdateContainmentAction(model); } - /// - /// - /// - /// - /// - /// - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteContainmentAction([DataSourceRequest] DataSourceRequest request, ContainmentActionObj model) - { - if (model != null && ModelState.IsValid) - { - mrbDMO.DeleteContainmentAction(model); + return Content(""); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult InsertContainmentAction(ContainmentActionObj model) { + if (model != null && ModelState.IsValid) { + mrbDMO.InsertContainmentAction(model); + } + + return Content(""); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteContainmentAction([DataSourceRequest] DataSourceRequest request, ContainmentActionObj model) { + if (model != null && ModelState.IsValid) { + mrbDMO.DeleteContainmentAction(model); + } + + return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + } + + #region + + public ActionResult GetDispostions([DataSourceRequest] DataSourceRequest request, int mrbNumber) { + return Json(mrbDMO.GetDispositions(mrbNumber).ToDataSourceResult(request)); + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult UpdateDisposition(Disposition model) { + if (model != null && ModelState.IsValid) { + mrbDMO.UpdateDisposition(model); + } + + return Json(model, JsonRequestBehavior.AllowGet); + } + + [AcceptVerbs(HttpVerbs.Post)] + public void InsertDisposition(Disposition model) { + if (model != null && ModelState.IsValid) { + mrbDMO.InsertDisposition(model); + } + } + + [AcceptVerbs(HttpVerbs.Post)] + public ActionResult DeleteDisposition(Disposition model) { + if (model != null && ModelState.IsValid) { + mrbDMO.DeleteDisposition(model); + } + + return Json(model, JsonRequestBehavior.AllowGet); + } + + #endregion + + public void PopulateCloseToQDB() { + List options = new List(); + options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 0, CloseToQDBOption = "No" }); + options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 1, CloseToQDBOption = "Yes" }); + //options.Add(new CloseToQDBOptionViewModel{CloseToQDBOption= "No"}); + //options.Add(new CloseToQDBOptionViewModel {CloseToQDBOption = "Yes" }); + + ViewData["CloseToQDBOptions"] = options; + } + + public void NotifyApprovers(int mrbNumber, byte currentStep) { + string emailSentList = ""; + + List emailIst = MiscDMO.GetApproverEmailListByDocument(mrbNumber, currentStep, (int)GlobalVars.DocumentType.MRB).Distinct().ToList(); + + string emailTemplate = "MRBAssigned.txt"; + string userEmail = string.Empty; + string subject = "MRB Assignment"; + string senderName = "MRB"; + + foreach (string email in emailIst) { + subject = "MRB Assignment"; + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[3]; + emailparams[0] = mrbNumber.ToString(); + emailparams[1] = mrbNumber.ToString(); + emailparams[2] = GlobalVars.hostURL; + userEmail = email; + //#if(DEBUG) + // userEmail = "rkotian1@irf.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + emailSentList += email + ","; + } + + try { + EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + } catch { } + } + + public void Approve(int issueID, byte currentStep, string comments) { + int isITARCompliant = 1; + MRB mrb = new MRB(); + mrb = mrbDMO.GetMRBItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + try { + bool lastStep = false; + + bool lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.MRB, mrb.WorkFlowNumber); + + while (lastApprover && !lastStep) { + currentStep++; + lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.MRB, mrb.WorkFlowNumber); + NotifyApprovers(issueID, currentStep); } + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw new Exception(e.Message); + } + } + public void CloseDocument(int mrb) { + mrbDMO.CloseDocument(mrb); + } - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); + public void SetDispositionTypeForAllLots(int mrb, string dispoType) { + mrbDMO.SetDispositionTypeForAllLots(mrb, dispoType); + } + + public JsonResult GetLotWaferDieCount(int mrbNumber) { + int lotCount = 0; + int waferCount = 0; + int dieCount = 0; + mrbDMO.GetLotWaferDieCount(mrbNumber, out lotCount, out waferCount, out dieCount); + + //dynamic data = new ExpandoObject(); + //data.LotCount = lotCount; + //data.WaferCount = waferCount; + //data.DieCount = dieCount; + + //string json = Newtonsoft.Json.JsonConvert.SerializeObject(data); + + //return Json(json, JsonRequestBehavior.AllowGet); + return Json(lotCount.ToString() + "~" + waferCount.ToString() + "~" + dieCount, JsonRequestBehavior.AllowGet); + } + + public ActionResult SendMRBHoldFlagToSPN(int mrbNumber) { + MRB mrbInfo; + try { + mrbInfo = mrbDMO.GetToolIssueStartEndDateData(mrbNumber); + } catch { + // if tools or issue start/end date is not provided, set them to null + mrbInfo = new MRB { ToolCSV = "", IssueStartDate = null, IssueEndDate = null }; } + if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) { + Lot l = new Lot(); + var mrbLotInfo = mrbDMO.GetLotsToFindNewChildLots(mrbNumber); + foreach (Lot lot in mrbLotInfo) { + //routine to cascade the "dispo type" to all the child lots in SPN (Lot that are not present in FAb App Sys,) + mrbDMO.ChildLotsUpdateInSPNWithNewDispoType(lot, mrbInfo); - #region - /// - /// - /// - /// - /// - /// - public ActionResult GetDispostions([DataSourceRequest] DataSourceRequest request, int mrbNumber) - { - return Json(mrbDMO.GetDispositions(mrbNumber).ToDataSourceResult(request)); - } - - - /// - /// - /// - /// - /// - /// - //[AcceptVerbs(HttpVerbs.Post)] - //public ActionResult UpdateDisposition([DataSourceRequest] DataSourceRequest request, Disposition model) - //{ - // if (model != null && ModelState.IsValid) - // { - // mrbDMO.UpdateDisposition(model); - // } - - - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - - - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult UpdateDisposition(Disposition model) - { - if (model != null && ModelState.IsValid) - { - mrbDMO.UpdateDisposition(model); - } - - return Json(model, JsonRequestBehavior.AllowGet); - } - - /// - /// - /// - /// - /// - /// - //[AcceptVerbs(HttpVerbs.Post)] - //public ActionResult InsertDisposition([DataSourceRequest] DataSourceRequest request, Disposition model) - //{ - - // if (model != null && ModelState.IsValid) - // { - // mrbDMO.InsertDisposition(model); - // } - - - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - - - - [AcceptVerbs(HttpVerbs.Post)] - public void InsertDisposition( Disposition model) - { - - if (model != null && ModelState.IsValid) - { - mrbDMO.InsertDisposition(model); } } - /// - /// - /// - /// - /// - /// - //[AcceptVerbs(HttpVerbs.Post)] - //public ActionResult DeleteDisposition([DataSourceRequest] DataSourceRequest request, Disposition model) - //{ - // if (model != null && ModelState.IsValid) - // { - // mrbDMO.DeleteDisposition(model); - // } - - - // return Json(new[] { model }.ToDataSourceResult(request, ModelState)); - //} - - [AcceptVerbs(HttpVerbs.Post)] - public ActionResult DeleteDisposition(Disposition model) - { - if (model != null && ModelState.IsValid) - { - mrbDMO.DeleteDisposition(model); - } - - - return Json(model, JsonRequestBehavior.AllowGet); - } - - #endregion - - - public void PopulateCloseToQDB() - { - List options = new List(); - options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 0, CloseToQDBOption = "No" }); - options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 1, CloseToQDBOption = "Yes" }); - //options.Add(new CloseToQDBOptionViewModel{CloseToQDBOption= "No"}); - //options.Add(new CloseToQDBOptionViewModel {CloseToQDBOption = "Yes" }); - - ViewData["CloseToQDBOptions"] = options; - - } - - - /// - /// - /// - /// - /// - //public ActionResult SubmitDocument(int mrbNumber) - //{ - // try - // { - // int appoverCount = mrbDMO.SubmitDocument(mrbNumber, (int)Session[GlobalVars.SESSION_USERID]); - // if (appoverCount > 0) - // NotifyApprovers(mrbNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1); - - - - // if (Request.IsAjaxRequest()) - // { - // return Content("Redirect"); - // } - // else - // return Content("Invalid"); - // } - // catch (Exception e) - // { - // string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + mrbNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - // Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument - MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - // EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); - // throw new Exception(e.Message); - - // } - //} - - - /// - /// - /// - /// - /// - public void NotifyApprovers(int mrbNumber, byte currentStep) - { - string emailSentList = ""; - - List emailIst = MiscDMO.GetApproverEmailListByDocument(mrbNumber, currentStep, (int)GlobalVars.DocumentType.MRB).Distinct().ToList(); - - string emailTemplate = "MRBAssigned.txt"; - string userEmail = string.Empty; - string subject = "MRB Assignment"; - string senderName = "MRB"; - - foreach (string email in emailIst) - { - subject = "MRB Assignment"; - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[3]; - emailparams[0] = mrbNumber.ToString(); - emailparams[1] = mrbNumber.ToString(); - emailparams[2] = GlobalVars.hostURL; - userEmail = email; - //#if(DEBUG) - // userEmail = "rkotian1@irf.com"; - //#endif - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - emailSentList += email + ","; - } - - try - { - - EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); - } - catch { } - - - } - - /// - /// - /// - /// - public void Approve(int issueID, byte currentStep, string comments) - { - int isITARCompliant = 1; - MRB mrb = new MRB(); - mrb = mrbDMO.GetMRBItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - try - { - bool lastStep = false; - - bool lastApprover = wfDMO.Approve(issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.MRB, mrb.WorkFlowNumber); - - while (lastApprover && !lastStep) - { - currentStep++; - lastApprover = wfDMO.Approve(issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.MRB, mrb.WorkFlowNumber); - NotifyApprovers(issueID, currentStep); - } - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw new Exception(e.Message); - } - - } - - - /// - /// - /// - /// - public void CloseDocument(int mrb) - { - mrbDMO.CloseDocument(mrb); - } - - - /// - /// - /// - /// - /// - public void SetDispositionTypeForAllLots(int mrb, string dispoType) - { - mrbDMO.SetDispositionTypeForAllLots(mrb, dispoType); - } - - /// - /// - /// - /// - public JsonResult GetLotWaferDieCount(int mrbNumber) - { - - - - int lotCount = 0; - int waferCount = 0; - int dieCount = 0; - mrbDMO.GetLotWaferDieCount(mrbNumber, out lotCount, out waferCount, out dieCount); - - - //dynamic data = new ExpandoObject(); - //data.LotCount = lotCount; - //data.WaferCount = waferCount; - //data.DieCount = dieCount; - - //string json = Newtonsoft.Json.JsonConvert.SerializeObject(data); - - - //return Json(json, JsonRequestBehavior.AllowGet); - return Json(lotCount.ToString() + "~" + waferCount.ToString() + "~" + dieCount, JsonRequestBehavior.AllowGet); - - } - - - /// - /// - /// - /// - /// - public ActionResult SendMRBHoldFlagToSPN(int mrbNumber) - { - MRB mrbInfo; - try - { - mrbInfo = mrbDMO.GetToolIssueStartEndDateData(mrbNumber); - } - catch - { - // if tools or issue start/end date is not provided, set them to null - mrbInfo = new MRB { ToolCSV = "", IssueStartDate = null, IssueEndDate = null }; - } - - if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) - { - - Lot l = new Lot(); - - var mrbLotInfo = mrbDMO.GetLotsToFindNewChildLots(mrbNumber); - foreach (Lot lot in mrbLotInfo) - { - //routine to cascade the "dispo type" to all the child lots in SPN (Lot that are not present in FAb App Sys,) - mrbDMO.ChildLotsUpdateInSPNWithNewDispoType(lot, mrbInfo); - - } - - } - - // SEND DATA to SPN - - StringBuilder output = new StringBuilder(); - try - { - IEnumerable data = mrbDMO.GetMRBHoldLots(mrbNumber); - foreach (string tempData in data) - { - //output = new StringBuilder(); - if (tempData != null) - output.Append(tempData.Trim() + Environment.NewLine); - - } - - - try - { - if (output.Length > 0) - { - DateTime dt = DateTime.Now; - string newsourceFileName = mrbNumber.ToString() + "_S" + dt.Day.ToString("00") + dt.Month.ToString("00") + dt.Year.ToString("00") + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb"; - string newDestFileName = "S" + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00"); - - //string outputFile = @"C:\Websites\SPNLotHoldFlag\" + newsourceFileName; - string outputFile = ConfigurationManager.AppSettings["SPNMRBHoldFlagDirectory"].ToString() + newsourceFileName; - - - System.IO.File.WriteAllText(outputFile, output.ToString()); - -#if (DEBUG) - Thread.Sleep(1000); -#endif - try - { - //#if (!DEBUG) - //FTPWrapper spfSPN = new FTPWrapper(outputFile, newDestFileName); - //spfSPN.FTPToSPN(); - - if (BatchFTP(outputFile, newDestFileName)) - { - //TODO - mrbDMO.LogHoldFlagSentToSPNHistory(mrbNumber); - } - - //#endif - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " FTPToSPN(): SendMRBHoldFlagToSPN(mrbNumber) - FTP Upload Error " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); - //return false; - } - - } - - //return true; - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " SendMRBHoldFlagToSPN(mrbNumber) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); ; - } - - return Json(new { Error = false, Message = "Success" }, JsonRequestBehavior.AllowGet); - - - - - } - - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "GUID =" + mrbNumber.ToString() + " SendMRBHoldFlagToSPN(mrbNumber) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); - } - - - - - } - - - - /// - /// RETIRED - /// - /// - // public ActionResult SendSPN_MRB_HoldFlag(int mrbNumber) - // { - // StringBuilder output; - // try - // { - // IEnumerable data = mrbDMO.GetMRB_QDB_HoldFlags(mrbNumber); - // foreach (string tempData in data) - // { - // output = new StringBuilder(); - // output.Append(tempData.Trim() + "\n"); - - - // try - // { - // if (output.Length > 0) - // { - // DateTime dt = DateTime.Now; - // string newsourceFileName = "S" + dt.Day.ToString("00") + dt.Month.ToString("00") + dt.Year.ToString("00") + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb"; - // string newDestFileName = "S" + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb"; - - // string outputFile = @"C:\Websites\SPNLotHoldFlag\" + newsourceFileName; - - // System.IO.File.WriteAllText(outputFile, output.ToString()); - - - //#if (DEBUG) - // Thread.Sleep(1000); - //#endif - // try - // { - //#if (!DEBUG) - // FTPWrapper spfSPN = new FTPWrapper(outputFile, newDestFileName); - // spfSPN.FTPToSPN(); - //#endif - // } - // catch(Exception e) - // { - // string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " FTPToSPN(): FTP Upload Error " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - // EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - // } - - // } - - // } - // catch (Exception e) - // { - // string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " SPN Hold Flag(SendToSPN) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - // Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - // EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - // return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); - // } - - // } - - // if (data.Count() > 0) - // { - // try - // { - // // Insert the new records - //#if (!DEBUG) - // mrbDMO.InsertSPN_MRB_HoldFlagLots(mrbNumber); - //#endif - // return Json(new { Error = false, Message = "" }, JsonRequestBehavior.AllowGet); - - // } - - // catch (Exception e) - // { - // string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " SPN Hold Flag(InsertSPN_MRB_HoldFlagLots) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - // Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - // EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - // return Json(new { Result = true, Message = e.Message }, JsonRequestBehavior.AllowGet); - // } - // } - // else - // { - // return Json(new { Error = true, Message = "There are no new Lot Numbers that needs to be sent to SPN for an MRB Hold" }, JsonRequestBehavior.AllowGet); - // } - - // } - - // catch (Exception e) - // { - // string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " SPN Hold Flag(GetSPN_MRB_HoldFlagLots) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - // Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - // EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - // return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); - // } - - - - - // } - - /// - /// - /// - /// - /// - public bool SendQDBFlagToSPN(string guid) - { - StringBuilder output = new StringBuilder(); - try - { - IEnumerable data = mrbDMO.GetMRB_QDB_HoldFlags(guid); - foreach (string tempData in data) - { - //output = new StringBuilder(); + // SEND DATA to SPN + + StringBuilder output = new StringBuilder(); + try { + string c = Server.MapPath("/FTPBatch/"); + string userIdentityName = @User.Identity.Name; + string b = Server.MapPath("/FTPBatch/" + ConfigurationManager.AppSettings["FTPSPNBatchFileName"]); + string a = Server.MapPath("/FTPBatch/" + ConfigurationManager.AppSettings["FTPSPNBatchFileName_Test"]); + IEnumerable data = mrbDMO.GetMRBHoldLots(mrbNumber); + foreach (string tempData in data) { + //output = new StringBuilder(); + if (tempData != null) output.Append(tempData.Trim() + Environment.NewLine); - } + } + try { + if (output.Length > 0) { + DateTime dt = DateTime.Now; + string newsourceFileName = mrbNumber.ToString() + "_S" + dt.Day.ToString("00") + dt.Month.ToString("00") + dt.Year.ToString("00") + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb"; + string newDestFileName = "S" + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00"); - try - { - if (output.Length > 0) - { - DateTime dt = DateTime.Now; - string newsourceFileName = "S" + dt.Day.ToString("00") + dt.Month.ToString("00") + dt.Year.ToString("00") + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb"; - string newDestFileName = "S" + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb"; + //string outputFile = @"C:\Websites\SPNLotHoldFlag\" + newsourceFileName; + string ftpLogDirectory = ConfigurationManager.AppSettings["SPNMRBHoldFlagFTPLogDirectory"].ToString(); + string outputFile = ConfigurationManager.AppSettings["SPNMRBHoldFlagDirectory"].ToString() + newsourceFileName; - //string outputFile = @"C:\Websites\SPNLotHoldFlag\" + newsourceFileName; - string outputFile = ConfigurationManager.AppSettings["HoldFlagDirectory"].ToString() + newsourceFileName; - - - System.IO.File.WriteAllText(outputFile, output.ToString()); + System.IO.File.WriteAllText(outputFile, output.ToString()); #if (DEBUG) - Thread.Sleep(1000); + Thread.Sleep(1000); #endif - try - { - //#if (!DEBUG) - //FTPWrapper spfSPN = new FTPWrapper(outputFile, newDestFileName); - //spfSPN.FTPToSPN(); + try { + //#if (!DEBUG) + //FTPWrapper spfSPN = new FTPWrapper(outputFile, newDestFileName); + //spfSPN.FTPToSPN(); - if (BatchFTP(outputFile, newDestFileName)) - { - mrbDMO.UpdateMRB_QDB_HoldFlag(guid, true); - } - else - { - mrbDMO.UpdateMRB_QDB_HoldFlag(guid, false); - } - - //#endif - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + guid.ToString() + " FTPToSPN(): FTP Upload Error " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - return false; + if (mrbDMO.BatchFTP(outputFile, newDestFileName, ftpLogDirectory, userIdentityName, a, b, c)) { + //TODO + mrbDMO.LogHoldFlagSentToSPNHistory(mrbNumber); } + //#endif + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " FTPToSPN(): SendMRBHoldFlagToSPN(mrbNumber) - FTP Upload Error " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); + //return false; } - return true; - } - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + guid.ToString() + " SPN Hold Flag(SendToSPN) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - return false; } - - - - - - } - - catch (Exception e) - { - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "GUID =" + guid.ToString() + " SPN Hold Flag(SendToSPN) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + //return true; + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " SendMRBHoldFlagToSPN(mrbNumber) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - return false; + return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); + ; } - - - + return Json(new { Error = false, Message = "Success" }, JsonRequestBehavior.AllowGet); + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "GUID =" + mrbNumber.ToString() + " SendMRBHoldFlagToSPN(mrbNumber) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); } - - - /// - /// - /// - /// - /// - public bool BatchFTP(string sourceFile, string destFile) - { - FileInfo sourcefile = new FileInfo(sourceFile); - - - //FileInfo sourcefile = new FileInfo(@"C:\Websites\ECNViewerAckResultToSPN\S15122017102017.ecn"); - - try - { - //Functions.WriteEvent("HR Emp", "SPNData - Start Send(): FTPing " + sourceFile + " to SPN server.", System.Diagnostics.EventLogEntryType.Information); - - //System.Security.SecureString ss = new System.Security.SecureString(); - //foreach (char c in credentialsStorage.Password) - // ss.AppendChar(c); - - ProcessStartInfo psiFab1 = new ProcessStartInfo(); - Process procFab1 = new Process(); - StringBuilder sb = new StringBuilder(); - - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") - { - psiFab1.FileName = Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch_Test()); - } - else - { - psiFab1.FileName = Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch()); - } - - psiFab1.Arguments = sourcefile.FullName + " " + destFile; - - psiFab1.RedirectStandardOutput = true; - psiFab1.UseShellExecute = false; - psiFab1.WorkingDirectory = Server.MapPath("/FTPBatch/"); - //credentialsStorage = MiscDMO.GetCredentialsInfo("TEMSA01EC", "LocalAdmin"); - //psiFab1.UserName = credentialsStorage.UserName; - //psiFab1.Password = ss; - - procFab1.StartInfo = psiFab1; - procFab1.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data); ; - procFab1.Start(); - procFab1.BeginOutputReadLine(); - procFab1.WaitForExit(4000); - - string ftpLogDirectory = ConfigurationManager.AppSettings["SPNMRBHoldFlagFTPLogDirectory"].ToString(); - System.IO.File.WriteAllText(Path.Combine(ftpLogDirectory, sourcefile.Name + ".txt"), sb.ToString()); - - - //procFab1.StartInfo = psiFab1; - //procFab1.Start(); - - - - //Functions.WriteEvent("HR Emp", "SPNData - Finish FTPing to SPN server.", System.Diagnostics.EventLogEntryType.Information); - - return true; - } - catch (Exception e) - { - - Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - return false; - } - - - } - - - public bool BatchFTP_Old(string sourceFile, string destFile) - { - FileInfo sourcefile = new FileInfo(sourceFile); - //FileInfo sourcefile = new FileInfo(@"C:\Websites\ECNViewerAckResultToSPN\S15122017102017.ecn"); - - try - { - //Functions.WriteEvent("HR Emp", "SPNData - Start Send(): FTPing " + sourceFile + " to SPN server.", System.Diagnostics.EventLogEntryType.Information); - - ProcessStartInfo psiFab1 = new ProcessStartInfo(); - //psiFab1.FileName = @Functions.FTPSPNBatch(); - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") - { - psiFab1.FileName = Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch_Test()); - } - else - { - psiFab1.FileName = Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch()); - } - - psiFab1.Arguments = sourcefile.FullName + " " + destFile; - - Process procFab1 = new Process(); - procFab1.StartInfo = psiFab1; - procFab1.Start(); - //Functions.WriteEvent("HR Emp", "SPNData - Finish FTPing to SPN server.", System.Diagnostics.EventLogEntryType.Information); - - return true; - } - catch (Exception e) - { - - Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - return false; - } - - - } - - - /// - /// - /// - /// - /// - public FileResult DownloadFile(string attachmentID) - { - //fileName = "ECNForm_71132.pdf"; - - var attachment = mrbDMO.GetMRBAttachment(Convert.ToInt32(attachmentID)); - - if (attachment == null) throw new Exception("Invalid attachment ID"); - - String fileName = attachment.Path; - if (String.IsNullOrEmpty(fileName)) fileName = attachment.FileName; - - var sDocument = Path.Combine(Functions.GetAttachmentFolder() + "MRB", fileName); - var FDir_AppData = Functions.GetAttachmentFolder(); - if (!sDocument.StartsWith(FDir_AppData)) - { - // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder - // and block requests outside like "../web.config" - throw new HttpException(403, "Forbidden"); - } - - if (!System.IO.File.Exists(sDocument)) - { - return null; - //throw new Exception("File not found"); - } - - return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, attachment.FileName); - } - - private string FormCSV(params object[] args) - { - bool first = true; - var sb = new StringBuilder(); - foreach (object arg in args) - { - if (!first) - sb.Append(","); - String s = Convert.ToString(arg); - s = s.Replace('\r', ' ').Replace('\n', ' ').Replace('"', ' '); - if (s.Contains(',')) - { - sb.Append("\""); - sb.Append(s); - sb.Append("\""); - } - else - { - sb.Append(s); - } - first = false; - } - return sb.ToString(); - } - public FileResult ExportMRBHoldFlagReport(int mrbNumber) - { - var sb = new StringBuilder(); - sb.AppendLine("LotNo,PartNo ,CurrentLocation,CurrentOperation,StartQty,CurrentQty,LotStatus,OperStatus,Successful,Comment,PriorMRB_DispoType,PriorMRBHoldLocation,PriorMRBHoldOperation,CurrentMRB_DispoType,CurrentMRBHoldLocation,CurrentMRBHoldOperation,TransactionDatetime"); - foreach (var report in mrbDMO.GetMRBHoldFlagReport(mrbNumber)) - { - sb.AppendLine(FormCSV( - report.LotNo, - report.PartNo, - report.CurrentLocation, - report.CurrentOperation, - report.StartQty, - report.CurrentQty, - report.LotStatus, - report.OperStatus, - report.Successful, - report.Comment, - report.PriorMRB_DispoType, - report.PriorMRBHoldLocation, - report.PriorMRBHoldOperation, - report.CurrentMRB_DispoType, - report.CurrentMRBHoldLocation, - report.CurrentMRBHoldOperation, - report.TransactionDateTime - - )); - } - var b = System.Text.ASCIIEncoding.ASCII.GetBytes(sb.ToString()); - return File(b, "application/octet-stream", "mrb_lots_" + mrbNumber.ToString() + ".csv"); - } - - public FileResult PreviewMRBHoldFlagTobeSentToSPN(int mrbNumber) - { - - var sb = new StringBuilder(); - sb.AppendLine("LotNumber,MRBNumber,DispoType,MRB Flag,Modified,Sent To SPN,Last Sent to SPN"); - foreach (var lot in mrbDMO.GetMRHoldFlagSentHistory(mrbNumber)) - { - sb.AppendLine(FormCSV( - lot.LotNumber, - lot.MRBNumber, - lot.DispoType, - lot.AddRemoveChangeMRBFlag, - lot.IsDirty, - lot.SentToSPN, - lot.MRBLotLastSentToSPNDatetime - )); - } - var b = System.Text.ASCIIEncoding.ASCII.GetBytes(sb.ToString()); - return File(b, "application/octet-stream", "mrb_lots_" + mrbNumber.ToString() + ".csv"); - - } - - public FileResult ExportLots(int mrbNumber) - { - var sb = new StringBuilder(); - sb.AppendLine("LotNumber,DieLotNumber,WipPartNo,DispoType,WaferCount,DiePartNo,DieCount,SourceLot,TotalCost,ProductFamily,Gen,HexSize,Channel,Voltage,Location,Status,QualityCode"); - foreach (var lot in mrbDMO.GetMRBLots(mrbNumber)) - { - sb.AppendLine(FormCSV( - lot.LotNumber, - lot.DieLotNumber, - lot.WipPartNo, - lot.DispoType, - lot.WaferCount, - lot.DiePartNo, - lot.DieCount, - lot.SourceLot, - lot.TotalCost, - lot.ProductFamily, - lot.Gen, - lot.Hexsize, - lot.Channel, - lot.Voltage, - lot.Location, - lot.Status, - lot.QualityCode - )); - } - var b = System.Text.ASCIIEncoding.ASCII.GetBytes(sb.ToString()); - return File(b, "application/octet-stream", "mrb_lots_" + mrbNumber.ToString() + ".csv"); - } - - } -} + + public bool BatchFTP_Old(string sourceFile, string destFile) { + FileInfo sourcefile = new FileInfo(sourceFile); + //FileInfo sourcefile = new FileInfo(@"C:\Websites\ECNViewerAckResultToSPN\S15122017102017.ecn"); + + try { + //Functions.WriteEvent("HR Emp", "SPNData - Start Send(): FTPing " + sourceFile + " to SPN server.", System.Diagnostics.EventLogEntryType.Information); + + ProcessStartInfo psiFab1 = new ProcessStartInfo(); + //psiFab1.FileName = ConfigurationManager.AppSettings["FTPSPNBatchFileName"]; + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { + psiFab1.FileName = Server.MapPath("/FTPBatch/" + ConfigurationManager.AppSettings["FTPSPNBatchFileName_Test"]); + } else { + psiFab1.FileName = Server.MapPath("/FTPBatch/" + ConfigurationManager.AppSettings["FTPSPNBatchFileName"]); + } + + psiFab1.Arguments = sourcefile.FullName + " " + destFile; + + Process procFab1 = new Process(); + procFab1.StartInfo = psiFab1; + procFab1.Start(); + //Functions.WriteEvent("HR Emp", "SPNData - Finish FTPing to SPN server.", System.Diagnostics.EventLogEntryType.Information); + + return true; + } catch (Exception e) { + Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + return false; + } + } + + public FileResult DownloadFile(string attachmentID) { + //fileName = "ECNForm_71132.pdf"; + + var attachment = mrbDMO.GetMRBAttachment(Convert.ToInt32(attachmentID)); + + if (attachment == null) + throw new Exception("Invalid attachment ID"); + + String fileName = attachment.Path; + if (String.IsNullOrEmpty(fileName)) + fileName = attachment.FileName; + + var sDocument = Path.Combine(_AppSettings.AttachmentFolder + "MRB", fileName); + var FDir_AppData = _AppSettings.AttachmentFolder; + if (!sDocument.StartsWith(FDir_AppData)) { + // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder + // and block requests outside like "../web.config" + throw new HttpException(403, "Forbidden"); + } + + if (!System.IO.File.Exists(sDocument)) { + return null; + //throw new Exception("File not found"); + } + + return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, attachment.FileName); + } + + public FileResult ExportMRBHoldFlagReport(int mrbNumber) { + var sb = new StringBuilder(); + sb.AppendLine("LotNo,PartNo ,CurrentLocation,CurrentOperation,StartQty,CurrentQty,LotStatus,OperStatus,Successful,Comment,PriorMRB_DispoType,PriorMRBHoldLocation,PriorMRBHoldOperation,CurrentMRB_DispoType,CurrentMRBHoldLocation,CurrentMRBHoldOperation,TransactionDatetime"); + foreach (var report in mrbDMO.GetMRBHoldFlagReport(mrbNumber)) { + sb.AppendLine(MRB_DMO.FormCSV( + report.LotNo, + report.PartNo, + report.CurrentLocation, + report.CurrentOperation, + report.StartQty, + report.CurrentQty, + report.LotStatus, + report.OperStatus, + report.Successful, + report.Comment, + report.PriorMRB_DispoType, + report.PriorMRBHoldLocation, + report.PriorMRBHoldOperation, + report.CurrentMRB_DispoType, + report.CurrentMRBHoldLocation, + report.CurrentMRBHoldOperation, + report.TransactionDateTime + + )); + } + var b = System.Text.ASCIIEncoding.ASCII.GetBytes(sb.ToString()); + return File(b, "application/octet-stream", "mrb_lots_" + mrbNumber.ToString() + ".csv"); + } + + public FileResult PreviewMRBHoldFlagTobeSentToSPN(int mrbNumber) { + var sb = new StringBuilder(); + sb.AppendLine("LotNumber,MRBNumber,DispoType,MRB Flag,Modified,Sent To SPN,Last Sent to SPN"); + foreach (var lot in mrbDMO.GetMRHoldFlagSentHistory(mrbNumber)) { + sb.AppendLine(MRB_DMO.FormCSV( + lot.LotNumber, + lot.MRBNumber, + lot.DispoType, + lot.AddRemoveChangeMRBFlag, + lot.IsDirty, + lot.SentToSPN, + lot.MRBLotLastSentToSPNDatetime + )); + } + var b = System.Text.ASCIIEncoding.ASCII.GetBytes(sb.ToString()); + return File(b, "application/octet-stream", "mrb_lots_" + mrbNumber.ToString() + ".csv"); + } + + public FileResult ExportLots(int mrbNumber) { + var sb = new StringBuilder(); + sb.AppendLine("LotNumber,DieLotNumber,WipPartNo,DispoType,WaferCount,DiePartNo,DieCount,SourceLot,TotalCost,ProductFamily,Gen,HexSize,Channel,Voltage,Location,Status,QualityCode"); + foreach (var lot in mrbDMO.GetMRBLots(mrbNumber)) { + sb.AppendLine(MRB_DMO.FormCSV( + lot.LotNumber, + lot.DieLotNumber, + lot.WipPartNo, + lot.DispoType, + lot.WaferCount, + lot.DiePartNo, + lot.DieCount, + lot.SourceLot, + lot.TotalCost, + lot.ProductFamily, + lot.Gen, + lot.Hexsize, + lot.Channel, + lot.Voltage, + lot.Location, + lot.Status, + lot.QualityCode + )); + } + var b = System.Text.ASCIIEncoding.ASCII.GetBytes(sb.ToString()); + return File(b, "application/octet-stream", "mrb_lots_" + mrbNumber.ToString() + ".csv"); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/ManagerController.cs b/Fab2ApprovalSystem/Controllers/ManagerController.cs index 9e9a271..3d42577 100644 --- a/Fab2ApprovalSystem/Controllers/ManagerController.cs +++ b/Fab2ApprovalSystem/Controllers/ManagerController.cs @@ -1,37 +1,36 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; + using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; -using Fab2ApprovalSystem.DMO; -using Fab2ApprovalSystem.Misc; -namespace Fab2ApprovalSystem.Controllers -{ - [Authorize] - [SessionExpireFilter] - public class ManagerController : Controller - { - UserAccountDMO userDMO = new UserAccountDMO(); - AdminDMO adminDMO = new AdminDMO(); - TrainingDMO trainingDMO = new TrainingDMO(); - LotDispositionDMO ldDMO = new LotDispositionDMO(); +namespace Fab2ApprovalSystem.Controllers; - /// - /// - /// - /// - public ActionResult Index() - { +[Authorize] +[SessionExpireFilter] +public class ManagerController : Controller { - if ((bool)Session[GlobalVars.IS_MANAGER]) - { - var model = userDMO.GetAllUsers(); - ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers(); - return View(model); - } - else - return Content("Not Autthorized"); - } + UserAccountDMO userDMO = new UserAccountDMO(); + AdminDMO adminDMO = new AdminDMO(); + TrainingDMO trainingDMO = new TrainingDMO(); + LotDispositionDMO ldDMO; + private readonly AppSettings _AppSettings; + + public ManagerController(AppSettings appSettings) { + _AppSettings = appSettings; + ldDMO = new LotDispositionDMO(appSettings); } -} + + public ActionResult Index() { + if ((bool)Session[GlobalVars.IS_MANAGER]) { + var model = userDMO.GetAllUsers(); + ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers(); + return View(model); + } else + return Content("Not Autthorized"); + } +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/PartsRequestController.cs b/Fab2ApprovalSystem/Controllers/PartsRequestController.cs index 2222fe4..ddcad1d 100644 --- a/Fab2ApprovalSystem/Controllers/PartsRequestController.cs +++ b/Fab2ApprovalSystem/Controllers/PartsRequestController.cs @@ -1,753 +1,617 @@ -using System; +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; + +using Kendo.Mvc.Extensions; +using Kendo.Mvc.UI; + +using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; -using Fab2ApprovalSystem.Models; -using Fab2ApprovalSystem.DMO; -using Fab2ApprovalSystem.Misc; -using Kendo.Mvc.Extensions; -using Kendo.Mvc.UI; -namespace Fab2ApprovalSystem.Controllers -{ - [Authorize] - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - [SessionExpireFilter] - public class PartsRequestController : Controller - { - PartsRequestDMO prDMO = new PartsRequestDMO(); - UserAccountDMO userDMO = new UserAccountDMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); +namespace Fab2ApprovalSystem.Controllers; - const int WorkflowNumber = 1; +[Authorize] +[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +[SessionExpireFilter] +public class PartsRequestController : Controller { - public PartsRequestController() - { - ViewBag.ShowReAssignApprovers = false; + + const int WorkflowNumber = 1; + PartsRequestDMO prDMO; + UserAccountDMO userDMO = new UserAccountDMO(); + WorkflowDMO wfDMO = new WorkflowDMO(); + private readonly AppSettings _AppSettings; + + public PartsRequestController(AppSettings appSettings) { + _AppSettings = appSettings; + ViewBag.ShowReAssignApprovers = false; + prDMO = new PartsRequestDMO(appSettings); + } + + protected ActionResult HandleValidationError(string msg) { + Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; + return Json(new { result = "Invalid", detail = msg }); + } + + protected ActionResult HandleAPIException(int issueID, Exception ex, string additionalKeys = "") { + HandleException(issueID, ex, additionalKeys); + + Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; + return Json(new { result = "Error", issueID = issueID, detail = ex.Message }); + } + + protected void HandleException(int issueID, Exception ex, string additionalKeys = "") { + var st = new System.Diagnostics.StackTrace(); + var sf = st.GetFrame(1); + + String controller = sf.GetMethod().DeclaringType.Name.Replace("Controller", ""); + String method = sf.GetMethod().Name; + + string detailedException = String.Format( + "Exception for issue # {0}\r\n" + + "Controller: {1}, Method: {2}, User: {3}, Keys: {4}\r\n" + + "=====\r\n", + issueID, + controller, + method, + User?.Identity?.Name, + additionalKeys); + + Exception x = ex; + while (x != null) { + detailedException += x.ToString(); + detailedException += "\r\n=====\r\n"; + x = x.InnerException; } - protected ActionResult HandleValidationError(string msg) - { - Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; - return Json(new { result = "Invalid", detail = msg }); - } + Functions.WriteEvent(_AppSettings, detailedException, System.Diagnostics.EventLogEntryType.Error); - protected ActionResult HandleAPIException(int issueID, Exception ex, string additionalKeys = "") - { - HandleException(issueID, ex, additionalKeys); + EventLogDMO.Add(new WinEventLog() { + IssueID = issueID, + UserID = @User.Identity.Name, + DocumentType = controller, + OperationType = "Error", + Comments = detailedException + }); + } - Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; - return Json(new { result = "Error", issueID = issueID, detail = ex.Message }); - } + // GET: PartsRequest + public ActionResult Index() { + return View(); + } - protected void HandleException(int issueID, Exception ex, string additionalKeys = "") - { - var st = new System.Diagnostics.StackTrace(); - var sf = st.GetFrame(1); + public ActionResult Edit(int issueID) { + var pr = new PartsRequest(); + try { + pr = prDMO.Get(issueID); - String controller = sf.GetMethod().DeclaringType.Name.Replace("Controller", ""); - String method = sf.GetMethod().Name; - - string detailedException = String.Format( - "Exception for issue # {0}\r\n" + - "Controller: {1}, Method: {2}, User: {3}, Keys: {4}\r\n" + - "=====\r\n", - issueID, - controller, - method, - User?.Identity?.Name, - additionalKeys); - - Exception x = ex; - while (x != null) - { - detailedException += x.ToString(); - detailedException += "\r\n=====\r\n"; - x = x.InnerException; - } - - Functions.WriteEvent(detailedException, System.Diagnostics.EventLogEntryType.Error); - - EventLogDMO.Add(new WinEventLog() - { - IssueID = issueID, - UserID = @User.Identity.Name, - DocumentType = controller, - OperationType = "Error", - Comments = detailedException - }); - - } - - // GET: PartsRequest - public ActionResult Index() - { - return View(); - } - - public ActionResult Edit(int issueID) - { - var pr = new PartsRequest(); - try - { - pr = prDMO.Get(issueID); - - if (pr == null) - { - ViewBag.ErrorDescription = "Document does not exist"; - return View("Error"); - } - else if (pr.CurrentStep < 0) - { - ViewBag.ErrorDescription = "Document is deleted"; - return View("Error"); - } - else if (pr.CurrentStep >= 1) - { - return RedirectToAction("EditApproval", new { issueID = issueID }); - } - else - { - if (pr.OriginatorID != (int)Session[GlobalVars.SESSION_USERID]) - { - if (Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]) == false) - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } - } - - ViewBag.UserList = userDMO.GetAllUsers(); - return View(pr); - } - } - catch (Exception e) - { - HandleException(issueID, e); + if (pr == null) { + ViewBag.ErrorDescription = "Document does not exist"; return View("Error"); - } - } - - [HttpPost] - public ActionResult Edit(PartsRequest pr) - { - try - { - var pr_srv = prDMO.Get(pr.PRNumber); - - if (pr_srv == null) - { - return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document does not exist"); - } - if (pr_srv.CurrentStep < 0) - { - return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document is deleted"); - } - - if (pr_srv.CurrentStep >= 1) - { - return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Parts Request is not editable"); - } - - prDMO.Update(pr); - return Content(""); - } - catch (Exception e) - { - return HandleAPIException(pr.PRNumber, e); - } - } - - public ActionResult EditApproval(int issueID) - { - var pr = new PartsRequest(); - try - { - int myUserID = (int)Session[GlobalVars.SESSION_USERID]; - - pr = prDMO.Get(issueID); - - if (pr == null) - { - ViewBag.ErrorDescription = "Document does not exist"; - return View("Error"); - } - if (pr.CurrentStep < 0) - { - ViewBag.ErrorDescription = "Document is deleted"; - return View("Error"); - } - - var wfStep = wfDMO.GetWorkflowStep((int)GlobalVars.DocumentType.PartsRequest, WorkflowNumber, pr.CurrentStep); - - var userList = MiscDMO.GetPendingApproversListByDocument(issueID, Convert.ToByte(pr.CurrentStep), (int)GlobalVars.DocumentType.PartsRequest); - ViewBag.IsApprover = (userList.Count(u => u.UserID == myUserID) > 0); - - if (ViewBag.IsApprover == false) - { - if (pr.OriginatorID != myUserID) - { - if (Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]) == false) - { - return RedirectToAction("ReadOnly", new { issueID = issueID }); - } + } else if (pr.CurrentStep < 0) { + ViewBag.ErrorDescription = "Document is deleted"; + return View("Error"); + } else if (pr.CurrentStep >= 1) { + return RedirectToAction("EditApproval", new { issueID = issueID }); + } else { + if (pr.OriginatorID != (int)Session[GlobalVars.SESSION_USERID]) { + if (Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]) == false) { + return RedirectToAction("ReadOnly", new { issueID = issueID }); } } - ViewBag.IsAdmin = Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]); - ViewBag.IsOriginator = (pr.OriginatorID == myUserID); - ViewBag.AllowReject = (wfStep != null ? (wfStep.AllowReject.HasValue && wfStep.AllowReject.Value) : false); - ViewBag.ShowReAssignApprovers = ViewBag.IsAdmin || ViewBag.IsOriginator; - ViewBag.ShowAddApprovers = ViewBag.IsAdmin || ViewBag.IsApprover || ViewBag.IsOriginator; ViewBag.UserList = userDMO.GetAllUsers(); return View(pr); } - catch (Exception e) - { - HandleException(issueID, e); - return View("Error"); - } + } catch (Exception e) { + HandleException(issueID, e); + return View("Error"); } + } - public ActionResult ReadOnly(int issueID) - { - var pr = new PartsRequest(); - try - { - int myUserID = (int)Session[GlobalVars.SESSION_USERID]; + [HttpPost] + public ActionResult Edit(PartsRequest pr) { + try { + var pr_srv = prDMO.Get(pr.PRNumber); - pr = prDMO.Get(issueID); - - if (pr == null) - { - ViewBag.ErrorDescription = "Document does not exist"; - return View("Error"); - } - if (pr.CurrentStep < 0) - { - ViewBag.ErrorDescription = "Document is deleted"; - return View("Error"); - } - - ViewBag.IsAdmin = Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]); - ViewBag.IsOriginator = (pr.OriginatorID == myUserID); - ViewBag.UserList = userDMO.GetAllUsers(); - return View(pr); + if (pr_srv == null) { + return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document does not exist"); } - catch (Exception e) - { - HandleException(issueID, e); - return View("Error"); - } - } - - public ActionResult Create() - { - var pr = new PartsRequest(); - try - { - pr.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; - - if (!CanCreatePartsRequest(pr.OriginatorID) && Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]) == false) - throw new Exception("User does not have permission to create Parts Request"); - - prDMO.Insert(pr); - - return RedirectToAction("Edit", new { issueID = pr.PRNumber }); - } - catch (Exception e) - { - return HandleAPIException(pr.PRNumber, e); - } - } - - public static bool CanCreatePartsRequest(int userID) - { - var adminDMO = new AdminDMO(); - var role = adminDMO.GetSubRoles().Where(r => string.Equals(r.RoleName, "Parts Request", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); - if (role != null) - { - var subrole = role.SubRoles.FirstOrDefault(sr => string.Equals(sr.SubRoleCategoryItem, "Originator", StringComparison.OrdinalIgnoreCase)); - if (subrole != null) - { - var users = adminDMO.GetAllUsersBySubRole(subrole.SubRoleID); - if (users.Count(u => u.UserID == userID) > 0) - { - return true; - } - } - } - return false; - } - - public ActionResult Attachment_Read([DataSourceRequest]DataSourceRequest request, int prNumber) - { - try - { - return Json(prDMO.GetAttachments(prNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - catch (Exception ex) - { - return HandleAPIException(prNumber, ex); - } - } - - [HttpPost] - public ActionResult AttachSave(IEnumerable files, int prNumber) - { - // The Name of the Upload component is "files" - if (files != null) - { - foreach (var file in files) - { - // Some browsers send file names with full path. - // We are only interested in the file name. - var fileName = System.IO.Path.GetFileName(file.FileName); - - string prFolderPath = Functions.GetAttachmentFolder() + "PartsRequest\\" + prNumber.ToString(); - - var di = new System.IO.DirectoryInfo(prFolderPath); - if (!di.Exists) - di.Create(); - - var physicalPath = System.IO.Path.Combine(prFolderPath, fileName); - - file.SaveAs(physicalPath); - var attach = new PartsRequestAttachment() - { - PRNumber = prNumber, - FileName = fileName, - UserID = (int)Session[GlobalVars.SESSION_USERID], - }; - prDMO.InsertAttachment(attach); - } + if (pr_srv.CurrentStep < 0) { + return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document is deleted"); } + if (pr_srv.CurrentStep >= 1) { + return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Parts Request is not editable"); + } + + prDMO.Update(pr); return Content(""); + } catch (Exception e) { + return HandleAPIException(pr.PRNumber, e); } + } - public FileResult DownloadFile(string attachmentID, string prNumber) - { - string fileName = prDMO.GetFileName(attachmentID); + public ActionResult EditApproval(int issueID) { + var pr = new PartsRequest(); + try { + int myUserID = (int)Session[GlobalVars.SESSION_USERID]; - string folderPath = Functions.GetAttachmentFolder() + "PartsRequest\\" + prNumber.ToString(); - var sDocument = System.IO.Path.Combine(folderPath, fileName); + pr = prDMO.Get(issueID); - var FDir_AppData = Functions.GetAttachmentFolder(); - if (!sDocument.StartsWith(FDir_AppData)) - { - // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder - // and block requests outside like "../web.config" - throw new HttpException(403, "Forbidden"); + if (pr == null) { + ViewBag.ErrorDescription = "Document does not exist"; + return View("Error"); + } + if (pr.CurrentStep < 0) { + ViewBag.ErrorDescription = "Document is deleted"; + return View("Error"); } - if (!System.IO.File.Exists(sDocument)) - return null; + var wfStep = wfDMO.GetWorkflowStep((int)GlobalVars.DocumentType.PartsRequest, WorkflowNumber, pr.CurrentStep); - return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); - } + var userList = MiscDMO.GetPendingApproversListByDocument(issueID, Convert.ToByte(pr.CurrentStep), (int)GlobalVars.DocumentType.PartsRequest); + ViewBag.IsApprover = (userList.Count(u => u.UserID == myUserID) > 0); - [HttpPost] - public ActionResult DeleteAttachment(int attachmentID, string fileName, int prNumber) - { - try - { - if (ModelState.IsValid) - { - prDMO.DeleteAttachment(attachmentID); - var physicalPath = System.IO.Path.Combine(Functions.GetAttachmentFolder() + @"PartsRequest\" + prNumber.ToString(), fileName); - - if (System.IO.File.Exists(physicalPath)) - { - System.IO.File.Delete(physicalPath); + if (ViewBag.IsApprover == false) { + if (pr.OriginatorID != myUserID) { + if (Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]) == false) { + return RedirectToAction("ReadOnly", new { issueID = issueID }); } } - return Content(""); } - catch (Exception e) - { - return HandleAPIException(prNumber, e, "AttachmentID=" + attachmentID.ToString()); + + ViewBag.IsAdmin = Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]); + ViewBag.IsOriginator = (pr.OriginatorID == myUserID); + ViewBag.AllowReject = (wfStep != null ? (wfStep.AllowReject.HasValue && wfStep.AllowReject.Value) : false); + ViewBag.ShowReAssignApprovers = ViewBag.IsAdmin || ViewBag.IsOriginator; + ViewBag.ShowAddApprovers = ViewBag.IsAdmin || ViewBag.IsApprover || ViewBag.IsOriginator; + ViewBag.UserList = userDMO.GetAllUsers(); + return View(pr); + } catch (Exception e) { + HandleException(issueID, e); + return View("Error"); + } + } + + public ActionResult ReadOnly(int issueID) { + var pr = new PartsRequest(); + try { + int myUserID = (int)Session[GlobalVars.SESSION_USERID]; + + pr = prDMO.Get(issueID); + + if (pr == null) { + ViewBag.ErrorDescription = "Document does not exist"; + return View("Error"); + } + if (pr.CurrentStep < 0) { + ViewBag.ErrorDescription = "Document is deleted"; + return View("Error"); + } + + ViewBag.IsAdmin = Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]); + ViewBag.IsOriginator = (pr.OriginatorID == myUserID); + ViewBag.UserList = userDMO.GetAllUsers(); + return View(pr); + } catch (Exception e) { + HandleException(issueID, e); + return View("Error"); + } + } + + public ActionResult Create() { + var pr = new PartsRequest(); + try { + pr.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + + if (!CanCreatePartsRequest(pr.OriginatorID) && Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]) == false) + throw new Exception("User does not have permission to create Parts Request"); + + prDMO.Insert(pr); + + return RedirectToAction("Edit", new { issueID = pr.PRNumber }); + } catch (Exception e) { + return HandleAPIException(pr.PRNumber, e); + } + } + + public static bool CanCreatePartsRequest(int userID) { + var adminDMO = new AdminDMO(); + var role = adminDMO.GetSubRoles().Where(r => string.Equals(r.RoleName, "Parts Request", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); + if (role != null) { + var subrole = role.SubRoles.FirstOrDefault(sr => string.Equals(sr.SubRoleCategoryItem, "Originator", StringComparison.OrdinalIgnoreCase)); + if (subrole != null) { + var users = adminDMO.GetAllUsersBySubRole(subrole.SubRoleID); + if (users.Count(u => u.UserID == userID) > 0) { + return true; + } + } + } + return false; + } + + public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int prNumber) { + try { + return Json(prDMO.GetAttachments(prNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } catch (Exception ex) { + return HandleAPIException(prNumber, ex); + } + } + + [HttpPost] + public ActionResult AttachSave(IEnumerable files, int prNumber) { + // The Name of the Upload component is "files" + if (files != null) { + int userId = (int)Session[GlobalVars.SESSION_USERID]; + foreach (var file in files) { + prDMO.AttachSave(prNumber, userId, file.FileName, file.InputStream); } } - [HttpPost] - public ActionResult Submit(int prNumber) - { - try - { - int myUserID = (int)Session[GlobalVars.SESSION_USERID]; + return Content(""); + } - var pr = prDMO.Get(prNumber); + public FileResult DownloadFile(string attachmentID, string prNumber) { + string fileName = prDMO.GetFileName(attachmentID); - if (pr == null) - return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document does not exist"); + string folderPath = _AppSettings.AttachmentFolder + "PartsRequest\\" + prNumber.ToString(); + var sDocument = System.IO.Path.Combine(folderPath, fileName); - if (String.IsNullOrWhiteSpace(pr.Title)) - return HandleValidationError("Title is required"); - if (pr.RequestorID <= 0) - return HandleValidationError("Requestor is required"); - if (pr.TechLeadID <= 0) - return HandleValidationError("Tech Lead is required"); + var FDir_AppData = _AppSettings.AttachmentFolder; + if (!sDocument.StartsWith(FDir_AppData)) { + // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder + // and block requests outside like "../web.config" + throw new HttpException(403, "Forbidden"); + } - prDMO.Submit(prNumber, myUserID); + if (!System.IO.File.Exists(sDocument)) + return null; + + return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); + } + + [HttpPost] + public ActionResult DeleteAttachment(int attachmentID, string fileName, int prNumber) { + try { + if (ModelState.IsValid) { + prDMO.DeleteAttachment(attachmentID); + var physicalPath = System.IO.Path.Combine(_AppSettings.AttachmentFolder + @"PartsRequest\" + prNumber.ToString(), fileName); + + if (System.IO.File.Exists(physicalPath)) { + System.IO.File.Delete(physicalPath); + } + } + return Content(""); + } catch (Exception e) { + return HandleAPIException(prNumber, e, "AttachmentID=" + attachmentID.ToString()); + } + } + + [HttpPost] + public ActionResult Submit(int prNumber) { + try { + int myUserID = (int)Session[GlobalVars.SESSION_USERID]; + + var pr = prDMO.Get(prNumber); + + if (pr == null) + return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document does not exist"); + + if (String.IsNullOrWhiteSpace(pr.Title)) + return HandleValidationError("Title is required"); + if (pr.RequestorID <= 0) + return HandleValidationError("Requestor is required"); + if (pr.TechLeadID <= 0) + return HandleValidationError("Tech Lead is required"); + + prDMO.Submit(prNumber, myUserID); + + var approvers = MiscDMO.GetApprovalsByDocument(prNumber, (int)GlobalVars.DocumentType.PartsRequest); + + if (approvers.Count(a => a.Step.HasValue && a.Step.Value == 1 && a.UserID == myUserID) > 0) { + // Auto-Approve if the user is an approver for workflow step 1 + var c = Approve(prNumber, 1, "Auto-Approve"); + if (c != null && c is ContentResult) { + var result = ((ContentResult)c).Content; + if (!String.Equals(result, "OK")) + throw new Exception(result); + } + if (c != null && c is JsonResult) + return c; + } else { + // Do step 1 notification + NotifyApprovers(prNumber, 1); + } + + if (Request.IsAjaxRequest()) { + return Content("Redirect"); + } else { + return Content("Invalid"); + } + + } catch (Exception e) { + return HandleAPIException(prNumber, e); + } + } + + public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) { + try { + return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.PartsRequest).ToDataSourceResult(request)); + } catch (Exception e) { + return HandleAPIException(issueID, e, "Step=" + step.ToString()); + } + } + + public ActionResult GetAllUsersList() { + try { + UserAccountDMO userDMO = new UserAccountDMO(); + IEnumerable userlist = userDMO.GetAllUsers(); + return Json(userlist, JsonRequestBehavior.AllowGet); + } catch (Exception e) { + return HandleAPIException(0, e); + } + } + + [HttpPost] + public ActionResult ReAssignApproval(int issueID, int fromUserID, int userIDs, byte step) { + try { + String email = wfDMO.ReAssignApproval( + issueID, fromUserID, userIDs, step, (int)GlobalVars.DocumentType.PartsRequest); + + NotifyReAssignment(issueID, email); + + return Content("OK"); + } catch (Exception e) { + return HandleAPIException(issueID, e); + } + } + + [HttpPost] + public ActionResult Approve(int prNumber, byte currentStep, string comments) { + try { + bool lastStep = false; + bool lastApproverInCurrentStep = false; + int myUserID = (int)Session[GlobalVars.SESSION_USERID]; + + var pr = prDMO.Get(prNumber); + + if (pr == null) + return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document does not exist"); + + while (true) { + lastApproverInCurrentStep = wfDMO.Approve( + _AppSettings, + prNumber, + currentStep, + comments, + out lastStep, + (int)Session[GlobalVars.SESSION_USERID], + (int)GlobalVars.DocumentType.PartsRequest, + WorkflowNumber); + + if (!lastApproverInCurrentStep) + break; + if (lastStep) { + NotifyCompletion(prNumber); + break; + } + + currentStep++; var approvers = MiscDMO.GetApprovalsByDocument(prNumber, (int)GlobalVars.DocumentType.PartsRequest); + if (approvers.Count(a => a.Step.HasValue && a.Step.Value == currentStep) == 0) + return Content("No approvers found for next step, contact support!"); - if (approvers.Count(a => a.Step.HasValue && a.Step.Value == 1 && a.UserID == myUserID) > 0) - { - // Auto-Approve if the user is an approver for workflow step 1 - var c = Approve(prNumber, 1, "Auto-Approve"); - if (c != null && c is ContentResult) - { - var result = ((ContentResult)c).Content; - if (!String.Equals(result, "OK")) - throw new Exception(result); - } - if (c != null && c is JsonResult) - return c; - } - else - { - // Do step 1 notification - NotifyApprovers(prNumber, 1); + // only continue with approving if the next step has me as an approver also + if (approvers.Count(a => a.Step.HasValue && a.Step.Value == currentStep && a.UserID == myUserID) == 0) { + NotifyApprovers(prNumber, currentStep); + break; } + } - if (Request.IsAjaxRequest()) - { - return Content("Redirect"); - } - else - { - return Content("Invalid"); - } - - } - catch (Exception e) - { - return HandleAPIException(prNumber, e); - } + return Content("OK"); + } catch (Exception e) { + return HandleAPIException(prNumber, e); } - - public ActionResult GetApproversList([DataSourceRequest]DataSourceRequest request, int issueID, byte step) - { - try - { - return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.PartsRequest).ToDataSourceResult(request)); - } - catch (Exception e) - { - return HandleAPIException(issueID, e, "Step=" + step.ToString()); - } - } - - public ActionResult GetAllUsersList() - { - try - { - UserAccountDMO userDMO = new UserAccountDMO(); - IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); - } - catch (Exception e) - { - return HandleAPIException(0, e); - } - } - - [HttpPost] - public ActionResult ReAssignApproval(int issueID, int fromUserID, int userIDs, byte step) - { - try - { - String email = wfDMO.ReAssignApproval( - issueID, fromUserID, userIDs, step, (int)GlobalVars.DocumentType.PartsRequest); - - NotifyReAssignment(issueID, email); - - return Content("OK"); - } - catch (Exception e) - { - return HandleAPIException(issueID, e); - } - } - - [HttpPost] - public ActionResult Approve(int prNumber, byte currentStep, string comments) - { - try - { - bool lastStep = false; - bool lastApproverInCurrentStep = false; - int myUserID = (int)Session[GlobalVars.SESSION_USERID]; - - var pr = prDMO.Get(prNumber); - - if (pr == null) - return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document does not exist"); - - while (true) - { - - lastApproverInCurrentStep = wfDMO.Approve( - prNumber, currentStep, comments, out lastStep, - (int)Session[GlobalVars.SESSION_USERID], - (int)GlobalVars.DocumentType.PartsRequest, - WorkflowNumber); - - if (!lastApproverInCurrentStep) break; - if (lastStep) - { - NotifyCompletion(prNumber); - break; - } - - currentStep++; - - var approvers = MiscDMO.GetApprovalsByDocument(prNumber, (int)GlobalVars.DocumentType.PartsRequest); - if (approvers.Count(a => a.Step.HasValue && a.Step.Value == currentStep) == 0) - return Content("No approvers found for next step, contact support!"); - - // only continue with approving if the next step has me as an approver also - if (approvers.Count(a => a.Step.HasValue && a.Step.Value == currentStep && a.UserID == myUserID) == 0) - { - NotifyApprovers(prNumber, currentStep); - break; - } - } - - return Content("OK"); - } - catch (Exception e) - { - return HandleAPIException(prNumber, e); - } - } - - protected void SendEmailNotification(String subject, int prNumber, string toEmail, string emailTemplate) - { - - string senderName = "Parts Request"; - - EmailNotification en = new EmailNotification(subject, System.Configuration.ConfigurationManager.AppSettings["EmailTemplatesPath"]); - string[] emailparams = new string[5]; - emailparams[0] = prNumber.ToString(); - emailparams[1] = prNumber.ToString(); - emailparams[2] = GlobalVars.hostURL; - emailparams[3] = "Parts Request"; - emailparams[4] = Session[GlobalVars.SESSION_USERNAME].ToString(); - String userEmail = toEmail; - - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - - } - - protected void NotifyReAssignment(int prNumber, string email) - { - var pr = prDMO.Get(prNumber); - - if (pr == null) - return; - - SendEmailNotification( - subject: String.Format("Parts Request Re-Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), - prNumber: prNumber, - toEmail: email, - emailTemplate: "PRReAssigned.txt"); - - EventLogDMO.Add(new WinEventLog() - { - IssueID = prNumber, - UserID = @User.Identity.Name, - DocumentType = "PR", - OperationType = "Email", - Comments = "ReAssigned Approver: " + email - }); - } - - protected void NotifyCompletion(int prNumber) - { - var pr = prDMO.Get(prNumber); - - if (pr == null) - return; - - var u = userDMO.GetUserByID(pr.RequestorID); - if ((u != null) && (!String.IsNullOrWhiteSpace(u.Email))) - { - SendEmailNotification( - subject: String.Format("Parts Request Completion notice for # {0} - {1}", pr.PRNumber, pr.Title), - prNumber: prNumber, - toEmail: u.Email, - emailTemplate: "PRCompleted.txt"); - - EventLogDMO.Add(new WinEventLog() - { - IssueID = prNumber, - UserID = @User.Identity.Name, - DocumentType = "PR", - OperationType = "Email", - Comments = "Completed: " + u.Email - }); - } - } - - public void NotifyRejection(int prNumber) - { - var pr = prDMO.Get(prNumber); - - if (pr == null) - return; - - var u = userDMO.GetUserByID(pr.OriginatorID); - if ((u != null) && (!String.IsNullOrWhiteSpace(u.Email))) - { - SendEmailNotification( - subject: String.Format("Parts Request Rejection notice for # {0} - {1}", pr.PRNumber, pr.Title), - prNumber: prNumber, - toEmail: u.Email, - emailTemplate: "PRReject.txt"); - - EventLogDMO.Add(new WinEventLog() - { - IssueID = prNumber, - UserID = @User.Identity.Name, - DocumentType = "PR", - OperationType = "Email", - Comments = "Rejected: " + u.Email - }); - } - } - - protected void NotifyApprovers(int prNumber, byte step) - { - try - { - string emailSentList = ""; - - var pr = prDMO.Get(prNumber); - - if (pr == null) - throw new Exception("Invalid pr#"); - - List emailList = MiscDMO.GetApproverEmailListByDocument( - prNumber, step, (int)GlobalVars.DocumentType.PartsRequest).Distinct().ToList(); - - foreach (string email in emailList) - { - try - { - SendEmailNotification( - subject: String.Format("Parts Request Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), - prNumber: prNumber, - toEmail: email, - emailTemplate: "PRAssigned.txt"); - } - catch (Exception ex) - { - HandleException(prNumber, ex, "email=" + email); - } - - emailSentList += email + ","; - } - - try - { - EventLogDMO.Add(new WinEventLog() { - IssueID = prNumber, UserID = @User.Identity.Name, DocumentType = "PR", OperationType = "Email", - Comments = "Approvers for Step " + step.ToString() + ":" + emailSentList }); - } - catch { } - } - catch (Exception e) - { - HandleException(prNumber, e, "Step=" + step.ToString()); - } - } - - [HttpPost] - public ActionResult Reject(int prNumber, byte currentStep, string comments) - { - try - { - if (Session[GlobalVars.SESSION_USERID] != null) - { - wfDMO.Reject(prNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.PartsRequest); - NotifyRejection(prNumber); - } - else - { - Response.Redirect("~/Account/Login"); - } - - return Content("OK"); - } - catch (Exception e) - { - return HandleAPIException(prNumber, e); - } - } - - public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int prNumber) - { - return Json(prDMO.GetApprovalLogHistory(prNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); - } - - protected void NotifyAssignment(int prNumber, string email) - { - var pr = prDMO.Get(prNumber); - - if (pr == null) - return; - - SendEmailNotification( - subject: String.Format("Parts Request Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), - prNumber: prNumber, - toEmail: email, - emailTemplate: "PRAssigned.txt"); - - EventLogDMO.Add(new WinEventLog() - { - IssueID = prNumber, - UserID = @User.Identity.Name, - DocumentType = "PR", - OperationType = "Email", - Comments = "Assigned Approver: " + email - }); - } - - [HttpPost] - public void AddAdditionalApproval(int issueID, byte step, string userIDs) - { - var emailArray = ""; - try - { - emailArray = wfDMO.AddAdditionalApproval(issueID, userIDs, step, (int)GlobalVars.DocumentType.PartsRequest); - } - catch (Exception e) - { - HandleAPIException(issueID, e); - } - - string emailSentList = ""; - string[] emaiList = emailArray.Split(new char[] { '~' }); - foreach (string email in emaiList) - { - if (email.Length > 0) - { - NotifyAssignment(issueID, email); - emailSentList += email + ","; - } - - } - - try - { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "PR", - OperationType = "Email", Comments = "Additional Approver: " + emailSentList }); - } - catch { } - } - } -} + + protected void SendEmailNotification(string subject, int prNumber, string toEmail, string emailTemplate) { + string senderName = "Parts Request"; + + EmailNotification en = new EmailNotification(_AppSettings, subject, System.Configuration.ConfigurationManager.AppSettings["EmailTemplatesPath"]); + string[] emailparams = new string[5]; + emailparams[0] = prNumber.ToString(); + emailparams[1] = prNumber.ToString(); + emailparams[2] = GlobalVars.hostURL; + emailparams[3] = "Parts Request"; + emailparams[4] = Session[GlobalVars.SESSION_USERNAME].ToString(); + String userEmail = toEmail; + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + } + + protected void NotifyReAssignment(int prNumber, string email) { + var pr = prDMO.Get(prNumber); + + if (pr == null) + return; + + SendEmailNotification( + subject: String.Format("Parts Request Re-Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), + prNumber: prNumber, + toEmail: email, + emailTemplate: "PRReAssigned.txt"); + + EventLogDMO.Add(new WinEventLog() { + IssueID = prNumber, + UserID = @User.Identity.Name, + DocumentType = "PR", + OperationType = "Email", + Comments = "ReAssigned Approver: " + email + }); + } + + protected void NotifyCompletion(int prNumber) { + var pr = prDMO.Get(prNumber); + + if (pr == null) + return; + + var u = userDMO.GetUserByID(pr.RequestorID); + if ((u != null) && (!String.IsNullOrWhiteSpace(u.Email))) { + SendEmailNotification( + subject: String.Format("Parts Request Completion notice for # {0} - {1}", pr.PRNumber, pr.Title), + prNumber: prNumber, + toEmail: u.Email, + emailTemplate: "PRCompleted.txt"); + + EventLogDMO.Add(new WinEventLog() { + IssueID = prNumber, + UserID = @User.Identity.Name, + DocumentType = "PR", + OperationType = "Email", + Comments = "Completed: " + u.Email + }); + } + } + + public void NotifyRejection(int prNumber) { + var pr = prDMO.Get(prNumber); + + if (pr == null) + return; + + var u = userDMO.GetUserByID(pr.OriginatorID); + if ((u != null) && (!String.IsNullOrWhiteSpace(u.Email))) { + SendEmailNotification( + subject: String.Format("Parts Request Rejection notice for # {0} - {1}", pr.PRNumber, pr.Title), + prNumber: prNumber, + toEmail: u.Email, + emailTemplate: "PRReject.txt"); + + EventLogDMO.Add(new WinEventLog() { + IssueID = prNumber, + UserID = @User.Identity.Name, + DocumentType = "PR", + OperationType = "Email", + Comments = "Rejected: " + u.Email + }); + } + } + + protected void NotifyApprovers(int prNumber, byte step) { + try { + string emailSentList = ""; + + var pr = prDMO.Get(prNumber); + + if (pr == null) + throw new Exception("Invalid pr#"); + + List emailList = MiscDMO.GetApproverEmailListByDocument( + prNumber, step, (int)GlobalVars.DocumentType.PartsRequest).Distinct().ToList(); + + foreach (string email in emailList) { + try { + SendEmailNotification( + subject: String.Format("Parts Request Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), + prNumber: prNumber, + toEmail: email, + emailTemplate: "PRAssigned.txt"); + } catch (Exception ex) { + HandleException(prNumber, ex, "email=" + email); + } + + emailSentList += email + ","; + } + + try { + EventLogDMO.Add(new WinEventLog() { + IssueID = prNumber, + UserID = @User.Identity.Name, + DocumentType = "PR", + OperationType = "Email", + Comments = "Approvers for Step " + step.ToString() + ":" + emailSentList + }); + } catch { } + } catch (Exception e) { + HandleException(prNumber, e, "Step=" + step.ToString()); + } + } + + [HttpPost] + public ActionResult Reject(int prNumber, byte currentStep, string comments) { + try { + if (Session[GlobalVars.SESSION_USERID] != null) { + wfDMO.Reject(prNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.PartsRequest); + NotifyRejection(prNumber); + } else { + Response.Redirect("~/Account/Login"); + } + + return Content("OK"); + } catch (Exception e) { + return HandleAPIException(prNumber, e); + } + } + + public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int prNumber) { + return Json(prDMO.GetApprovalLogHistory(prNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + } + + protected void NotifyAssignment(int prNumber, string email) { + var pr = prDMO.Get(prNumber); + + if (pr == null) + return; + + SendEmailNotification( + subject: String.Format("Parts Request Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), + prNumber: prNumber, + toEmail: email, + emailTemplate: "PRAssigned.txt"); + + EventLogDMO.Add(new WinEventLog() { + IssueID = prNumber, + UserID = @User.Identity.Name, + DocumentType = "PR", + OperationType = "Email", + Comments = "Assigned Approver: " + email + }); + } + + [HttpPost] + public void AddAdditionalApproval(int issueID, byte step, string userIDs) { + var emailArray = ""; + try { + emailArray = wfDMO.AddAdditionalApproval(issueID, userIDs, step, (int)GlobalVars.DocumentType.PartsRequest); + } catch (Exception e) { + HandleAPIException(issueID, e); + } + + string emailSentList = ""; + string[] emaiList = emailArray.Split(new char[] { '~' }); + foreach (string email in emaiList) { + if (email.Length > 0) { + NotifyAssignment(issueID, email); + emailSentList += email + ","; + } + + } + + try { + EventLogDMO.Add(new WinEventLog() { + IssueID = issueID, + UserID = @User.Identity.Name, + DocumentType = "PR", + OperationType = "Email", + Comments = "Additional Approver: " + emailSentList + }); + } catch { } + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/ReportsController.cs b/Fab2ApprovalSystem/Controllers/ReportsController.cs index 3eeabce..1a4a5f2 100644 --- a/Fab2ApprovalSystem/Controllers/ReportsController.cs +++ b/Fab2ApprovalSystem/Controllers/ReportsController.cs @@ -1,221 +1,194 @@ -using System; +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.ViewModels; + +using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; -using Fab2ApprovalSystem.DMO; -using Fab2ApprovalSystem.Misc; -using Fab2ApprovalSystem.ViewModels; +namespace Fab2ApprovalSystem.Controllers; -namespace Fab2ApprovalSystem.Controllers -{ - [Authorize] - [SessionExpireFilter] - public class ReportsController : Controller - { - public const String specialNullString = "~NULL~"; +[Authorize] +[SessionExpireFilter] +public class ReportsController : Controller { + public const String specialNullString = "~NULL~"; - // GET: Export - public ActionResult Index() - { - UserAccountDMO userDMO = new UserAccountDMO(); - ViewBag.HasITARAccess = userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID]); + // GET: Export + public ActionResult Index() { + UserAccountDMO userDMO = new UserAccountDMO(); + ViewBag.HasITARAccess = userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID]); - return View(); - } + return View(); + } - public ActionResult Report(String id, String docType = "") - { - if (String.IsNullOrEmpty(id)) - return RedirectToAction("Index"); + public ActionResult Report(String id, String docType = "") { + if (String.IsNullOrEmpty(id)) + return RedirectToAction("Index"); - UserAccountDMO userDMO = new UserAccountDMO(); - if (!userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID])) - return View("UnAuthorizedAccess"); + UserAccountDMO userDMO = new UserAccountDMO(); + if (!userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID])) + return View("UnAuthorizedAccess"); - var m = new ReportViewModel(); - var reports = GetReportList(docType); - foreach (var report in reports) - { - if (String.Equals(report.ReportID, id, StringComparison.OrdinalIgnoreCase)) - { - m.ReportID = report.ReportID; - m.ReportName = report.Name; - m.Description = report.Description; - m.DocType = docType; + var m = new ReportViewModel(); + var reports = GetReportList(docType); + foreach (var report in reports) { + if (String.Equals(report.ReportID, id, StringComparison.OrdinalIgnoreCase)) { + m.ReportID = report.ReportID; + m.ReportName = report.Name; + m.Description = report.Description; + m.DocType = docType; - var c = SetupSSRSHelperClient(); + var c = SetupSSRSHelperClient(); - m.Parameters = c.GetReportParameters(report.FullPath).Select(parm => - { - var r = new ReportParameterViewModel(); - r.Visible = (parm.PromptUser.HasValue == false || parm.PromptUser == true) && !String.IsNullOrEmpty(parm.Prompt); - r.Prompt = parm.Prompt; - r.Name = parm.Name; - r.HtmlID = "parm_" + parm.Name; + m.Parameters = c.GetReportParameters(report.FullPath).Select(parm => { + var r = new ReportParameterViewModel(); + r.Visible = (parm.PromptUser.HasValue == false || parm.PromptUser == true) && !String.IsNullOrEmpty(parm.Prompt); + r.Prompt = parm.Prompt; + r.Name = parm.Name; + r.HtmlID = "parm_" + parm.Name; - if (parm.MultiValue.HasValue && parm.MultiValue.Value) - r.ControlType = ParameterControlTypes.Multiselect; - else if ((parm.ValidValues != null) && (parm.ValidValues.Length > 0)) - r.ControlType = ParameterControlTypes.Dropdown; - else if (parm.DataType.Equals("DateTime", StringComparison.OrdinalIgnoreCase)) - r.ControlType = ParameterControlTypes.DatePicker; - else - r.ControlType = ParameterControlTypes.Textbox; + if (parm.MultiValue.HasValue && parm.MultiValue.Value) + r.ControlType = ParameterControlTypes.Multiselect; + else if ((parm.ValidValues != null) && (parm.ValidValues.Length > 0)) + r.ControlType = ParameterControlTypes.Dropdown; + else if (parm.DataType.Equals("DateTime", StringComparison.OrdinalIgnoreCase)) + r.ControlType = ParameterControlTypes.DatePicker; + else + r.ControlType = ParameterControlTypes.Textbox; - r.SelectList = null; - if (parm.ValidValues != null) - { - r.SelectList = parm.ValidValues.Select(vv => { - return new SelectListItem() - { - Text = vv.Value, - Value = (vv.Key == null ? specialNullString : vv.Key), - Selected = (parm.DefaultValues != null && parm.DefaultValues.Contains(vv.Key)) - }; - }).ToList(); - } + r.SelectList = null; + if (parm.ValidValues != null) { + r.SelectList = parm.ValidValues.Select(vv => { + return new SelectListItem() { + Text = vv.Value, + Value = (vv.Key == null ? specialNullString : vv.Key), + Selected = (parm.DefaultValues != null && parm.DefaultValues.Contains(vv.Key)) + }; + }).ToList(); + } - r.DefaultValue = ""; - if (parm.DefaultValues != null && parm.DefaultValues.Length > 0) - r.DefaultValue = parm.DefaultValues[0]; + r.DefaultValue = ""; + if (parm.DefaultValues != null && parm.DefaultValues.Length > 0) + r.DefaultValue = parm.DefaultValues[0]; - return r; + return r; - }).ToArray(); - } + }).ToArray(); } - - return View(m); } - public SSRSHelper.SSRSClient SetupSSRSHelperClient() - { - var useCfgForBindings = false; - if (String.Equals(System.Configuration.ConfigurationManager.AppSettings["SSRSBindingsByConfiguration"], "true", StringComparison.OrdinalIgnoreCase)) - useCfgForBindings = true; + return View(m); + } - var c = new SSRSHelper.SSRSClient( - Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSBaseURL"]), - Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSDomain"]), - Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSUsername"]), - Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSPassword"]), - useCfgForBindings); - c.Initialize(); + public SSRSHelper.SSRSClient SetupSSRSHelperClient() { + var useCfgForBindings = false; + if (String.Equals(System.Configuration.ConfigurationManager.AppSettings["SSRSBindingsByConfiguration"], "true", StringComparison.OrdinalIgnoreCase)) + useCfgForBindings = true; - return c; - } + var c = new SSRSHelper.SSRSClient( + Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSBaseURL"]), + Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSDomain"]), + Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSUsername"]), + Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSPassword"]), + useCfgForBindings); + c.Initialize(); - private IEnumerable GetReportList(String docType) - { - String folderName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSFolder"]); - if (folderName.EndsWith("/")) - folderName = folderName.TrimEnd('/'); - if (!String.IsNullOrWhiteSpace(docType)) - folderName = folderName + "/" + docType; + return c; + } - var c = SetupSSRSHelperClient(); - return c.ListReports(folderName); - } + private IEnumerable GetReportList(String docType) { + String folderName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSFolder"]); + if (folderName.EndsWith("/")) + folderName = folderName.TrimEnd('/'); + if (!String.IsNullOrWhiteSpace(docType)) + folderName = folderName + "/" + docType; - public ActionResult GetReports(String docType) - { - var reports = GetReportList(docType); + var c = SetupSSRSHelperClient(); + return c.ListReports(folderName); + } - return Json(new { Data = - reports.Select(r => new ReportViewModel() - { - ReportName = r.Name ?? "", - Description = r.Description ?? "", - ReportID = r.ReportID ?? "", - DocType = docType - }) - }, - JsonRequestBehavior.AllowGet); - } + public ActionResult GetReports(String docType) { + var reports = GetReportList(docType); - [HttpPost] - public ActionResult ExportReport(String DocType, String ReportID) - { - var c = SetupSSRSHelperClient(); - var reports = GetReportList(DocType); + return Json(new { + Data = + reports.Select(r => new ReportViewModel() { + ReportName = r.Name ?? "", + Description = r.Description ?? "", + ReportID = r.ReportID ?? "", + DocType = docType + }) + }, + JsonRequestBehavior.AllowGet); + } - var report = reports.Where(r => String.Equals(r.ReportID, ReportID, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); - if (report == null) - return Content("Invalid report ID"); + [HttpPost] + public ActionResult ExportReport(String DocType, String ReportID) { + var c = SetupSSRSHelperClient(); + var reports = GetReportList(DocType); - var reportParms = c.GetReportParameters(report.FullPath); + var report = reports.Where(r => String.Equals(r.ReportID, ReportID, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); + if (report == null) + return Content("Invalid report ID"); - var parms = new SSRSHelper.ReportParameterCollection(); - parms.Add("DocType", DocType); - parms.Add("UserID", Convert.ToString(Session[GlobalVars.SESSION_USERID])); - parms.Add("BaseURL", GlobalVars.hostURL); + var reportParms = c.GetReportParameters(report.FullPath); - foreach (var rp in reportParms) - { - if (rp.MultiValue.HasValue && rp.MultiValue.Value) - { - foreach (String v in Request.Params.GetValues("parm_" + rp.Name)) - { - parms.Add(rp.Name, v); + var parms = new SSRSHelper.ReportParameterCollection(); + parms.Add("DocType", DocType); + parms.Add("UserID", Convert.ToString(Session[GlobalVars.SESSION_USERID])); + parms.Add("BaseURL", GlobalVars.hostURL); + + foreach (var rp in reportParms) { + if (rp.MultiValue.HasValue && rp.MultiValue.Value) { + foreach (String v in Request.Params.GetValues("parm_" + rp.Name)) { + parms.Add(rp.Name, v); + } + } else { + String value = null; + + if (Request.Params.AllKeys.Contains("parm_" + rp.Name)) + value = Request.Params.GetValues("parm_" + rp.Name).FirstOrDefault(); + + if (value == specialNullString) + value = null; + + if ((rp.AllowBlank.HasValue == false || rp.AllowBlank.Value == false) && value == "") + value = null; + + if (value == null) { + if (rp.Nullable.HasValue == false || rp.Nullable.Value == false) { + if (rp.DefaultValues != null && rp.DefaultValues.Length > 0) + value = rp.DefaultValues[0]; + if (value == null) + continue; } } - else - { - String value = null; - if (Request.Params.AllKeys.Contains("parm_" + rp.Name)) - value = Request.Params.GetValues("parm_" + rp.Name).FirstOrDefault(); - - if (value == specialNullString) - value = null; - - if ((rp.AllowBlank.HasValue == false || rp.AllowBlank.Value == false) && value == "") - value = null; - - if (value == null) - { - if (rp.Nullable.HasValue == false || rp.Nullable.Value == false) - { - if (rp.DefaultValues != null && rp.DefaultValues.Length > 0) - value = rp.DefaultValues[0]; - if (value == null) - continue; - } - } - - parms.Add(rp.Name, value); - } + parms.Add(rp.Name, value); } - - var b = c.ExportReport(report.FullPath, @User.Identity.Name, parms, "EXCELOPENXML"); - try - { - var b2 = c.FreezeExcelHeaders(b); - return File(b2, "application/octet-stream", MakeFilename(report.Name) + ".xlsx"); - } - catch - { - - } - return File(b, "application/octet-stream", MakeFilename(report.Name) + ".xlsx"); - } - protected String MakeFilename(String reportName) - { - String r = ""; - var invalidChars = System.IO.Path.GetInvalidFileNameChars(); - foreach (char c in reportName) - { - if (invalidChars.Contains(c)) - r += '_'; - else - r += c; - } - return r; + var b = c.ExportReport(report.FullPath, @User.Identity.Name, parms, "EXCELOPENXML"); + try { + var b2 = c.FreezeExcelHeaders(b); + return File(b2, "application/octet-stream", MakeFilename(report.Name) + ".xlsx"); + } catch { } - + return File(b, "application/octet-stream", MakeFilename(report.Name) + ".xlsx"); } + + protected String MakeFilename(String reportName) { + String r = ""; + var invalidChars = System.IO.Path.GetInvalidFileNameChars(); + foreach (char c in reportName) { + if (invalidChars.Contains(c)) + r += '_'; + else + r += c; + } + return r; + } + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/TrainingController.cs b/Fab2ApprovalSystem/Controllers/TrainingController.cs index 278f32e..626a5a9 100644 --- a/Fab2ApprovalSystem/Controllers/TrainingController.cs +++ b/Fab2ApprovalSystem/Controllers/TrainingController.cs @@ -1,596 +1,592 @@ using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; -using Fab2ApprovalSystem.ViewModels; using Fab2ApprovalSystem.Utilities; +using Fab2ApprovalSystem.ViewModels; + +using Kendo.Mvc.Extensions; + using System; using System.Collections.Generic; +using System.Configuration; using System.Linq; using System.Web.Mvc; -using Kendo.Mvc.Extensions; -using Fab2ApprovalSystem.Misc; -using System.Configuration; -namespace Fab2ApprovalSystem.Controllers { - [Authorize] - [SessionExpireFilter] - public class TrainingController : Controller { - UserAccountDMO userDMO = new UserAccountDMO(); - AdminDMO adminDMO = new AdminDMO(); - TrainingDMO trainingDMO = new TrainingDMO(); +namespace Fab2ApprovalSystem.Controllers; + +[Authorize] +[SessionExpireFilter] +public class TrainingController : Controller { + + UserAccountDMO userDMO = new UserAccountDMO(); + AdminDMO adminDMO = new AdminDMO(); + TrainingDMO trainingDMO = new TrainingDMO(); + ECN_DMO ecnDMO = new ECN_DMO(); + private readonly AppSettings _AppSettings; + + // GET: Training + public ActionResult Index() { + return View(); + } + + public int Create(int ecnId) { ECN_DMO ecnDMO = new ECN_DMO(); - public EmailUtilities emailer = new EmailUtilities(); - // GET: Training - public ActionResult Index() { - return View(); + //Delete old training if exists + int oldTrainingId = trainingDMO.GetTrainingId(ecnId); + if (oldTrainingId != null && oldTrainingId != 0) { + trainingDMO.DeleteTraining(oldTrainingId); } - //public int Create(int ecnId, List groupIds) - public int Create(int ecnId) { - ECN_DMO ecnDMO = new ECN_DMO(); - - //Delete old training if exists - int oldTrainingId = trainingDMO.GetTrainingId(ecnId); - if (oldTrainingId != null && oldTrainingId != 0) { - trainingDMO.DeleteTraining(oldTrainingId); - } - - int trainingId = trainingDMO.Create(ecnId); - List TrainingGroups = new List(); - TrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId); - string ECNTitle = ecnDMO.GetECN(ecnId).Title; - List Trainees = new List(); - foreach (int group in TrainingGroups) { - Trainees.AddRange(trainingDMO.GetTrainees(group)); - } - Trainees = (from a in Trainees select a).Distinct().ToList(); - - foreach (int trainee in Trainees) { - int assignmentId = trainingDMO.CreateAssignment(trainingId, trainee); - NotifyTrainee(trainee, assignmentId, ecnId, ECNTitle); - } - - return trainingId; + int trainingId = trainingDMO.Create(ecnId); + List TrainingGroups = new List(); + TrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId); + string ECNTitle = ecnDMO.GetECN(ecnId).Title; + List Trainees = new List(); + foreach (int group in TrainingGroups) { + Trainees.AddRange(trainingDMO.GetTrainees(group)); } - public ActionResult AddUserToTrainingAdHoc(int trainingId, int traineeId, int ecnId) { - if ((bool)Session[GlobalVars.IS_ADMIN]) { - //Get ECN - ECN ecn = ecnDMO.GetECN(ecnId); + Trainees = (from a in Trainees select a).Distinct().ToList(); - //Get User - LoginModel user = userDMO.GetUserByID(traineeId); - - //Get Training - Training training = trainingDMO.GetTraining(trainingId); - if (ecn != null) { - if (user != null) { - if (training != null) { - if (!trainingDMO.IsUserAssigned(traineeId, trainingId)) { - if (training.DeletedDate == null && !ecn.Deleted) { - //Both the ECN and training still exist - if (training.CompletedDate != null) { - //Training is completed and now we need to re-open it. - trainingDMO.reOpenTraining(trainingId); - int assignmentId = trainingDMO.CreateAssignment(trainingId, traineeId); - NotifyTrainee(traineeId, assignmentId, ecnId, ecn.Title); - return Content("Success"); - } else { - //training is still open, just add a user and notify - int assignmentId = trainingDMO.CreateAssignment(trainingId, traineeId); - NotifyTrainee(traineeId, assignmentId, ecnId, ecn.Title); - return Content("Success"); - } - } else { - //Ecn or training task have been deleted. - return Content("Training or ECN has been deleted."); - } - } else { - return Content("User already has an open or completed assignment for this training."); - } - } else { - return Content("Invalid training id."); - } - } else { - return Content("invalid userId"); - } - } else { - return Content("ECN invalid"); - } - } else { - return Content("Not Authorized"); - } + foreach (int trainee in Trainees) { + int assignmentId = trainingDMO.CreateAssignment(trainingId, trainee); + NotifyTrainee(trainee, assignmentId, ecnId, ECNTitle); } - public ActionResult AddGroupToTrainingAdHoc(int trainingId, int groupId, int ecnId) { - if ((bool)Session[GlobalVars.IS_ADMIN]) { - ECN ecn = ecnDMO.GetECN(ecnId); - Training training = trainingDMO.GetTraining(trainingId); - TrainingGroup group = trainingDMO.GetTrainingGroupByID(groupId); - List groupMemberIds = trainingDMO.GetTrainees(groupId); - int usersAdded = 0; + return trainingId; + } + public ActionResult AddUserToTrainingAdHoc(int trainingId, int traineeId, int ecnId) { + if ((bool)Session[GlobalVars.IS_ADMIN]) { + //Get ECN + ECN ecn = ecnDMO.GetECN(ecnId); - if (ecn != null) { + //Get User + LoginModel user = userDMO.GetUserByID(traineeId); + + //Get Training + Training training = trainingDMO.GetTraining(trainingId); + if (ecn != null) { + if (user != null) { if (training != null) { - if (training.DeletedDate == null && !ecn.Deleted) { - if (training.CompletedDate != null) { - //Training is completed and now we need to re-open it. - foreach (int id in groupMemberIds) { - //Check to make sure user doesn't have an active assignment for this training - if (!trainingDMO.IsUserAssigned(id, trainingId)) { - usersAdded++; - int assignmentId = trainingDMO.CreateAssignment(trainingId, id); - NotifyTrainee(id, assignmentId, ecnId, ecn.Title); - } - } - if (usersAdded > 0) { + if (!trainingDMO.IsUserAssigned(traineeId, trainingId)) { + if (training.DeletedDate == null && !ecn.Deleted) { + //Both the ECN and training still exist + if (training.CompletedDate != null) { + //Training is completed and now we need to re-open it. trainingDMO.reOpenTraining(trainingId); + int assignmentId = trainingDMO.CreateAssignment(trainingId, traineeId); + NotifyTrainee(traineeId, assignmentId, ecnId, ecn.Title); + return Content("Success"); + } else { + //training is still open, just add a user and notify + int assignmentId = trainingDMO.CreateAssignment(trainingId, traineeId); + NotifyTrainee(traineeId, assignmentId, ecnId, ecn.Title); + return Content("Success"); } } else { - //training is still open, just add a users and notify - foreach (int id in groupMemberIds) { - //Check to make sure user doesn't have an active assignment for this training - if (!trainingDMO.IsUserAssigned(id, trainingId)) { - usersAdded++; - int assignmentId = trainingDMO.CreateAssignment(trainingId, id); - NotifyTrainee(id, assignmentId, ecnId, ecn.Title); - } - } + //Ecn or training task have been deleted. + return Content("Training or ECN has been deleted."); } - if (usersAdded > 0) { - try { - trainingDMO.AddTrainingGroupToECN(ecnId, groupId); - } catch (Exception e) { - return Content(e.ToString()); - } - } - return Content("Success. " + usersAdded + " users added."); } else { - return Content("Training or ECN has been deleted."); + return Content("User already has an open or completed assignment for this training."); } } else { return Content("Invalid training id."); } } else { - return Content("ECN invalid"); + return Content("invalid userId"); } } else { - return Content("Not Authorized"); + return Content("ECN invalid"); } + } else { + return Content("Not Authorized"); } + } - public ActionResult DeleteTrainingByECN(int ECNNumber) { - int trainingId = trainingDMO.GetTrainingId(ECNNumber); - if (trainingId != null && trainingId != 0) { - trainingDMO.DeleteTraining(trainingId); + public ActionResult AddGroupToTrainingAdHoc(int trainingId, int groupId, int ecnId) { + if ((bool)Session[GlobalVars.IS_ADMIN]) { + ECN ecn = ecnDMO.GetECN(ecnId); + Training training = trainingDMO.GetTraining(trainingId); + TrainingGroup group = trainingDMO.GetTrainingGroupByID(groupId); + List groupMemberIds = trainingDMO.GetTrainees(groupId); + int usersAdded = 0; + + if (ecn != null) { + if (training != null) { + if (training.DeletedDate == null && !ecn.Deleted) { + if (training.CompletedDate != null) { + //Training is completed and now we need to re-open it. + foreach (int id in groupMemberIds) { + //Check to make sure user doesn't have an active assignment for this training + if (!trainingDMO.IsUserAssigned(id, trainingId)) { + usersAdded++; + int assignmentId = trainingDMO.CreateAssignment(trainingId, id); + NotifyTrainee(id, assignmentId, ecnId, ecn.Title); + } + } + if (usersAdded > 0) { + trainingDMO.reOpenTraining(trainingId); + } + } else { + //training is still open, just add a users and notify + foreach (int id in groupMemberIds) { + //Check to make sure user doesn't have an active assignment for this training + if (!trainingDMO.IsUserAssigned(id, trainingId)) { + usersAdded++; + int assignmentId = trainingDMO.CreateAssignment(trainingId, id); + NotifyTrainee(id, assignmentId, ecnId, ecn.Title); + } + } + } + if (usersAdded > 0) { + try { + trainingDMO.AddTrainingGroupToECN(ecnId, groupId); + } catch (Exception e) { + return Content(e.ToString()); + } + } + return Content("Success. " + usersAdded + " users added."); + } else { + return Content("Training or ECN has been deleted."); + } + } else { + return Content("Invalid training id."); + } + } else { + return Content("ECN invalid"); } - return RedirectToAction("ViewTrainings"); + } else { + return Content("Not Authorized"); } + } - public ActionResult DeleteTrainingByID(int trainingId) { - if (trainingId != null && trainingId != 0) { - trainingDMO.DeleteTraining(trainingId); - } - return RedirectToAction("ViewTrainings"); + public ActionResult DeleteTrainingByECN(int ECNNumber) { + int trainingId = trainingDMO.GetTrainingId(ECNNumber); + if (trainingId != null && trainingId != 0) { + trainingDMO.DeleteTraining(trainingId); } + return RedirectToAction("ViewTrainings"); + } - public void NotifyTrainee(int userId, int assignmentId, int ecnId, string title) { + public ActionResult DeleteTrainingByID(int trainingId) { + if (trainingId != null && trainingId != 0) { + trainingDMO.DeleteTraining(trainingId); + } + return RedirectToAction("ViewTrainings"); + } + + public void NotifyTrainee(int userId, int assignmentId, int ecnId, string title) { + try { + string emailSentList = ""; + string recipient = userDMO.GetUserEmailByID(userId); + + string emailTemplate = "ECNTrainingAssigned.txt"; + string userEmail = string.Empty; + string subject = string.Empty; + string senderName = "ECN Training"; + + subject = "ECN# " + ecnId + " - Training Assignment Notice - " + title; + + EmailNotification en = new EmailNotification(_AppSettings, subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); + userEmail = recipient; + string[] emailparams = new string[4]; + emailparams[0] = assignmentId.ToString(); + emailparams[1] = ecnId.ToString(); + emailparams[2] = GlobalVars.hostURL; + //#if(DEBUG) + //string SenderEmail = "MesaFabApproval@infineon.com"; + //userEmail = "jonathan.ouellette@infineon.com"; + //#endif + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + } catch (Exception e) { + string detailedException = ""; try { - string emailSentList = ""; - string recipient = userDMO.GetUserEmailByID(userId.ToString()); + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + } + } - string emailTemplate = "ECNTrainingAssigned.txt"; - string userEmail = string.Empty; - string subject = string.Empty; - string senderName = "ECN Training"; + public ActionResult ViewTrainingPartial(int trainingID, int userID) { + List TrainingData = trainingDMO.GetTrainingAssignmentsByUser(trainingID, userID); + if (trainingID > 0) { + ViewBag.ECNNumber = trainingDMO.GetTraining(trainingID).ECN; + } + return PartialView(TrainingData); + } - subject = "ECN# " + ecnId + " - Training Assignment Notice - " + title; + public ActionResult ViewTrainingDocsPartial(int trainingAssignmentId) { + ViewBag.trainingAssignmentId = trainingAssignmentId; + //IEnumerable attachments = ecnDMO.GetECNAttachments(ecnNumber); + IEnumerable attachments = trainingDMO.GetAssignedDocs(trainingAssignmentId); + return PartialView(attachments); + } - EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - userEmail = recipient; - string[] emailparams = new string[4]; - emailparams[0] = assignmentId.ToString(); - emailparams[1] = ecnId.ToString(); - emailparams[2] = GlobalVars.hostURL; - //#if(DEBUG) - //string SenderEmail = "MesaFabApproval@infineon.com"; - //userEmail = "jonathan.ouellette@infineon.com"; - //#endif + public ActionResult AcknowledgeDocument(int trainingAssignmentID, int trainingDocAckID) { + //Check to see if acknowledgement is valid(Security Feature to protect data integrity) + if (trainingDMO.CheckValidDocAck(trainingDocAckID)) { + trainingDMO.AcknowledgeDocument(trainingDocAckID); + bool isFinishedTrainingAssignment = trainingDMO.CheckTrainingAssignmentStatus(trainingAssignmentID); - en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - } catch (Exception e) { - string detailedException = ""; + if (isFinishedTrainingAssignment) { try { - detailedException = e.InnerException.ToString(); - } catch { - detailedException = e.Message; + trainingDMO.UpdateAssignmentStatus(trainingAssignmentID); + bool isFinishedTraining = trainingDMO.CheckTrainingStatus(trainingAssignmentID); + if (isFinishedTraining) { + int TrainingID = trainingDMO.GetTrainingIdByAssignment(trainingAssignmentID); + trainingDMO.UpdateTrainingStatus(TrainingID); + } + } catch (Exception e) { + string exception = e.ToString(); + return Content(exception); } } } - public ActionResult ViewTrainingPartial(int trainingID, int userID) { - List TrainingData = trainingDMO.GetTrainingAssignmentsByUser(trainingID, userID); - if (trainingID > 0) { - ViewBag.ECNNumber = trainingDMO.GetTraining(trainingID).ECN; + return Content("Marked Succesfully."); + } + + public ActionResult AcknowledgeReviewNoDocuments(int trainingAssignmentID) { + try { + trainingDMO.UpdateAssignmentStatus(trainingAssignmentID); + bool isFinishedTraining = trainingDMO.CheckTrainingStatus(trainingAssignmentID); + if (isFinishedTraining) { + int TrainingID = trainingDMO.GetTrainingIdByAssignment(trainingAssignmentID); + trainingDMO.UpdateTrainingStatus(TrainingID); } - return PartialView(TrainingData); + } catch (Exception e) { + string exception = e.ToString(); + return Content(exception, "application/json"); } - public ActionResult ViewTrainingDocsPartial(int trainingAssignmentId) { - ViewBag.trainingAssignmentId = trainingAssignmentId; - //IEnumerable attachments = ecnDMO.GetECNAttachments(ecnNumber); - IEnumerable attachments = trainingDMO.GetAssignedDocs(trainingAssignmentId); - return PartialView(attachments); - } + return Json(new { test = "Succesfully saved" }); + } - public ActionResult AcknowledgeDocument(int trainingAssignmentID, int trainingDocAckID) { - //Check to see if acknowledgement is valid(Security Feature to protect data integrity) - if (trainingDMO.CheckValidDocAck(trainingDocAckID)) { - trainingDMO.AcknowledgeDocument(trainingDocAckID); - bool isFinishedTrainingAssignment = trainingDMO.CheckTrainingAssignmentStatus(trainingAssignmentID); + public ActionResult TrainingReports() { + return View(); + } - if (isFinishedTrainingAssignment) { - try { - trainingDMO.UpdateAssignmentStatus(trainingAssignmentID); - bool isFinishedTraining = trainingDMO.CheckTrainingStatus(trainingAssignmentID); - if (isFinishedTraining) { - int TrainingID = trainingDMO.GetTrainingIdByAssignment(trainingAssignmentID); - trainingDMO.UpdateTrainingStatus(TrainingID); - } - } catch (Exception e) { - string exception = e.ToString(); - return Content(exception); + public ActionResult TrainingReportsView(int? filterType, string filterValue) { + ViewBag.TrainingGroups = adminDMO.GetTrainingGroups(); + IEnumerable trainingList = trainingDMO.GetAllTrainings(); + //Group Filter + if (filterType == 1 && filterValue != "") { + ViewBag.GroupFilter = filterValue; + List filteredTraining = new List(); + foreach (Training item in trainingList) { + List assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN); + foreach (int id in assignedTrainingGroups) { + if (filterValue == id.ToString()) { + filteredTraining.Add(item); } } } + trainingList = filteredTraining; + return PartialView(trainingList); + } + //Status Filter + if (filterType == 2 && filterValue != "") { + List filteredTraining = new List(); + switch (filterValue) { + case "1": + //Completed + filteredTraining = (from a in trainingList where a.Status == true && a.Deleted != true select a).ToList(); + break; + case "2": + //In Progress + filteredTraining = (from a in trainingList where a.Status != true && a.Deleted != true select a).ToList(); + break; + case "3": + //Cancelled + filteredTraining = (from a in trainingList where a.Deleted == true select a).ToList(); + break; + } + trainingList = filteredTraining; + return PartialView(trainingList); + } + //Default return all. + else { + return PartialView(trainingList); + } + } - return Content("Marked Succesfully."); + public ActionResult ViewTrainingAssignmentsReportView(int trainingID, string statusFilter, string groupFilter) { + bool? trainingStatus = trainingDMO.GetTraining(trainingID).Status; + int ECNNumber = trainingDMO.GetTraining(trainingID).ECN; + string ECNTitle = ecnDMO.GetECN(ECNNumber).Title; + ViewBag.TrainingGroups = adminDMO.GetTrainingGroups(); + ViewBag.TrainingStatus = trainingStatus; + ViewBag.ECNNumber = ECNNumber; + ViewBag.ECNTitle = ECNTitle; + ViewBag.trainingID = trainingID; + IEnumerable trainingAssignments = trainingDMO.GetAllTrainingAssignments(trainingID); + //Calculate Percent Complete: + float percentComplete = 0; + //float assignmentCount = trainingAssignments.Count(); + float assignmentCount = (from a in trainingAssignments where a.Deleted != true select a).Count(); + float totalCompleted = 0; + foreach (TrainingAssignment assignment in trainingAssignments) { + if (assignment.status == true && assignment.Deleted != true) { + totalCompleted++; + } + } + percentComplete = totalCompleted / assignmentCount * 100; + ViewBag.PercentComplete = percentComplete.ToString("0.00") + "%"; + + if (groupFilter != "" && groupFilter != null) { + ViewBag.GroupFilter = groupFilter; + List groupFilteredTraining = new List(); + List groupMemberIds = trainingDMO.GetTrainees(Convert.ToInt32(groupFilter)); + foreach (TrainingAssignment assignment in trainingAssignments) { + if (trainingDMO.isUserTrainingMember(Convert.ToInt32(groupFilter), assignment.UserID)) { + groupFilteredTraining.Add(assignment); + } + } + trainingAssignments = groupFilteredTraining; + } + if (statusFilter != "" && statusFilter != null) { + List filteredTraining = new List(); + switch (statusFilter) { + case "1": + //Completed + filteredTraining = (from a in trainingAssignments where a.status == true && a.Deleted != true select a).ToList(); + break; + case "2": + //In Progress + filteredTraining = (from a in trainingAssignments where a.status != true && a.Deleted != true select a).ToList(); + break; + case "3": + //Cancelled + filteredTraining = (from a in trainingAssignments where a.Deleted == true select a).ToList(); + break; + default: + filteredTraining = (from a in trainingAssignments select a).ToList(); + break; + } + trainingAssignments = filteredTraining; + //return PartialView(trainingList); } - public ActionResult AcknowledgeReviewNoDocuments(int trainingAssignmentID) { + return PartialView(trainingAssignments); + } + + public ActionResult ViewTrainingAssignments(int trainingID) { + bool? trainingStatus = trainingDMO.GetTraining(trainingID).Status; + int ECNNumber = trainingDMO.GetTraining(trainingID).ECN; + string ECNTitle = ecnDMO.GetECN(ECNNumber).Title; + ViewBag.TrainingStatus = trainingStatus; + ViewBag.ECNNumber = ECNNumber; + ViewBag.ECNTitle = ECNTitle; + ViewBag.TrainingId = trainingID; + ViewBag.AllUsers = userDMO.GetAllActiveUsers(); + ViewBag.AllGroups = trainingDMO.GetTrainingGroups(); + IEnumerable trainingAssignments = trainingDMO.GetTrainingAssignments(trainingID); + + return View(trainingAssignments); + } + + /// + /// Method to return all the training assignments for a specified user + /// + public ActionResult ViewMyTrainingAssignments() { + int userID = (int)Session[GlobalVars.SESSION_USERID]; + List assignments = trainingDMO.GetTrainingAssignmentsByUserID(userID); + List ViewData = new List(); + foreach (TrainingAssignment assignment in assignments) { + Training training = trainingDMO.GetTraining(assignment.TrainingID); + if (training != null && !assignment.status) { + int ecnID = training.ECN; + ViewData.Add(new ECNTrainingAssignments { + TrainingAssignmentID = assignment.ID, + ECN_ID = ecnID, + TrainingID = assignment.TrainingID, + DateAssigned = assignment.DateAssigned, + DateCompleted = assignment.DateCompleted, + Status = assignment.status + }); + } + } + + return View(ViewData); + } + + /// + /// Method to return all assigned documents for a specified training assignment + /// + public ActionResult ViewMyTrainingAssignment(int assignmentID, int ECNNumber) { + ViewBag.ECNNumber = ECNNumber; + ViewBag.AssignmentID = assignmentID; + ViewBag.IsCompleted = trainingDMO.GetAssignment(assignmentID).status; + return View(trainingDMO.GetAssignedDocs(assignmentID)); + } + + public ActionResult ViewTrainings(int? filterType, string filterValue) { + IEnumerable AllTrainings = trainingDMO.GetTrainings(); + ViewBag.TrainingGroups = adminDMO.GetTrainingGroups(); + ViewBag.AllGroups = trainingDMO.GetTrainingGroups(); + //Group Filter + if (filterType == 1 && filterValue != "") { + ViewBag.GroupFilter = filterValue; + List filteredTraining = new List(); + foreach (Training item in AllTrainings) { + List assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN); + foreach (int id in assignedTrainingGroups) { + if (filterValue == id.ToString()) { + filteredTraining.Add(item); + } + } + } + AllTrainings = filteredTraining; + return View(AllTrainings); + } else { + ViewBag.AllGroups = trainingDMO.GetTrainingGroups(); + return View(AllTrainings); + } + } + + public ActionResult ViewAllTrainings() { + return View(); + } + + public ActionResult DeleteAssignment(int assignmentId) { + trainingDMO.DeleteTrainingAssignment(assignmentId); + trainingDMO.DeleteTrainingDocAck(assignmentId); + + //Below checks and updates the training status + //TO-DO Put this in its own method. + bool isFinishedTrainingAssignment = trainingDMO.CheckTrainingAssignmentStatus(assignmentId); + + if (isFinishedTrainingAssignment) { try { - trainingDMO.UpdateAssignmentStatus(trainingAssignmentID); - bool isFinishedTraining = trainingDMO.CheckTrainingStatus(trainingAssignmentID); + trainingDMO.UpdateAssignmentStatus(assignmentId); + bool isFinishedTraining = trainingDMO.CheckTrainingStatus(assignmentId); if (isFinishedTraining) { - int TrainingID = trainingDMO.GetTrainingIdByAssignment(trainingAssignmentID); + int TrainingID = trainingDMO.GetTrainingIdByAssignment(assignmentId); trainingDMO.UpdateTrainingStatus(TrainingID); } } catch (Exception e) { string exception = e.ToString(); return Content(exception, "application/json"); } - - return Json(new { test = "Succesfully saved" }); } - public ActionResult TrainingReports() { - return View(); - } + return Json(new { test = "Succesfully saved" }); + } - public ActionResult TrainingReportsView(int? filterType, string filterValue) { - ViewBag.TrainingGroups = adminDMO.GetTrainingGroups(); - IEnumerable trainingList = trainingDMO.GetAllTrainings(); - //Group Filter - if (filterType == 1 && filterValue != "") { - ViewBag.GroupFilter = filterValue; - List filteredTraining = new List(); - foreach (Training item in trainingList) { - List assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN); - foreach (int id in assignedTrainingGroups) { - if (filterValue == id.ToString()) { - filteredTraining.Add(item); - } - } - } - trainingList = filteredTraining; - return PartialView(trainingList); - } - //Status Filter - if (filterType == 2 && filterValue != "") { - List filteredTraining = new List(); - switch (filterValue) { - case "1": - //Completed - filteredTraining = (from a in trainingList where a.Status == true && a.Deleted != true select a).ToList(); - break; - case "2": - //In Progress - filteredTraining = (from a in trainingList where a.Status != true && a.Deleted != true select a).ToList(); - break; - case "3": - //Cancelled - filteredTraining = (from a in trainingList where a.Deleted == true select a).ToList(); - break; - } - trainingList = filteredTraining; - return PartialView(trainingList); - } - //Default return all. - else { - return PartialView(trainingList); - } - } - - public ActionResult ViewTrainingAssignmentsReportView(int trainingID, string statusFilter, string groupFilter) { - bool? trainingStatus = trainingDMO.GetTraining(trainingID).Status; - int ECNNumber = trainingDMO.GetTraining(trainingID).ECN; - string ECNTitle = ecnDMO.GetECN(ECNNumber).Title; - ViewBag.TrainingGroups = adminDMO.GetTrainingGroups(); - ViewBag.TrainingStatus = trainingStatus; - ViewBag.ECNNumber = ECNNumber; - ViewBag.ECNTitle = ECNTitle; - ViewBag.trainingID = trainingID; - IEnumerable trainingAssignments = trainingDMO.GetAllTrainingAssignments(trainingID); - //Calculate Percent Complete: - float percentComplete = 0; - //float assignmentCount = trainingAssignments.Count(); - float assignmentCount = (from a in trainingAssignments where a.Deleted != true select a).Count(); - float totalCompleted = 0; - foreach (TrainingAssignment assignment in trainingAssignments) { - if (assignment.status == true && assignment.Deleted != true) { - totalCompleted++; - } - } - percentComplete = totalCompleted / assignmentCount * 100; - ViewBag.PercentComplete = percentComplete.ToString("0.00") + "%"; - - if (groupFilter != "" && groupFilter != null) { - ViewBag.GroupFilter = groupFilter; - List groupFilteredTraining = new List(); - List groupMemberIds = trainingDMO.GetTrainees(Convert.ToInt32(groupFilter)); - foreach (TrainingAssignment assignment in trainingAssignments) { - if (trainingDMO.isUserTrainingMember(Convert.ToInt32(groupFilter), assignment.UserID)) { - groupFilteredTraining.Add(assignment); - } - } - trainingAssignments = groupFilteredTraining; - - } - if (statusFilter != "" && statusFilter != null) { - List filteredTraining = new List(); - switch (statusFilter) { - - case "1": - //Completed - filteredTraining = (from a in trainingAssignments where a.status == true && a.Deleted != true select a).ToList(); - break; - case "2": - //In Progress - filteredTraining = (from a in trainingAssignments where a.status != true && a.Deleted != true select a).ToList(); - break; - case "3": - //Cancelled - filteredTraining = (from a in trainingAssignments where a.Deleted == true select a).ToList(); - break; - default: - filteredTraining = (from a in trainingAssignments select a).ToList(); - break; - } - trainingAssignments = filteredTraining; - //return PartialView(trainingList); - } - - return PartialView(trainingAssignments); - } - - public ActionResult ViewTrainingAssignments(int trainingID) { - bool? trainingStatus = trainingDMO.GetTraining(trainingID).Status; - int ECNNumber = trainingDMO.GetTraining(trainingID).ECN; - string ECNTitle = ecnDMO.GetECN(ECNNumber).Title; - ViewBag.TrainingStatus = trainingStatus; - ViewBag.ECNNumber = ECNNumber; - ViewBag.ECNTitle = ECNTitle; - ViewBag.TrainingId = trainingID; - ViewBag.AllUsers = userDMO.GetAllActiveUsers(); - ViewBag.AllGroups = trainingDMO.GetTrainingGroups(); - IEnumerable trainingAssignments = trainingDMO.GetTrainingAssignments(trainingID); - - return View(trainingAssignments); - } - - /// - /// Method to return all the training assignments for a specified user - /// - /// - /// - public ActionResult ViewMyTrainingAssignments() { - int userID = (int)Session[GlobalVars.SESSION_USERID]; - List assignments = trainingDMO.GetTrainingAssignmentsByUserID(userID); - List ViewData = new List(); - foreach (TrainingAssignment assignment in assignments) { - Training training = trainingDMO.GetTraining(assignment.TrainingID); - if (training != null && !assignment.status) { - int ecnID = training.ECN; - ViewData.Add(new ECNTrainingAssignments { - TrainingAssignmentID = assignment.ID, - ECN_ID = ecnID, - TrainingID = assignment.TrainingID, - DateAssigned = assignment.DateAssigned, - DateCompleted = assignment.DateCompleted, - Status = assignment.status - }); - } - } - - return View(ViewData); - } - - /// - /// Method to return all assigned documents for a specified training assignment - /// - /// - /// - public ActionResult ViewMyTrainingAssignment(int assignmentID, int ECNNumber) { - ViewBag.ECNNumber = ECNNumber; - ViewBag.AssignmentID = assignmentID; - ViewBag.IsCompleted = trainingDMO.GetAssignment(assignmentID).status; - return View(trainingDMO.GetAssignedDocs(assignmentID)); - } - - public ActionResult ViewTrainings(int? filterType, string filterValue) { - IEnumerable AllTrainings = trainingDMO.GetTrainings(); - ViewBag.TrainingGroups = adminDMO.GetTrainingGroups(); - ViewBag.AllGroups = trainingDMO.GetTrainingGroups(); - //Group Filter - if (filterType == 1 && filterValue != "") { - ViewBag.GroupFilter = filterValue; - List filteredTraining = new List(); - foreach (Training item in AllTrainings) { - List assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN); - foreach (int id in assignedTrainingGroups) { - if (filterValue == id.ToString()) { - filteredTraining.Add(item); - } - } - } - AllTrainings = filteredTraining; - return View(AllTrainings); - } else { - ViewBag.AllGroups = trainingDMO.GetTrainingGroups(); - return View(AllTrainings); - } - } - - public ActionResult ViewAllTrainings() { - return View(); - } - - public ActionResult DeleteAssignment(int assignmentId) { - trainingDMO.DeleteTrainingAssignment(assignmentId); - trainingDMO.DeleteTrainingDocAck(assignmentId); - - //Below checks and updates the training status - //TO-DO Put this in its own method. - bool isFinishedTrainingAssignment = trainingDMO.CheckTrainingAssignmentStatus(assignmentId); - - if (isFinishedTrainingAssignment) { - try { - trainingDMO.UpdateAssignmentStatus(assignmentId); - bool isFinishedTraining = trainingDMO.CheckTrainingStatus(assignmentId); - if (isFinishedTraining) { - int TrainingID = trainingDMO.GetTrainingIdByAssignment(assignmentId); - trainingDMO.UpdateTrainingStatus(TrainingID); - } - } catch (Exception e) { - string exception = e.ToString(); - return Content(exception, "application/json"); - } - } - - return Json(new { test = "Succesfully saved" }); - } - - public ActionResult ManuallyExecuteECNTraining(int ecnId, int[] trainingGroupsIn) { - if ((bool)Session[GlobalVars.IS_ADMIN]) { - List newTrainingGroupIds = new List(trainingGroupsIn); - //Get ECN - ECN ecn = ecnDMO.GetECN(ecnId); - if (ecn != null) { - if (ecn.CloseDate != null) { - if (newTrainingGroupIds.Count > 0) { - //Check each assigned group id and see if it's already saved to the ECN - List assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId); - IEnumerable onlyNewTrainingIds = newTrainingGroupIds.Except(assignedTrainingGroups); - try { - foreach (int trainingId in onlyNewTrainingIds) { - trainingDMO.AddTrainingGroupToECN(ecnId, trainingId); - } - - trainingDMO.SetTrainingFlag(ecnId); - Create(ecnId); - return Content("Success"); - } catch (Exception e) { - return Content("Failed: " + e.Message.ToString()); - } - } else { - return Content("There were no training groups to assign to. Please select at least one training groups."); - } - } else { - return Content("Selected ECN hasn't been approved yet."); - } - } else { - return Content("Invalid ECN"); - } - } else { - return Content("Not Autthorized"); - } - } - - public ActionResult CheckECN(int ecnId) { + public ActionResult ManuallyExecuteECNTraining(int ecnId, int[] trainingGroupsIn) { + if ((bool)Session[GlobalVars.IS_ADMIN]) { + List newTrainingGroupIds = new List(trainingGroupsIn); + //Get ECN ECN ecn = ecnDMO.GetECN(ecnId); if (ecn != null) { if (ecn.CloseDate != null) { - List trainingGroupIds = trainingDMO.GetECNAssignedTrainingGroups(ecnId); - List assignedGroups = new List(); - foreach (int trainingGroupId in trainingGroupIds) { - TrainingGroup trainingGroup = trainingDMO.GetTrainingGroupByID(trainingGroupId); - assignedGroups.Add(trainingGroup); - } - return Json(trainingGroupIds.ToList()); - } else { - return Content("ECN not yet approved."); - } - } else { - return Content("That ECN wasn't found."); - } - } - - public bool RunTrainingReport() { - bool isSuccess = false; - try { - string emailBody = "

Mesa Approval Open Training Assignments Daily Report


"; - emailBody += "

The following contains open training assignments in the Mesa Approval system. "; - emailBody += "Please ensure the following users complete their training assignments. "; - emailBody += "Dates in red font identify past due training tasks.


"; - emailBody += ""; - //Get all users set up to receive the training report email. - List trainingReportUsers = adminDMO.GetTrainingReportUsers(); - List emailList = new List(); - foreach (TrainingReportUser user in trainingReportUsers) { - string userEmail = userDMO.GetUserByID(user.UserId).Email; - emailList.Add(userEmail); - } - //emailList.Add("Chase.Tucker@infineon.com"); - //Get a list of open trainings - List openTrainings = trainingDMO.GetAllOpenTrainings(); - - foreach (Training training in openTrainings) { - string trainingSection = ""; - int trainingSectionUserCount = 0; - string ecnTitle = ecnDMO.GetECN(training.ECN).Title; - trainingSection += "

" + training.ECN + " - " + ecnTitle + "

"; - - trainingSection += ""; - trainingSection += ""; - List openAssignments = trainingDMO.GetOpenAssignmentsByTrainingID(training.TrainingID); - foreach (TrainingAssignment assignment in openAssignments) { - - if (!userDMO.GetUserByID(assignment.UserID).OOO) { - trainingSectionUserCount++; - - DateTime? assignmentDate = assignment.DateAssigned; - - string DateAssigned = assignmentDate.HasValue ? assignmentDate.Value.ToString("MM/dd/yyyy") : ""; - - if (assignmentDate.HasValue && (DateTime.Now.Date - assignmentDate.Value.Date).TotalDays > 15) { - trainingSection += ""; - } else { - trainingSection += ""; + if (newTrainingGroupIds.Count > 0) { + //Check each assigned group id and see if it's already saved to the ECN + List assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId); + IEnumerable onlyNewTrainingIds = newTrainingGroupIds.Except(assignedTrainingGroups); + try { + foreach (int trainingId in onlyNewTrainingIds) { + trainingDMO.AddTrainingGroupToECN(ecnId, trainingId); } - trainingSection += ""; + trainingDMO.SetTrainingFlag(ecnId); + Create(ecnId); + return Content("Success"); + } catch (Exception e) { + return Content("Failed: " + e.Message.ToString()); } + } else { + return Content("There were no training groups to assign to. Please select at least one training groups."); } - trainingSection += "
NameDate Assigned
" + assignment.FullName + "" + DateAssigned + "
" + assignment.FullName + "" + DateAssigned + "
"; - if (trainingSectionUserCount > 0) emailBody += trainingSection; + } else { + return Content("Selected ECN hasn't been approved yet."); } - string recipientEmail = ""; - List ccRecipients = emailList; - emailer.SendNotification("MesaFabApproval@infineon.com", ccRecipients, "Mesa Approval Daily Open Training Report", emailBody, "Daily Open Training Report"); - isSuccess = true; - } catch { - isSuccess = false; + } else { + return Content("Invalid ECN"); } - return isSuccess; + } else { + return Content("Not Autthorized"); } } -} + + public ActionResult CheckECN(int ecnId) { + ECN ecn = ecnDMO.GetECN(ecnId); + if (ecn != null) { + if (ecn.CloseDate != null) { + List trainingGroupIds = trainingDMO.GetECNAssignedTrainingGroups(ecnId); + List assignedGroups = new List(); + foreach (int trainingGroupId in trainingGroupIds) { + TrainingGroup trainingGroup = trainingDMO.GetTrainingGroupByID(trainingGroupId); + assignedGroups.Add(trainingGroup); + } + return Json(trainingGroupIds.ToList()); + } else { + return Content("ECN not yet approved."); + } + } else { + return Content("That ECN wasn't found."); + } + } + + public bool RunTrainingReport() { + bool isSuccess = false; + try { + string emailBody = "

Mesa Approval Open Training Assignments Daily Report


"; + emailBody += "

The following contains open training assignments in the Mesa Approval system. "; + emailBody += "Please ensure the following users complete their training assignments. "; + emailBody += "Dates in red font identify past due training tasks.


"; + emailBody += ""; + //Get all users set up to receive the training report email. + List trainingReportUsers = adminDMO.GetTrainingReportUsers(); + List emailList = new List(); + foreach (TrainingReportUser user in trainingReportUsers) { + string userEmail = userDMO.GetUserByID(user.UserId).Email; + emailList.Add(userEmail); + } + //emailList.Add("Chase.Tucker@infineon.com"); + //Get a list of open trainings + List openTrainings = trainingDMO.GetAllOpenTrainings(); + + foreach (Training training in openTrainings) { + string trainingSection = ""; + int trainingSectionUserCount = 0; + string ecnTitle = ecnDMO.GetECN(training.ECN).Title; + trainingSection += "

" + training.ECN + " - " + ecnTitle + "

"; + + trainingSection += ""; + trainingSection += ""; + List openAssignments = trainingDMO.GetOpenAssignmentsByTrainingID(training.TrainingID); + foreach (TrainingAssignment assignment in openAssignments) { + if (!userDMO.GetUserByID(assignment.UserID).OOO) { + trainingSectionUserCount++; + + DateTime? assignmentDate = assignment.DateAssigned; + + string DateAssigned = assignmentDate.HasValue ? assignmentDate.Value.ToString("MM/dd/yyyy") : ""; + + if (assignmentDate.HasValue && (DateTime.Now.Date - assignmentDate.Value.Date).TotalDays > 15) { + trainingSection += ""; + } else { + trainingSection += ""; + } + + trainingSection += ""; + } + } + trainingSection += "
NameDate Assigned
" + assignment.FullName + "" + DateAssigned + "
" + assignment.FullName + "" + DateAssigned + "
"; + if (trainingSectionUserCount > 0) + emailBody += trainingSection; + } + string recipientEmail = ""; + List ccRecipients = emailList; + EmailUtilities.SendNotification("MesaFabApproval@infineon.com", ccRecipients, "Daily Open Training Report", emailBody); + isSuccess = true; + } catch { + isSuccess = false; + } + return isSuccess; + } +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/WebAPIController.cs b/Fab2ApprovalSystem/Controllers/WebAPIController.cs index dec2786..b6d6544 100644 --- a/Fab2ApprovalSystem/Controllers/WebAPIController.cs +++ b/Fab2ApprovalSystem/Controllers/WebAPIController.cs @@ -5,87 +5,69 @@ using System.Net; using System.Net.Http; using System.Web.Http; +using Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.Controllers -{ - - public class WebAPIController : ApiController - { - public TrainingController trainingFunctions = new TrainingController(); - public CorrectiveActionController carFunctions = new CorrectiveActionController(); - public AccountController accountFunctions = new AccountController(); - public HomeController homeFunctions = new HomeController(); - public string Get() - { - return "Welcome To Web API"; - } - public List Get(int Id) - { - return new List { +namespace Fab2ApprovalSystem.Controllers; + +public class WebAPIController : ApiController { + public TrainingController trainingFunctions = new TrainingController(); + public CorrectiveActionController carFunctions; + public AccountController accountFunctions = new AccountController(); + public HomeController homeFunctions; + private readonly AppSettings _AppSettings; + + public WebAPIController(AppSettings appSettings) { + _AppSettings = appSettings; + carFunctions = new CorrectiveActionController(appSettings); + homeFunctions = new HomeController(appSettings); + } + + public string Get() { + return "Welcome To Web API"; + } + public List Get(int Id) { + return new List { "Data1", "Data2" }; - } - public void Post() - { - - } - - public HttpResponseMessage Post(HttpRequestMessage request, string action) - { - - switch (action) - { - case "TrainingReport": - if (trainingFunctions.RunTrainingReport()) - { - return request.CreateResponse(HttpStatusCode.OK); - } - else - { - return request.CreateResponse(HttpStatusCode.InternalServerError); - } - case "CARDueDates": - if (carFunctions.ProcessCARDueDates()) - { - return request.CreateResponse(HttpStatusCode.OK); - } - else - { - return request.CreateResponse(HttpStatusCode.InternalServerError); - } - case "ProcessOoO": - if (homeFunctions.ProcessOoO()) - { - return request.CreateResponse(HttpStatusCode.OK); - } - else - { - return request.CreateResponse(HttpStatusCode.InternalServerError); - } - case "ExpireOoO": - if (homeFunctions.ExpireOoO()) - { - return request.CreateResponse(HttpStatusCode.OK); - } - else - { - return request.CreateResponse(HttpStatusCode.InternalServerError); - } - case "ApprovalReminders": - if (homeFunctions.ApprovalsReminderNotifications()) - { - return request.CreateResponse(HttpStatusCode.OK); - } - else - { - return request.CreateResponse(HttpStatusCode.InternalServerError); - } - default: - return request.CreateResponse(HttpStatusCode.InternalServerError, "Action Not Found"); - - } + } + public void Post() { + } + public HttpResponseMessage Post(HttpRequestMessage request, string action) { + switch (action) { + case "TrainingReport": + if (trainingFunctions.RunTrainingReport()) { + return request.CreateResponse(HttpStatusCode.OK); + } else { + return request.CreateResponse(HttpStatusCode.InternalServerError); + } + case "CARDueDates": + if (carFunctions.ProcessCARDueDates()) { + return request.CreateResponse(HttpStatusCode.OK); + } else { + return request.CreateResponse(HttpStatusCode.InternalServerError); + } + case "ProcessOoO": + if (homeFunctions.ProcessOoO()) { + return request.CreateResponse(HttpStatusCode.OK); + } else { + return request.CreateResponse(HttpStatusCode.InternalServerError); + } + case "ExpireOoO": + if (homeFunctions.ExpireOoO()) { + return request.CreateResponse(HttpStatusCode.OK); + } else { + return request.CreateResponse(HttpStatusCode.InternalServerError); + } + case "ApprovalReminders": + if (homeFunctions.ApprovalsReminderNotifications()) { + return request.CreateResponse(HttpStatusCode.OK); + } else { + return request.CreateResponse(HttpStatusCode.InternalServerError); + } + default: + return request.CreateResponse(HttpStatusCode.InternalServerError, "Action Not Found"); } } -} +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/WorkflowController.cs b/Fab2ApprovalSystem/Controllers/WorkflowController.cs index 77087e2..7f0765f 100644 --- a/Fab2ApprovalSystem/Controllers/WorkflowController.cs +++ b/Fab2ApprovalSystem/Controllers/WorkflowController.cs @@ -1,99 +1,81 @@ using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Models; + +using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; + using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; -using Kendo.Mvc.Extensions; - +namespace Fab2ApprovalSystem.Controllers; -namespace Fab2ApprovalSystem.Controllers -{ - public class WorkflowController : Controller - { - // - - // - // GET: /Workflow/Details/5 - public ActionResult Details(int id) - { - return View(); - } - - // - // GET: /Workflow/Create - public ActionResult Create() - { - return View(); - } - - // - // POST: /Workflow/Create - [HttpPost] - public ActionResult Create(FormCollection collection) - { - try - { - // TODO: Add insert logic here - - return RedirectToAction("Index"); - } - catch - { - return View(); - } - } - - // - // GET: /Workflow/Edit/5 - public ActionResult Edit(int id) - { - return View(); - } - - // - // POST: /Workflow/Edit/5 - [HttpPost] - public ActionResult Edit(int id, FormCollection collection) - { - try - { - // TODO: Add update logic here - - return RedirectToAction("Index"); - } - catch - { - return View(); - } - } - - // - // GET: /Workflow/Delete/5 - public ActionResult Delete(int id) - { - return View(); - } - - // - // POST: /Workflow/Delete/5 - [HttpPost] - public ActionResult Delete(int id, FormCollection collection) - { - try - { - // TODO: Add delete logic here - - return RedirectToAction("Index"); - } - catch - { - return View(); - } - } +public class WorkflowController : Controller { + // + // + // GET: /Workflow/Details/5 + public ActionResult Details(int id) { + return View(); } -} + + // + // GET: /Workflow/Create + public ActionResult Create() { + return View(); + } + + // + // POST: /Workflow/Create + [HttpPost] + public ActionResult Create(FormCollection collection) { + try { + // TODO: Add insert logic here + + return RedirectToAction("Index"); + } catch { + return View(); + } + } + + // + // GET: /Workflow/Edit/5 + public ActionResult Edit(int id) { + return View(); + } + + // + // POST: /Workflow/Edit/5 + [HttpPost] + public ActionResult Edit(int id, FormCollection collection) { + try { + // TODO: Add update logic here + + return RedirectToAction("Index"); + } catch { + return View(); + } + } + + // + // GET: /Workflow/Delete/5 + public ActionResult Delete(int id) { + return View(); + } + + // + // POST: /Workflow/Delete/5 + [HttpPost] + public ActionResult Delete(int id, FormCollection collection) { + try { + // TODO: Add delete logic here + + return RedirectToAction("Index"); + } catch { + return View(); + } + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/AccountDMO.cs b/Fab2ApprovalSystem/DMO/AccountDMO.cs new file mode 100644 index 0000000..962f006 --- /dev/null +++ b/Fab2ApprovalSystem/DMO/AccountDMO.cs @@ -0,0 +1,59 @@ +using System; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; + +using Fab2ApprovalSystem.Models; + +using Newtonsoft.Json; + +namespace Fab2ApprovalSystem.DMO; + +public class AccountDMO { + + public static async Task LoginAsync(HttpClient httpClient, LoginModel loginModel) { + LoginResult result; + + HttpRequestMessage request = new(HttpMethod.Post, "auth/login"); + + AuthAttempt authAttempt = loginModel is null ? null : new AuthAttempt() { + LoginID = loginModel.LoginID, + Password = loginModel.Password + }; + + string json = authAttempt is null ? "{}" : JsonConvert.SerializeObject(authAttempt); + + request.Content = new StringContent(json, Encoding.UTF8, "application/json"); + + HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(request); + + if (!httpResponseMessage.IsSuccessStatusCode) + throw new Exception($"The authentication API failed, because {httpResponseMessage.ReasonPhrase}"); + + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(); + + result = JsonConvert.DeserializeObject(responseContent); + return result; + } + + public static async Task ExternalAuthSetupAsync(HttpClient httpClient, AuthAttempt authAttempt) { + LoginResult result; + + HttpRequestMessage request = new(HttpMethod.Post, "auth/refresh"); + + string json = authAttempt is null ? "{}" : JsonConvert.SerializeObject(authAttempt); + + request.Content = new StringContent(json, Encoding.UTF8, "application/json"); + + HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(request); + + if (!httpResponseMessage.IsSuccessStatusCode) + throw new Exception($"The authentication API failed, because {httpResponseMessage.ReasonPhrase}"); + + string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(); + + result = JsonConvert.DeserializeObject(responseContent); + return result; + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/AdminDMO.cs b/Fab2ApprovalSystem/DMO/AdminDMO.cs index 18415fe..d51b97d 100644 --- a/Fab2ApprovalSystem/DMO/AdminDMO.cs +++ b/Fab2ApprovalSystem/DMO/AdminDMO.cs @@ -1,311 +1,336 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; -using System.Web; -using Dapper; -using Fab2ApprovalSystem.Models; using System.Text; + +using Dapper; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.DMO -{ - public class AdminDMO - { - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - private static FabApprovalTrainingEntities FabApprovalDB = new FabApprovalTrainingEntities(); +namespace Fab2ApprovalSystem.DMO; - /// - /// - /// - /// - public List GetSubRoles() - { - StringBuilder sql = new StringBuilder(); - sql.Append( - "SELECT R.RoleID, R.RoleName, SubRoleID, SubRoleCategoryItem, SR.RoleID, SR.Inactive " + - "FROM vSubRoles SR " + - "INNER JOIN Role R ON R.RoleID = SR.RoleID " + - "ORDER BY R.RoleID, SubRoleCategoryItem "); +public class AdminDMO { + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); +#if !NET8 + private static FabApprovalTrainingEntities FabApprovalDB = new FabApprovalTrainingEntities(); +#endif + public List GetAllSubRoles(string showInactiveRoles = "") { + List results = new(); + + List roles = GetSubRoles(); + + ParentChildModel child; + ParentChildModel parent; + + foreach (Role r in roles) { + parent = new ParentChildModel { + id = r.RoleID, + parentid = -1, + text = r.RoleName, + value = r.RoleID.ToString() + }; + + foreach (SubRole sr in r.SubRoles) { + if (sr.Inactive) { + // hide inactive roles unless parameter says otherwise + if (showInactiveRoles.Equals("true") == false) + continue; + } + + child = new ParentChildModel { + id = sr.SubRoleID, + parentid = r.RoleID, + text = sr.SubRoleCategoryItem + (sr.Inactive ? " (Inactive)" : ""), + value = sr.SubRoleID.ToString() + }; + results.Add(child); + } + + results.Add(parent); + }; + return results; + } + + public List GetSubRoles() { + StringBuilder sql = new(); + sql.Append( + "SELECT R.RoleID, R.RoleName, SubRoleID, SubRoleCategoryItem, SR.RoleID, SR.Inactive " + + "FROM vSubRoles SR " + + "INNER JOIN Role R ON R.RoleID = SR.RoleID " + + "ORDER BY R.RoleID, SubRoleCategoryItem "); + + db.Open(); + Dictionary lookup = new(); + List data = db.Query(sql.ToString(), + (parent, child) => { + Role role; + if (!lookup.TryGetValue(parent.RoleID, out role)) { + lookup.Add(parent.RoleID, role = parent); + } + //if (role.RoleID == null) + // role.SubRoles = new List(); + role.SubRoles.Add(child); + return role; + }, + splitOn: "SubRoleID").Distinct().ToList(); + + return data; + } + /// + public List GetUserSubRoles(int userId) { + DynamicParameters parameters = new(); + parameters.Add("@UserId", userId); + List userSubRoleList = db.Query("GetSubRolesByUserId", parameters, commandType: CommandType.StoredProcedure).ToList(); + return userSubRoleList; + } + + public IEnumerable GetAllUsersBySubRole(int subRole) { + StringBuilder sql = new(); + sql.Append("SELECT FirstName + ' ' + LastName AS FullName , LoginID, FirstName, LastName, U.UserID, SubRoleID "); + sql.Append("FROM UserSubRole UR "); + sql.Append("INNER JOIN Users U ON UR.UserID = U.UserID "); + sql.Append("WHERE UR.SubRoleID = " + subRole.ToString() + " "); + sql.Append("ORDER BY FirstName"); + + return db.Query(sql.ToString()).ToList(); + } + + public void AddUserRoles(int subRole, string userids) { + string sql; + + string[] arrayOfUsers = userids.Split(new char[] { '~' }); + + for (int i = 0; i < arrayOfUsers.Length; i++) { + sql = "INSERT INTO UserSubRole (UserID, SubRoleID) VALUES (" + arrayOfUsers[i] + ", " + subRole + " )"; + db.Execute(sql); + } + + } + + public void DeleteUserFromAllTrainingGroups(int userId) { + string sql = "DELETE FROM TrainingGroupMembers WHERE UserId = " + userId; + + db.Open(); + db.Execute(sql); + return; + } + + public void DeleteUserRoles(int subRole, string userids) { + string sql; + + string[] arrayOfUsers = userids.Split(new char[] { '~' }); + + for (int i = 0; i < arrayOfUsers.Length; i++) { + sql = "DELETE FROM UserSubRole WHERE UserID = " + arrayOfUsers[i] + " AND SubRoleID = " + subRole; + db.Execute(sql); + } + + } +#if !NET8 + public List GetTrainingReportUsers() { + List CurrentReportUsers = (from a in FabApprovalDB.TrainingReportUsers select a).ToList(); + return CurrentReportUsers; + } +#else + public List GetTrainingReportUsers() => throw new NotImplementedException(); +#endif +#if !NET8 + public List GetTECNNotificationUsers() { + List currentTECNNotificationUsers = (from a in FabApprovalDB.TECNNotificationsUsers select a).ToList(); + return currentTECNNotificationUsers; + } +#endif + + public void TrainingReportAddUser(int userId) { + string sql = "INSERT INTO TrainingReportUsers (UserId) " + "VALUES ('" + userId + "') "; + + db.Open(); + db.Execute(sql); + return; + } + + public void TECNExpirationAddUser(int userId) { + string sql = "INSERT INTO TECNNotificationsUsers (UserId) " + "VALUES ('" + userId + "') "; + + db.Open(); + db.Execute(sql); + + return; + } + + public void TrainingReportDeleteUser(int userId) { + DynamicParameters parameters = new(); + + parameters = new DynamicParameters(); + parameters.Add("@UserID", userId); + + db.Execute("DeleteUserFromTrainingReport", parameters, commandType: CommandType.StoredProcedure); + return; + } + + public void TECNExpirationDeleteUser(int userId) { + DynamicParameters parameters = new(); + + parameters = new DynamicParameters(); + parameters.Add("@UserID", userId); + + db.Execute("DeleteUserFromTECNReport", parameters, commandType: CommandType.StoredProcedure); + return; + } +#if !NET8 + public List GetTrainingGroups() { + //StringBuilder sql = new StringBuilder(); + //sql.Append( + // "SELECT 'TrainingGroupID', TrainingGroupName " + + // "FROM TrainingGroups " + + // "ORDER BY TrainingGroupID "); + + //db.Open(); + //var lookup = new Dictionary(); + ////List data = this.db.Query(sql.ToString() + //return this.db.Query(sql.ToString()).ToList(); + var TrainingGroups = from a in FabApprovalDB.TrainingGroups select a; + List GroupsToReturn = TrainingGroups.ToList(); + + return GroupsToReturn; + } + + public void AddNewTrainingGroup(string groupName) { + TrainingGroup existing = null; + //Check to see that the group name doesn't exist. + try { + existing = (from a in FabApprovalDB.TrainingGroups where a.TrainingGroupName == groupName select a).FirstOrDefault(); + } catch { + // string test = ""; + } + + + if (existing == null) { + //string sql = new StringBuilder(); + string sql = "INSERT INTO TrainingGroups (TrainingGroupName) " + "VALUES ('" + groupName + "') "; + + this.db.Open(); + this.db.Execute(sql); + return; + } else { + return; + } + } +#endif + + public void DeleteTrainingGroup(int groupID) { + try { + string sql = "DELETE FROM TrainingGroups WHERE TrainingGroupID = " + groupID; db.Open(); - var lookup = new Dictionary(); - List data = this.db.Query(sql.ToString(), - (parent, child) => - { - Role role; - if (!lookup.TryGetValue(parent.RoleID, out role)) - { - lookup.Add(parent.RoleID, role = parent); - } - //if (role.RoleID == null) - // role.SubRoles = new List(); - role.SubRoles.Add(child); - return role; - }, - splitOn: "SubRoleID").Distinct().ToList(); + db.Execute(sql); - - return data; - } - /// - /// - /// - /// /// - /// - public List GetUserSubRoles(int userId) - { - var parameters = new DynamicParameters(); - parameters.Add("@UserId", userId); - var userSubRoleList = this.db.Query("GetSubRolesByUserId", parameters, commandType: CommandType.StoredProcedure).ToList(); - return userSubRoleList; - } - - - /// - /// - /// - /// - /// - public IEnumerable GetAllUsersBySubRole(int subRole) - { - StringBuilder sql = new StringBuilder(); - sql.Append("SELECT FirstName + ' ' + LastName AS FullName , LoginID, FirstName, LastName, U.UserID, SubRoleID "); - sql.Append("FROM UserSubRole UR "); - sql.Append("INNER JOIN Users U ON UR.UserID = U.UserID "); - sql.Append("WHERE UR.SubRoleID = " + subRole.ToString() + " "); - sql.Append("ORDER BY FirstName"); - - return this.db.Query(sql.ToString()).ToList(); - } - - - /// - /// - /// - /// - /// - public void AddUserRoles(int subRole, string userids) - { - string sql; - - string[] arrayOfUsers = userids.Split(new char[] { '~' }); - - for (int i = 0; i < arrayOfUsers.Length; i++) - { - sql = "INSERT INTO UserSubRole (UserID, SubRoleID) VALUES (" + arrayOfUsers[i] + ", " + subRole + " )"; - this.db.Execute(sql); - } - - } - - public void DeleteUserFromAllTrainingGroups(int userId) - { - string sql = "DELETE FROM TrainingGroupMembers WHERE UserId = " + userId; - - - this.db.Open(); - this.db.Execute(sql); + sql = "DELETE FROM TrainingGroupMembers WHERE TrainingGroupID = " + groupID; + db.Execute(sql); return; - + } catch { } - /// - /// - /// - /// - /// - public void DeleteUserRoles(int subRole, string userids) - { - string sql; + } +#if !NET8 + public List GetTrainingGroupMembers(int GroupID) { + return (from a in FabApprovalDB.TrainingGroupMembers where a.TrainingGroupID == GroupID select a).ToList(); + } - string[] arrayOfUsers = userids.Split(new char[] { '~' }); + public void AddUserToGroup(int userId, int groupId) { + UserAccountDMO userDB = new UserAccountDMO(); + string userFullName = userDB.GetUserByID(userId).FullName; - for (int i = 0; i < arrayOfUsers.Length; i++) - { - sql = "DELETE FROM UserSubRole WHERE UserID = " + arrayOfUsers[i] + " AND SubRoleID = " + subRole; - this.db.Execute(sql); - } + TrainingGroupMember existing = null; - } - public List GetTrainingReportUsers() - { - List CurrentReportUsers = (from a in FabApprovalDB.TrainingReportUsers select a).ToList(); - return CurrentReportUsers; - } - public List GetTECNNotificationUsers() - { - List currentTECNNotificationUsers = (from a in FabApprovalDB.TECNNotificationsUsers select a).ToList(); - return currentTECNNotificationUsers; - } - - public void TrainingReportAddUser(int userId) - { - string sql = "INSERT INTO TrainingReportUsers (UserId) " + "VALUES ('" + userId + "') "; - - - this.db.Open(); - this.db.Execute(sql); - return; - } - public void TECNExpirationAddUser(int userId) - { - string sql = "INSERT INTO TECNNotificationsUsers (UserId) " + "VALUES ('" + userId + "') "; - - this.db.Open(); - this.db.Execute(sql); - - - - return; - } - public void TrainingReportDeleteUser(int userId) - { - var parameters = new DynamicParameters(); - - parameters = new DynamicParameters(); - parameters.Add("@UserID", userId); - - this.db.Execute("DeleteUserFromTrainingReport", parameters, commandType: CommandType.StoredProcedure); - return; - } - public void TECNExpirationDeleteUser(int userId) - { - var parameters = new DynamicParameters(); - - parameters = new DynamicParameters(); - parameters.Add("@UserID", userId); - - this.db.Execute("DeleteUserFromTECNReport", parameters, commandType: CommandType.StoredProcedure); - return; - } - public List GetTrainingGroups() - { - //StringBuilder sql = new StringBuilder(); - //sql.Append( - // "SELECT 'TrainingGroupID', TrainingGroupName " + - // "FROM TrainingGroups " + - // "ORDER BY TrainingGroupID "); - - //db.Open(); - //var lookup = new Dictionary(); - ////List data = this.db.Query(sql.ToString() - //return this.db.Query(sql.ToString()).ToList(); - var TrainingGroups = from a in FabApprovalDB.TrainingGroups select a; - List GroupsToReturn = TrainingGroups.ToList(); - - return GroupsToReturn; - } - public void AddNewTrainingGroup(string groupName) - { - TrainingGroup existing = null; - //Check to see that the group name doesn't exist. - try - { - existing = (from a in FabApprovalDB.TrainingGroups where a.TrainingGroupName == groupName select a).FirstOrDefault(); - } - catch - { - // string test = ""; - } - - - if (existing == null) - { - //string sql = new StringBuilder(); - string sql = "INSERT INTO TrainingGroups (TrainingGroupName) " + "VALUES ('" + groupName + "') "; - - - this.db.Open(); - this.db.Execute(sql); - return; - } - else - { - return; - } - } - - public void DeleteTrainingGroup(int groupID) - { - try - { - string sql = "DELETE FROM TrainingGroups WHERE TrainingGroupID = " + groupID; - this.db.Open(); - this.db.Execute(sql); - - sql = "DELETE FROM TrainingGroupMembers WHERE TrainingGroupID = " + groupID; - this.db.Execute(sql); - return; - } - catch - { - - } - } - public List GetTrainingGroupMembers(int GroupID) - { - return (from a in FabApprovalDB.TrainingGroupMembers where a.TrainingGroupID == GroupID select a).ToList(); - } - public void AddUserToGroup(int userId, int groupId) - { - UserAccountDMO userDB = new UserAccountDMO(); - string userFullName = userDB.GetUserByID(userId).FullName; - - TrainingGroupMember existing = null; - - existing = (from a in FabApprovalDB.TrainingGroupMembers where a.TrainingGroupID == groupId && a.UserID == userId select a).FirstOrDefault(); - if (existing == null) - { - var parameters = new DynamicParameters(); - - parameters = new DynamicParameters(); - parameters.Add("@GroupID", groupId); - parameters.Add("@UserID", userId); - parameters.Add("@UserFullName", userFullName); - - this.db.Execute("AddUserToTrainingGroup", parameters, commandType: CommandType.StoredProcedure); - } - else - { - throw new Exception("The user already exists in this training group."); - } - - - //if (existing == null) - //{ - // //string sql = new StringBuilder(); - - // string sql = "INSERT INTO TrainingGroupMembers (TrainingGroupID, UserID, FullName) " + "VALUES ('" + groupId + "','" + userId + "','" + userFullName + "') "; - - // try - // { - // this.db.Open(); - // this.db.Execute(sql); - // } - // catch(Exception e) - // { - // return; - // } - // return; - //} - //else - //{ - // return; - - } - public void DeleteFromGroup(int userId, int groupId) - { + existing = (from a in FabApprovalDB.TrainingGroupMembers where a.TrainingGroupID == groupId && a.UserID == userId select a).FirstOrDefault(); + if (existing == null) { var parameters = new DynamicParameters(); parameters = new DynamicParameters(); parameters.Add("@GroupID", groupId); parameters.Add("@UserID", userId); + parameters.Add("@UserFullName", userFullName); - this.db.Execute("DeleteUserFromTrainingGroup", parameters, commandType: CommandType.StoredProcedure); + this.db.Execute("AddUserToTrainingGroup", parameters, commandType: CommandType.StoredProcedure); + } else { + throw new Exception("The user already exists in this training group."); + } - return; + + //if (existing == null) + //{ + // //string sql = new StringBuilder(); + + // string sql = "INSERT INTO TrainingGroupMembers (TrainingGroupID, UserID, FullName) " + "VALUES ('" + groupId + "','" + userId + "','" + userFullName + "') "; + + // try + // { + // this.db.Open(); + // this.db.Execute(sql); + // } + // catch(Exception e) + // { + // return; + // } + // return; + //} + //else + //{ + // return; + + } +#endif + public void DeleteFromGroup(int userId, int groupId) { + DynamicParameters parameters = new(); + + parameters = new DynamicParameters(); + parameters.Add("@GroupID", groupId); + parameters.Add("@UserID", userId); + + db.Execute("DeleteUserFromTrainingGroup", parameters, commandType: CommandType.StoredProcedure); + + return; + } + + public void DeleteUser(UserAccountDMO userDMO, TrainingDMO trainingDMO, LoginModel loginModel) { + if (loginModel != null) { + userDMO.DeleteUser(loginModel); + //Remove open trainings + //Get a list of all user assigned trainings. + List trainingAssignments = trainingDMO.GetTrainingAssignmentsByUserID(loginModel.UserID); + + //Go Through that list. + foreach (var trainingAssignment in trainingAssignments) { + //Delete Any document acknowledgements. + trainingDMO.DeleteTrainingDocAck(trainingAssignment.ID); + //Delete the training assignment itself + trainingDMO.DeleteTrainingAssignment(trainingAssignment.ID); + //Check the parent Training task to set to to complete if applicable. + if (trainingDMO.CheckTrainingStatus(trainingAssignment.ID)) { + int TrainingID = trainingAssignment.TrainingID; + //Set Training status to complete + trainingDMO.UpdateTrainingStatus(TrainingID); + } + + } + + //Remove user from any Training Groups + DeleteUserFromAllTrainingGroups(loginModel.UserID); + + //Remove User from training report notifications + TrainingReportDeleteUser(loginModel.UserID); + //Remove user from TECN Expiration Notifications + TECNExpirationDeleteUser(loginModel.UserID); + //Get user subroles + List userSubRoles = GetUserSubRoles(loginModel.UserID); + //Delete user from any subroles + foreach (var userSubRole in userSubRoles) { + DeleteUserRoles(userSubRole.SubRoleID, loginModel.UserID.ToString()); + } } } -} + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/ApprovalLogDMO.cs b/Fab2ApprovalSystem/DMO/ApprovalLogDMO.cs index 34d85fa..f6ba5ec 100644 --- a/Fab2ApprovalSystem/DMO/ApprovalLogDMO.cs +++ b/Fab2ApprovalSystem/DMO/ApprovalLogDMO.cs @@ -1,33 +1,26 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; using System.Data; using System.Data.SqlClient; -using Fab2ApprovalSystem.Models; + using Dapper; -using System.Configuration; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.DMO -{ - public static class ApprovalLogDMO - { +namespace Fab2ApprovalSystem.DMO; - private static IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); +public static class ApprovalLogDMO { - public static void Add(ApprovalLog appLog) - { - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", appLog.IssueID); - parameters.Add("@UserID", appLog.UserID); - parameters.Add("@OperationType", appLog.OperationType); - parameters.Add("@SubRoleID", appLog.SubRoleID); - parameters.Add("@OperationLog", appLog.OperationLog); - parameters.Add("@DocumentTypeID", appLog.DocumentTypeID); + private static readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - db.Execute("InsertApprovalLogByDocument", parameters, commandType: CommandType.StoredProcedure); + public static void Add(ApprovalLog appLog) { + DynamicParameters parameters = new(); + parameters.Add("@IssueID", appLog.IssueID); + parameters.Add("@UserID", appLog.UserID); + parameters.Add("@OperationType", appLog.OperationType); + parameters.Add("@SubRoleID", appLog.SubRoleID); + parameters.Add("@OperationLog", appLog.OperationLog); + parameters.Add("@DocumentTypeID", appLog.DocumentTypeID); - } + db.Execute("InsertApprovalLogByDocument", parameters, commandType: CommandType.StoredProcedure); } -} +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/AuditDMO.cs b/Fab2ApprovalSystem/DMO/AuditDMO.cs index 1621553..37ba686 100644 --- a/Fab2ApprovalSystem/DMO/AuditDMO.cs +++ b/Fab2ApprovalSystem/DMO/AuditDMO.cs @@ -1,659 +1,635 @@ using Dapper; + using Fab2ApprovalSystem.Models; -using Fab2ApprovalSystem.ViewModels; + using System; using System.Collections.Generic; -using System.Configuration; using System.Data; using System.Data.SqlClient; + +#if !NET8 using System.Data.Linq; +#endif + using System.Linq; -using System.Text; using System.Transactions; -using System.Web; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Utilities; -namespace Fab2ApprovalSystem.DMO -{ - public class AuditDMO - { - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - WorkflowDMO wfDMO = new WorkflowDMO(); +using System.IO; - /// - /// - /// - /// - /// - public Audit InsertAudit(Audit audit) - { - var parameters = new DynamicParameters(); +namespace Fab2ApprovalSystem.DMO; - parameters = new DynamicParameters(); - parameters.Add("@AuditNo", value: audit.AuditNo, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@OriginatorID", audit.OriginatorID); +public class AuditDMO { - this.db.Execute("_8DInsertAuditItem", parameters, commandType: CommandType.StoredProcedure); - audit.AuditNo = parameters.Get("@AuditNo"); + private readonly AppSettings _AppSettings; + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - return audit; - } + public AuditDMO(AppSettings appSettings) => + _AppSettings = appSettings; - /// - /// - /// - /// - /// - /// - /// - public Audit GetAuditItem(int auditNo, int userID) - { - Audit audit = new Audit(); + public Audit InsertAudit(Audit audit) { + DynamicParameters parameters = new(); - //isITAR = 2; - - var parameters = new DynamicParameters(); - parameters.Add("@AuditNo", value: auditNo); - parameters.Add("@UserID", userID); - //parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters = new DynamicParameters(); + parameters.Add("@AuditNo", value: audit.AuditNo, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@OriginatorID", audit.OriginatorID); - //audit = this.db.Query("_8DGetAuditItem", parameters, commandType: CommandType.StoredProcedure).Single(); - - - - using (var multipleResultItems = this.db.QueryMultiple("_8DGetAuditItem", parameters, commandType: CommandType.StoredProcedure)) - { - audit = multipleResultItems.Read().SingleOrDefault(); - - var auditors = multipleResultItems.Read().ToList(); - - - if (audit != null && auditors != null) - { - if (auditors.Count > 0) - audit.AuditorIDs.AddRange(auditors); - } - - var auditorTypes = multipleResultItems.Read().ToList(); - if (audit != null && auditorTypes != null) - { - if (auditorTypes.Count > 0) - audit.AuditTypeIDs.AddRange(auditorTypes); - } - - var auditorAreas = multipleResultItems.Read().ToList(); - if (audit != null && auditorAreas != null) - { - if (auditorAreas.Count > 0) - audit.AuditedAreaIDs.AddRange(auditorAreas); - } - } - //FabApprovalSystemEntitiesAll auditDb = new FabApprovalSystemEntitiesAll(); - - //var auditedStandardIDs = (from a in auditDb.C_8DAuditedStandardByAudit where a.AuditNo == audit.AuditNo select a.AuditedStandardID).ToList(); - - //foreach (var id in auditedStandardIDs) - //{ - // audit.AuditedStandardIDs.Add(id); - //} - - return audit; - } - - /// - /// - /// - /// - /// - /// - public Audit GetAuditItemReadOnly(int auditNo, int userID) - { - Audit audit = new Audit(); - - //isITAR = 2; - - var parameters = new DynamicParameters(); - parameters.Add("@AuditNo", value: auditNo); - parameters.Add("@UserID", userID); - //parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - //audit = this.db.Query("_8DGetAuditItem", parameters, commandType: CommandType.StoredProcedure).Single(); - - - - using (var multipleResultItems = this.db.QueryMultiple("_8DGetAuditItemReadOnly", parameters, commandType: CommandType.StoredProcedure)) - { - audit = multipleResultItems.Read().SingleOrDefault(); - - var auditors = multipleResultItems.Read().ToList(); - - - if (audit != null && auditors != null) - { - if (auditors.Count > 0) - audit.AuditorIDs.AddRange(auditors); - } - - var auditorTypes = multipleResultItems.Read().ToList(); - if (audit != null && auditorTypes != null) - { - if (auditorTypes.Count > 0) - audit.AuditTypeIDs.AddRange(auditorTypes); - } - - var auditorAreas = multipleResultItems.Read().ToList(); - if (audit != null && auditorAreas != null) - { - if (auditorAreas.Count > 0) - audit.AuditedAreaIDs.AddRange(auditorAreas); - } - } - - return audit; - } - - - /// - /// - /// - /// - public IEnumerable GetAuditTypeList() - { - var parameters = new DynamicParameters(); - - - var auditTypeList = this.db.Query("_8DGetAuditTypeList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return auditTypeList; - - } - - public IEnumerable GetAuditStandardList() - { - - FabApprovalSystemEntitiesAll db = new FabApprovalSystemEntitiesAll(); - - var auditStandardList = from a in db.C_8DAuditedStandard select a; - - return auditStandardList; - - } - /// - /// - /// - /// - public IEnumerable GetAuditorList() - { - var parameters = new DynamicParameters(); - - - var auditorList = this.db.Query("_8DGetAuditorList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return auditorList; - - } - - - /// - /// - /// - /// - public IEnumerable GetAuditAreaList() - { - var parameters = new DynamicParameters(); - - var auditAreaList = this.db.Query("_8DGetAuditAreaList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return auditAreaList; - - } - - - /// - /// - /// - /// - public void UpdateAudit(Audit audit, int userID) - { - int result = 0; - var parameters = new DynamicParameters(); - - using(var transaction = new TransactionScope()) - { - try - { - parameters.Add("AuditNo", audit.AuditNo); - parameters.Add("Title", audit.AuditTitle); - //parameters.Add("AuditTypeID", audit.AuditTypeID); - parameters.Add("AuditDate", audit.AuditDate); - parameters.Add("AuditStatus", audit.AuditStatus); - parameters.Add("AuditScore", audit.AuditScore); - //parameters.Add("AuditedAreaID", audit.AuditedAreaID); - parameters.Add("Auditees", audit.Auditees); - this.db.Execute("_8DUpdateAudit", param: parameters, commandType: CommandType.StoredProcedure); - - parameters = new DynamicParameters(); - parameters.Add("@AuditNo", audit.AuditNo); - this.db.Execute("_8DDeleteAuditors", parameters, commandType: CommandType.StoredProcedure); - List auditors = audit.AuditorIDs; - if (auditors != null) - { - foreach (int auditorID in auditors) - { - parameters = new DynamicParameters(); - parameters.Add("@AuditNo", audit.AuditNo); - parameters.Add("@AuditorID", auditorID); - this.db.Execute("_8DInsertAuditor", parameters, commandType: CommandType.StoredProcedure); - } - } - - - parameters = new DynamicParameters(); - parameters.Add("@AuditNo", audit.AuditNo); - this.db.Execute("_8DDeleteAuditTypes", parameters, commandType: CommandType.StoredProcedure); - List auditTypes = audit.AuditTypeIDs; - if (auditTypes != null) - { - foreach (int auditTypeID in auditTypes) - { - parameters = new DynamicParameters(); - parameters.Add("@AuditNo", audit.AuditNo); - parameters.Add("@AuditTypeID", auditTypeID); - this.db.Execute("_8DInsertAuditType", parameters, commandType: CommandType.StoredProcedure); - } - } - - parameters = new DynamicParameters(); - parameters.Add("@AuditNo", audit.AuditNo); - this.db.Execute("_8DDeleteAuditedAreas", parameters, commandType: CommandType.StoredProcedure); - List auditedAreas = audit.AuditedAreaIDs; - if (auditedAreas != null) - { - foreach (int auditedAreaID in auditedAreas) - { - parameters = new DynamicParameters(); - parameters.Add("@AuditNo", audit.AuditNo); - parameters.Add("@AuditedAreaID", auditedAreaID); - this.db.Execute("_8DInsertAuditedArea", parameters, commandType: CommandType.StoredProcedure); - } - } - - transaction.Complete(); - - - - } - - - - - catch (Exception ex) - { - transaction.Dispose(); - throw new Exception(ex.Message + " " + ex.InnerException); - } - } - //FabApprovalSystemEntitiesAll auditDb = new FabApprovalSystemEntitiesAll(); - - //List auditedStandards = audit.AuditedStandardIDs; - //if (auditedStandards != null) - //{ - // foreach (int auditedStandard in auditedStandards) - // { - // var auditStandardExists = (from a in auditDb.C_8DAuditedStandardByAudit where a.AuditNo == audit.AuditNo && a.AuditedStandardID == auditedStandard select a).ToList(); - // if (auditStandardExists.Count() <= 0) - // { - // C_8DAuditedStandardByAudit standard = new C_8DAuditedStandardByAudit - // { - // AuditNo = audit.AuditNo, - // AuditedStandardID = auditedStandard - // }; - // auditDb.C_8DAuditedStandardByAudit.Add(standard); - // auditDb.SaveChanges(); - // } - - // } - //} - - //parameters = new DynamicParameters(); - //parameters.Add("AuditNo", audit.AuditNo); - //this.db.Execute("_8DUpdateAuditScore", parameters, commandType: CommandType.StoredProcedure); - } - - - - /// - /// - /// - /// - /// - public IEnumerable GetAuditReportAttachments(int auditNo) - { - var parameters = new DynamicParameters(); - parameters.Add("@AuditNo", auditNo); - var data = this.db.Query("_8DGetAuditReportAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - /// - /// - /// - /// - /// - public IEnumerable GetCAFindingsItemAttachments(int caFindingsID) - { - var parameters = new DynamicParameters(); - parameters.Add("@CAFindingsID", caFindingsID); - var data = this.db.Query("_8DGetCAFindingsItemAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - /// - /// - /// - /// - public IEnumerable GetUserList() - { - var parameters = new DynamicParameters(); - var userList = this.db.Query("_8DGetUserList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return userList; - } - - public AuditFindings GetAuditFindingsByID(int auditFindingsID) - { - var parameters = new DynamicParameters(); - parameters.Add("@AuditFindingsID", auditFindingsID); - var data = this.db.Query("SELECT * FROM _8DAuditFinding WHERE ID = @AuditFindingsID", parameters).SingleOrDefault(); - return data; - } - public IEnumerable GetAuditFindingCategoryIdsByFindingId(int auditFindingsID) - { - var parameters = new DynamicParameters(); - parameters.Add("@AuditFindingID", auditFindingsID); - var data = this.db.Query("SELECT CategoryID FROM _8DAuditFindingCategoryByAuditFinding WHERE AuditFindingID = @AuditFindingID", parameters).ToList(); - return data; - } - /// - /// - /// - /// - /// - public IEnumerable GetAuditFindingsList(int auditNo) - { - var parameters = new DynamicParameters(); - parameters.Add("@AuditNo", auditNo); - var data = this.db.Query("_8DGetAuditFindingsList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - - - /// - /// - /// - /// - public void DeleteAuditReportAttachment(int attachmentID) - { - var parameters = new DynamicParameters(); - parameters.Add("@AttachmentID", attachmentID); - this.db.Execute("_8DDeleteAuditReportAttachments", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - public void InsertAuditReportAttachment(AuditReportAttachment attach) - { - var parameters = new DynamicParameters(); - parameters.Add("@AuditNo", attach.AuditNo); - parameters.Add("@CAFindingsID", attach.CAFindingsID); - parameters.Add("@UploadedByID", attach.UploadedByID); - parameters.Add("@FileName", attach.FileName); - parameters.Add("@FileGUID", attach.FileGUID); - - this.db.Execute("_8DInsertAuditReportAttachment", parameters, commandType: CommandType.StoredProcedure); - - - } - - - /// - /// - /// - /// - /// - internal string GetAuditReportAttachmentFileName(string fileGUID) - { - var parameters = new DynamicParameters(); - parameters.Add("@FileGUID", fileGUID); - var fileName = this.db.Query("_8DGetAuditReportAttachmentFileName", parameters, commandType: CommandType.StoredProcedure).Single(); - return fileName; - } - - /// - /// - /// - /// - internal void InsertAuditFindingsItem(AuditFindings data) - { - var parameters = new DynamicParameters(); - parameters.Add("@AuditNo", data.AuditNo); - parameters.Add("@Findings", data.Findings); - parameters.Add("@ViolatedClause", data.ViolatedClause); - parameters.Add("@FindingType", data.FindingType); - parameters.Add("@FindingCategories", data.FindingCategories); - parameters.Add("@CANo", data.CANo); - parameters.Add("@Title", data.Title); - - - this.db.Execute("_8DInsertAuditFinding", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - internal void UpdateAuditFindingsItem(AuditFindings data) - { - var parameters = new DynamicParameters(); - parameters.Add("@AuditFindingsID", data.ID); - parameters.Add("@Findings", data.Findings); - parameters.Add("@ViolatedClause", data.ViolatedClause); - parameters.Add("@FindingType", data.FindingType); - parameters.Add("@FindingCategories", data.FindingCategories); - parameters.Add("@CANo", data.CANo); - parameters.Add("@Title", data.Title); - - - - this.db.Execute("_8DUpdateAuditFinding", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - internal void DeleteAuditFindingsItem(int auditFindingsID ) - { - var parameters = new DynamicParameters(); - parameters.Add("@AuditFindingsID", auditFindingsID); - - this.db.Execute("_8DDeleteAuditFinding", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - internal List GetAuditFindingCategories() - { - var parameters = new DynamicParameters(); - return this.db.Query("_8DGetAuditFindingCategories", commandType: CommandType.StoredProcedure).ToList(); - } - - /// - /// - /// - /// - /// - public void ReleaseLockOnDocument(int userID, int issueID) - { - var parameters = new DynamicParameters(); - parameters.Add("@AuditNo", issueID); - parameters.Add("@UserID", userID); - this.db.Execute("_8DReleaseLockOnAuditDocuments", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - public IEnumerable GetCorrectiveActionNoList() - { - var parameters = new DynamicParameters(); - var dataList = this.db.Query("_8DGetCorrectiveActionNoList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return dataList; - } - - /// - /// - /// - /// - /// - public List Get8DQA() - { - List users = new List(); - var parameters = new DynamicParameters(); - users = this.db.Query("_8DGet8DQA", parameters, commandType: CommandType.StoredProcedure).ToList(); - return users; - - } - - - /// - /// - /// - /// - /// - public int GetOpenCACountByAuditNo(int auditNo) - { - - int rowCount = 0 ; - var parameters = new DynamicParameters(); - parameters.Add("@AuditNo", auditNo); - rowCount = this.db.Query("_8DGetOpenCACountByAuditNo", parameters, commandType: CommandType.StoredProcedure).Single(); - return rowCount; - - - - } - - - - // CA Findings ==================================================================================================================================== - - - /// - /// - /// - /// - public void InsertCAFindings(CAFindings model) - { - - var parameters = new DynamicParameters(); - parameters.Add("@AuditNo", model.AuditNo); - parameters.Add("@CAFinding", model.CAFinding); - parameters.Add("@CorrectiveAction", model.CorrectiveAction); - parameters.Add("@Result", model.Result); - parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); - parameters.Add("@ECD", model.ECD); - parameters.Add("@ImplementedDate", model.ImplementedDate); - - this.db.Execute("_8DInsertCAFindings", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - public void UpdateCAFindings(CAFindings model) - { - - var parameters = new DynamicParameters(); - parameters.Add("@CAFindingsID", model.ID); - parameters.Add("@CAFinding", model.CAFinding); - parameters.Add("@CorrectiveAction", model.CorrectiveAction); - parameters.Add("@Result", model.Result); - parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); - parameters.Add("@ECD", model.ECD); - parameters.Add("@ImplementedDate", model.ImplementedDate); - - this.db.Execute("_8DUpdateCAFindings", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - public void DeleteCAFindingsItem(int caFindingsID) - { - var parameters = new DynamicParameters(); - parameters.Add("@CAFindingsID", caFindingsID); - - this.db.Execute("_8DDeleteCAFindingsItem", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - /// - public CAFindings GetCAFindingsItem(int caFindingsID) - { - var model = new CAFindings(); - var parameters = new DynamicParameters(); - parameters.Add("@CAFindingsID", caFindingsID); - var data = this.db.Query("_8DGetCAFindings", parameters, commandType: CommandType.StoredProcedure).Single(); - return data; - } - - /// - /// - /// - /// - /// - public IEnumerable GetCAFindingsList(int auditNo) - { - - var parameters = new DynamicParameters(); - parameters.Add("@AuditNo", auditNo); - var dataList = this.db.Query("_8DGetCAFindingsList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return dataList; - - } - - /// - /// - /// - /// - /// - public int IsCAAssignedToAudit(int CANo, int auditNo) - { - var parameters = new DynamicParameters(); - int returnValue = 1; - parameters.Add("@CANo", CANo); - parameters.Add("@AuditNo", auditNo); - parameters.Add("@IsCAAssignedToAudit", returnValue, direction: ParameterDirection.Output); - - this.db.Execute("_8DIsCAAssignedtoAudit", parameters, commandType: CommandType.StoredProcedure); - - returnValue = parameters.Get("IsCAAssignedToAudit"); - return returnValue; - } + db.Execute("_8DInsertAuditItem", parameters, commandType: CommandType.StoredProcedure); + audit.AuditNo = parameters.Get("@AuditNo"); + return audit; } -} + + public Audit GetAuditItem(int auditNo, int userID) { + Audit audit = new(); + + //isITAR = 2; + + DynamicParameters parameters = new(); + parameters.Add("@AuditNo", value: auditNo); + parameters.Add("@UserID", userID); + //parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + //audit = this.db.Query("_8DGetAuditItem", parameters, commandType: CommandType.StoredProcedure).Single(); + + using (var multipleResultItems = db.QueryMultiple("_8DGetAuditItem", parameters, commandType: CommandType.StoredProcedure)) { + audit = multipleResultItems.Read().SingleOrDefault(); + + List auditors = multipleResultItems.Read().ToList(); + + if (audit != null && auditors != null) { + if (auditors.Count > 0) + audit.AuditorIDs.AddRange(auditors); + } + + List auditorTypes = multipleResultItems.Read().ToList(); + if (audit != null && auditorTypes != null) { + if (auditorTypes.Count > 0) + audit.AuditTypeIDs.AddRange(auditorTypes); + } + + List auditorAreas = multipleResultItems.Read().ToList(); + if (audit != null && auditorAreas != null) { + if (auditorAreas.Count > 0) + audit.AuditedAreaIDs.AddRange(auditorAreas); + } + } + //FabApprovalSystemEntitiesAll auditDb = new FabApprovalSystemEntitiesAll(); + + //var auditedStandardIDs = (from a in auditDb.C_8DAuditedStandardByAudit where a.AuditNo == audit.AuditNo select a.AuditedStandardID).ToList(); + + //foreach (var id in auditedStandardIDs) + //{ + // audit.AuditedStandardIDs.Add(id); + //} + + return audit; + } + + public Audit GetAuditItemReadOnly(int auditNo, int userID) { + Audit audit = new(); + + //isITAR = 2; + + DynamicParameters parameters = new(); + parameters.Add("@AuditNo", value: auditNo); + parameters.Add("@UserID", userID); + //parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + //audit = this.db.Query("_8DGetAuditItem", parameters, commandType: CommandType.StoredProcedure).Single(); + + using (var multipleResultItems = db.QueryMultiple("_8DGetAuditItemReadOnly", parameters, commandType: CommandType.StoredProcedure)) { + audit = multipleResultItems.Read().SingleOrDefault(); + + List auditors = multipleResultItems.Read().ToList(); + + if (audit != null && auditors != null) { + if (auditors.Count > 0) + audit.AuditorIDs.AddRange(auditors); + } + + List auditorTypes = multipleResultItems.Read().ToList(); + if (audit != null && auditorTypes != null) { + if (auditorTypes.Count > 0) + audit.AuditTypeIDs.AddRange(auditorTypes); + } + + List auditorAreas = multipleResultItems.Read().ToList(); + if (audit != null && auditorAreas != null) { + if (auditorAreas.Count > 0) + audit.AuditedAreaIDs.AddRange(auditorAreas); + } + } + + return audit; + } + + public IEnumerable GetAuditTypeList() { + DynamicParameters parameters = new(); + + List auditTypeList = db.Query("_8DGetAuditTypeList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return auditTypeList; + } + +#if !NET8 + public IEnumerable GetAuditStandardList() { + FabApprovalSystemEntitiesAll db = new FabApprovalSystemEntitiesAll(); + + var auditStandardList = from a in db.C_8DAuditedStandard select a; + + return auditStandardList; + } +#endif + public IEnumerable GetAuditorList() { + DynamicParameters parameters = new(); + + List auditorList = db.Query("_8DGetAuditorList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return auditorList; + } + + public IEnumerable GetAuditAreaList() { + DynamicParameters parameters = new(); + + List auditAreaList = db.Query("_8DGetAuditAreaList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return auditAreaList; + } + + public void UpdateAudit(Audit audit, int userID) { + int result = 0; + DynamicParameters parameters = new(); + + using (TransactionScope transaction = new()) { + try { + parameters.Add("AuditNo", audit.AuditNo); + parameters.Add("Title", audit.AuditTitle); + //parameters.Add("AuditTypeID", audit.AuditTypeID); + parameters.Add("AuditDate", audit.AuditDate); + parameters.Add("AuditStatus", audit.AuditStatus); + parameters.Add("AuditScore", audit.AuditScore); + //parameters.Add("AuditedAreaID", audit.AuditedAreaID); + parameters.Add("Auditees", audit.Auditees); + db.Execute("_8DUpdateAudit", param: parameters, commandType: CommandType.StoredProcedure); + + parameters = new DynamicParameters(); + parameters.Add("@AuditNo", audit.AuditNo); + db.Execute("_8DDeleteAuditors", parameters, commandType: CommandType.StoredProcedure); + List auditors = audit.AuditorIDs; + if (auditors != null) { + foreach (int auditorID in auditors) { + parameters = new DynamicParameters(); + parameters.Add("@AuditNo", audit.AuditNo); + parameters.Add("@AuditorID", auditorID); + db.Execute("_8DInsertAuditor", parameters, commandType: CommandType.StoredProcedure); + } + } + + parameters = new DynamicParameters(); + parameters.Add("@AuditNo", audit.AuditNo); + db.Execute("_8DDeleteAuditTypes", parameters, commandType: CommandType.StoredProcedure); + List auditTypes = audit.AuditTypeIDs; + if (auditTypes != null) { + foreach (int auditTypeID in auditTypes) { + parameters = new DynamicParameters(); + parameters.Add("@AuditNo", audit.AuditNo); + parameters.Add("@AuditTypeID", auditTypeID); + db.Execute("_8DInsertAuditType", parameters, commandType: CommandType.StoredProcedure); + } + } + + parameters = new DynamicParameters(); + parameters.Add("@AuditNo", audit.AuditNo); + db.Execute("_8DDeleteAuditedAreas", parameters, commandType: CommandType.StoredProcedure); + List auditedAreas = audit.AuditedAreaIDs; + if (auditedAreas != null) { + foreach (int auditedAreaID in auditedAreas) { + parameters = new DynamicParameters(); + parameters.Add("@AuditNo", audit.AuditNo); + parameters.Add("@AuditedAreaID", auditedAreaID); + db.Execute("_8DInsertAuditedArea", parameters, commandType: CommandType.StoredProcedure); + } + } + + transaction.Complete(); + + } catch (Exception ex) { + transaction.Dispose(); + throw new Exception(ex.Message + " " + ex.InnerException); + } + } + //FabApprovalSystemEntitiesAll auditDb = new FabApprovalSystemEntitiesAll(); + + //List auditedStandards = audit.AuditedStandardIDs; + //if (auditedStandards != null) + //{ + // foreach (int auditedStandard in auditedStandards) + // { + // var auditStandardExists = (from a in auditDb.C_8DAuditedStandardByAudit where a.AuditNo == audit.AuditNo && a.AuditedStandardID == auditedStandard select a).ToList(); + // if (auditStandardExists.Count() <= 0) + // { + // C_8DAuditedStandardByAudit standard = new C_8DAuditedStandardByAudit + // { + // AuditNo = audit.AuditNo, + // AuditedStandardID = auditedStandard + // }; + // auditDb.C_8DAuditedStandardByAudit.Add(standard); + // auditDb.SaveChanges(); + // } + + // } + //} + + //parameters = new DynamicParameters(); + //parameters.Add("AuditNo", audit.AuditNo); + //this.db.Execute("_8DUpdateAuditScore", parameters, commandType: CommandType.StoredProcedure); + } + + public IEnumerable GetAuditReportAttachments(int auditNo) { + DynamicParameters parameters = new(); + parameters.Add("@AuditNo", auditNo); + List data = db.Query("_8DGetAuditReportAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetCAFindingsItemAttachments(int caFindingsID) { + DynamicParameters parameters = new(); + parameters.Add("@CAFindingsID", caFindingsID); + List data = db.Query("_8DGetCAFindingsItemAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetUserList() { + DynamicParameters parameters = new(); + List userList = db.Query("_8DGetUserList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return userList; + } + + public AuditFindings GetAuditFindingsByID(int auditFindingsID) { + DynamicParameters parameters = new(); + parameters.Add("@AuditFindingsID", auditFindingsID); + var data = db.Query("SELECT * FROM _8DAuditFinding WHERE ID = @AuditFindingsID", parameters).SingleOrDefault(); + return data; + } + + public IEnumerable GetAuditFindingCategoryIdsByFindingId(int auditFindingsID) { + DynamicParameters parameters = new(); + parameters.Add("@AuditFindingID", auditFindingsID); + List data = db.Query("SELECT CategoryID FROM _8DAuditFindingCategoryByAuditFinding WHERE AuditFindingID = @AuditFindingID", parameters).ToList(); + return data; + } + + public IEnumerable GetAuditFindingsList(int auditNo) { + DynamicParameters parameters = new(); + parameters.Add("@AuditNo", auditNo); + List data = db.Query("_8DGetAuditFindingsList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public void DeleteAuditReportAttachment(int attachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@AttachmentID", attachmentID); + db.Execute("_8DDeleteAuditReportAttachments", parameters, commandType: CommandType.StoredProcedure); + } + + public void InsertAuditReportAttachment(AuditReportAttachment attach) { + DynamicParameters parameters = new(); + parameters.Add("@AuditNo", attach.AuditNo); + parameters.Add("@CAFindingsID", attach.CAFindingsID); + parameters.Add("@UploadedByID", attach.UploadedByID); + parameters.Add("@FileName", attach.FileName); + parameters.Add("@FileGUID", attach.FileGUID); + + db.Execute("_8DInsertAuditReportAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal string GetAuditReportAttachmentFileName(string fileGUID) { + DynamicParameters parameters = new(); + parameters.Add("@FileGUID", fileGUID); + var fileName = db.Query("_8DGetAuditReportAttachmentFileName", parameters, commandType: CommandType.StoredProcedure).Single(); + return fileName; + } + + internal void InsertAuditFindingsItem(AuditFindings data) { + DynamicParameters parameters = new(); + parameters.Add("@AuditNo", data.AuditNo); + parameters.Add("@Findings", data.Findings); + parameters.Add("@ViolatedClause", data.ViolatedClause); + parameters.Add("@FindingType", data.FindingType); + parameters.Add("@FindingCategories", data.FindingCategories); + parameters.Add("@CANo", data.CANo); + parameters.Add("@Title", data.Title); + + db.Execute("_8DInsertAuditFinding", parameters, commandType: CommandType.StoredProcedure); + } + + internal void UpdateAuditFindingsItem(AuditFindings data) { + DynamicParameters parameters = new(); + parameters.Add("@AuditFindingsID", data.ID); + parameters.Add("@Findings", data.Findings); + parameters.Add("@ViolatedClause", data.ViolatedClause); + parameters.Add("@FindingType", data.FindingType); + parameters.Add("@FindingCategories", data.FindingCategories); + parameters.Add("@CANo", data.CANo); + parameters.Add("@Title", data.Title); + + db.Execute("_8DUpdateAuditFinding", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteAuditFindingsItem(int auditFindingsID) { + DynamicParameters parameters = new(); + parameters.Add("@AuditFindingsID", auditFindingsID); + + db.Execute("_8DDeleteAuditFinding", parameters, commandType: CommandType.StoredProcedure); + } + + internal List GetAuditFindingCategories() { + DynamicParameters parameters = new(); + return db.Query("_8DGetAuditFindingCategories", commandType: CommandType.StoredProcedure).ToList(); + } + + public void ReleaseLockOnDocument(int userID, int issueID) { + DynamicParameters parameters = new(); + parameters.Add("@AuditNo", issueID); + parameters.Add("@UserID", userID); + db.Execute("_8DReleaseLockOnAuditDocuments", parameters, commandType: CommandType.StoredProcedure); + } + + public IEnumerable GetCorrectiveActionNoList() { + DynamicParameters parameters = new(); + List dataList = db.Query("_8DGetCorrectiveActionNoList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return dataList; + } + + public List Get8DQA() { + List users = new(); + DynamicParameters parameters = new(); + users = db.Query("_8DGet8DQA", parameters, commandType: CommandType.StoredProcedure).ToList(); + return users; + } + + public int GetOpenCACountByAuditNo(int auditNo) { + int rowCount = 0; + DynamicParameters parameters = new(); + parameters.Add("@AuditNo", auditNo); + rowCount = db.Query("_8DGetOpenCACountByAuditNo", parameters, commandType: CommandType.StoredProcedure).Single(); + return rowCount; + } + + // CA Findings ==================================================================================================================================== + + public void InsertCAFindings(CAFindings model) { + DynamicParameters parameters = new(); + parameters.Add("@AuditNo", model.AuditNo); + parameters.Add("@CAFinding", model.CAFinding); + parameters.Add("@CorrectiveAction", model.CorrectiveAction); + parameters.Add("@Result", model.Result); + parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); + parameters.Add("@ECD", model.ECD); + parameters.Add("@ImplementedDate", model.ImplementedDate); + + db.Execute("_8DInsertCAFindings", parameters, commandType: CommandType.StoredProcedure); + } + + public void UpdateCAFindings(CAFindings model) { + DynamicParameters parameters = new(); + parameters.Add("@CAFindingsID", model.ID); + parameters.Add("@CAFinding", model.CAFinding); + parameters.Add("@CorrectiveAction", model.CorrectiveAction); + parameters.Add("@Result", model.Result); + parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); + parameters.Add("@ECD", model.ECD); + parameters.Add("@ImplementedDate", model.ImplementedDate); + + db.Execute("_8DUpdateCAFindings", parameters, commandType: CommandType.StoredProcedure); + } + + public void DeleteCAFindingsItem(int caFindingsID) { + DynamicParameters parameters = new(); + parameters.Add("@CAFindingsID", caFindingsID); + + db.Execute("_8DDeleteCAFindingsItem", parameters, commandType: CommandType.StoredProcedure); + } + + public CAFindings GetCAFindingsItem(int caFindingsID) { + CAFindings model = new(); + DynamicParameters parameters = new(); + parameters.Add("@CAFindingsID", caFindingsID); + var data = db.Query("_8DGetCAFindings", parameters, commandType: CommandType.StoredProcedure).Single(); + return data; + } + + public IEnumerable GetCAFindingsList(int auditNo) { + DynamicParameters parameters = new(); + parameters.Add("@AuditNo", auditNo); + List dataList = db.Query("_8DGetCAFindingsList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return dataList; + } + + public int IsCAAssignedToAudit(int CANo, int auditNo) { + DynamicParameters parameters = new(); + int returnValue = 1; + parameters.Add("@CANo", CANo); + parameters.Add("@AuditNo", auditNo); + parameters.Add("@IsCAAssignedToAudit", returnValue, direction: ParameterDirection.Output); + + db.Execute("_8DIsCAAssignedtoAudit", parameters, commandType: CommandType.StoredProcedure); + + returnValue = parameters.Get("IsCAAssignedToAudit"); + return returnValue; + } + + public AuditEdit GetAuditEdit(int issueID, Audit audit, bool isAdmin, int userId) { + AuditEdit result = new(); + List userList = Get8DQA(); + result.MesaUsers = UserUtilities.GetMesaUsers(); + int QAs = userList.Find(delegate (int al) { return al == userId; }); + result.Is8DQA = "false"; + if (QAs != 0) { + result.Is8DQA = "true"; + } + + audit = GetAuditItem(issueID, userId); + //transform audit users from string to list, delimited by a comma. + if (audit.Auditees == null) { + result.AuditeeNames = new List(); + } else { + string[] auditeeNames = audit.Auditees.Split(','); + result.AuditeeNames = auditeeNames.ToList(); + } + + result.IsSubmitter = false; + if (audit.OriginatorID == userId) { + result.IsSubmitter = true; + } + if (isAdmin != true) { + result.IsAdmin = false; + } else { + result.IsAdmin = true; + } + if ((audit.RecordLockIndicator && audit.RecordLockedBy != userId) + || audit.AuditStatus != 0) //open + { + result.RedirectToAction = true; + } + if (result.IsAdmin == false && result.IsSubmitter == false) { + result.RedirectToAction = true; + } else { + result.UserList = GetUserList(); + result.AuditTypeList = GetAuditTypeList(); + // result.AuditStandardList = GetAuditStandardList(); + result.AuditorList = GetAuditorList(); + result.AuditAreaList = GetAuditAreaList(); + result.AuditFindingCategoryList = GetAuditFindingCategories(); + result.CANoList = GetCorrectiveActionNoList(); + } + return result; + } + + public List GetFileNameAndDocument(string fileGuid, int auditNo) { + List results = new(); + string fileName = GetAuditReportAttachmentFileName(fileGuid); + string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")); + + string ecnFolderPath = _AppSettings.AttachmentFolder + "Audit\\" + auditNo.ToString(); + string sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension); + + string FDir_AppData = _AppSettings.AttachmentFolder; + if (!sDocument.StartsWith(FDir_AppData)) { + sDocument = string.Empty; + } + results.Add(fileName); + results.Add(sDocument); + return results; + } + + public Audit InsertAndGetAudit(CorrectiveActionDMO caDMO, AuditFindings data, int userID) { + Audit audit = new(); + InsertAuditFindingsItem(data); + audit = GetAuditItem(data.AuditNo, userID); + + //Transfer Finding Details to CA + if (data.CANo != 0) { + CorrectiveAction ca = caDMO.GetCAItem(data.CANo, userID); + ca.CATitle = data.Title; + ca.CASourceID = 1;//Audit + caDMO.UpdateCorrectiveAction(ca); + } + + return audit; + } + + public Audit UpdateAndGetAudit(CorrectiveActionDMO caDMO, AuditFindings data, int userID) { + Audit audit = new(); + UpdateAuditFindingsItem(data); + audit = GetAuditItem(data.AuditNo, userID); + + //Transfer Finding Details to CA + if (data.CANo != 0) { + CorrectiveAction ca = caDMO.GetCAItem(data.CANo, userID); + ca.CATitle = data.Title; + ca.CASourceID = 1;//Audit + caDMO.UpdateCorrectiveAction(ca); + } + + return audit; + } + + public Audit DeleteAndGetAudit(int auditFindingsID, int userID) { + var af = GetAuditFindingsByID(auditFindingsID); + DeleteAuditFindingsItem(auditFindingsID); + var audit = GetAuditItem(af.AuditNo, userID); + return audit; + } + + public void AuditReportAttachSave(int auditNo, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var ccPhysicalPath = _AppSettings.AttachmentFolder + @"Audit\" + auditNo; + di = new DirectoryInfo(ccPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"Audit\" + auditNo + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + AuditReportAttachment attach = new() { + AuditNo = auditNo, + FileGUID = guid, + FileName = fileName, + UploadedByID = userId + + }; + + //ccDMO.InsertCCAttachment(attach); + InsertAuditReportAttachment(attach); + } + + public void SaveAndInsert(int caFindingsID, int auditNo, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var ccPhysicalPath = _AppSettings.AttachmentFolder + @"Audit\" + auditNo; + di = new DirectoryInfo(ccPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"Audit\" + auditNo + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + AuditReportAttachment attach = new() { + CAFindingsID = caFindingsID, + AuditNo = auditNo, + FileGUID = guid, + FileName = fileName, + UploadedByID = userId + + }; + + InsertAuditReportAttachment(attach); + } + + public string NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID, string emailTemplatesPath) { + string emailSentList = ""; + + //List emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); + string email = MiscDMO.GetEmail(responsibleOwnerID); + + string emailTemplate = "CorrectiveActionFindingAssigned.txt"; + string userEmail = string.Empty; + string subject = "5s/CA Findings"; + string senderName = "CorrectiveAction"; + + EmailNotification en = new(_AppSettings, subject, emailTemplatesPath); + string[] emailparams = new string[5]; + emailparams[0] = Functions.ReturnAuditNoStringFormat(issueID); + if (dueDate is null) + emailparams[1] = string.Empty; + else + emailparams[1] = dueDate.Value.ToString(); + emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.Audit); + emailparams[3] = GlobalVars.hostURL; + emailparams[4] = issueID.ToString(); + userEmail = email; + + en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); + emailSentList += email + ","; + return email; + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/ChangeControlDMO.cs b/Fab2ApprovalSystem/DMO/ChangeControlDMO.cs index 92e56a5..abb7561 100644 --- a/Fab2ApprovalSystem/DMO/ChangeControlDMO.cs +++ b/Fab2ApprovalSystem/DMO/ChangeControlDMO.cs @@ -1,1099 +1,874 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.IO; +using System.Linq; +using System.Transactions; + using Dapper; + using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.ViewModels; -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Data.SqlClient; -using System.Linq; -using System.Text; -using System.Transactions; -using System.Web; -namespace Fab2ApprovalSystem.DMO -{ - public class ChangeControlDMO - { - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - WorkflowDMO wfDMO = new WorkflowDMO(); +namespace Fab2ApprovalSystem.DMO; - /// - /// - /// - /// - /// - internal ChangeControlViewModel InsertChangeControl(ChangeControlViewModel cc) - { +public class ChangeControlDMO { - var parameters = new DynamicParameters(); - parameters.Add("@PlanNumber", value: cc.PlanNumber, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@OwnerID", cc.OwnerID); + private readonly AppSettings _AppSettings; + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - this.db.Execute("CCInsertChangeControl", parameters, commandType: CommandType.StoredProcedure); - cc.PlanNumber = parameters.Get("@PlanNumber"); + public ChangeControlDMO(AppSettings appSettings) => + _AppSettings = appSettings; - return cc; - } + internal ChangeControlViewModel InsertChangeControl(ChangeControlViewModel cc) { + DynamicParameters parameters = new(); + parameters.Add("@PlanNumber", value: cc.PlanNumber, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@OwnerID", cc.OwnerID); + db.Execute("CCInsertChangeControl", parameters, commandType: CommandType.StoredProcedure); + cc.PlanNumber = parameters.Get("@PlanNumber"); - /// - /// - /// - /// - /// - internal ChangeControlViewModel GetChangeControl(int planNumber, out int canViewITAR, int userID ) - { - canViewITAR = 1; - ChangeControlViewModel ccItem = new ChangeControlViewModel(); - var parameters = new DynamicParameters(); - parameters.Add("@planNumber", planNumber); - - parameters.Add("@UserID", userID); - //parameters.Add("@UserID", GlobalVars.USER_ID); - parameters.Add("@CanViewITAR", value: canViewITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - //cc = this.db.Query("CCGetChangeControl", parameters, commandType: CommandType.StoredProcedure).SingleOrDefault(); - - - using (var multipleResultItems = this.db.QueryMultiple("CCGetChangeControl", parameters, commandType: CommandType.StoredProcedure)) - { - ccItem = multipleResultItems.Read().SingleOrDefault(); - - var gens = multipleResultItems.Read().ToList(); - //if (ccItem != null && gens != null) - //{ - // if (gens.Count > 0) - // ccItem.GenerationIDs.AddRange(gens); - //} - - - var logis = multipleResultItems.Read().ToList(); - //if (ccItem != null && logis != null) - //{ - // if (logis.Count > 0) - // ccItem.LogisticsIDs.AddRange(logis); - //} - - var procs = multipleResultItems.Read().ToList(); - //if (ccItem != null && procs != null) - //{ - // if (procs.Count > 0) - // ccItem.ProcessIDs.AddRange(procs); - //} - - - - //var parts = multipleResultItems.Read().ToList(); - //if (ccItem != null && parts != null) - //{ - // if (parts.Count > 0) - // ccItem.PartNumberIDs.AddRange(parts); - //} - - - - } - return ccItem; - } - - - - internal ChangeControlViewModel GetChangeControlRead(int planNumber, out int canViewITAR, int userID) - { - canViewITAR = 1; - ChangeControlViewModel ccItem = new ChangeControlViewModel(); - var parameters = new DynamicParameters(); - parameters.Add("@planNumber", planNumber); - - parameters.Add("@UserID", userID); - //parameters.Add("@UserID", GlobalVars.USER_ID); - parameters.Add("@CanViewITAR", value: canViewITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - //cc = this.db.Query("CCGetChangeControl", parameters, commandType: CommandType.StoredProcedure).SingleOrDefault(); - - - using (var multipleResultItems = this.db.QueryMultiple("CCGetChangeControlRead", parameters, commandType: CommandType.StoredProcedure)) - { - ccItem = multipleResultItems.Read().SingleOrDefault(); - - var gens = multipleResultItems.Read().ToList(); - //if (ccItem != null && gens != null) - //{ - // if (gens.Count > 0) - // ccItem.GenerationIDs.AddRange(gens); - //} - - - var logis = multipleResultItems.Read().ToList(); - //if (ccItem != null && logis != null) - //{ - // if (logis.Count > 0) - // ccItem.LogisticsIDs.AddRange(logis); - //} - - var procs = multipleResultItems.Read().ToList(); - //if (ccItem != null && procs != null) - //{ - // if (procs.Count > 0) - // ccItem.ProcessIDs.AddRange(procs); - //} - - //var tools = multipleResultItems.Read().ToList(); - //if (ccItem != null && tools != null) - //{ - // if (tools.Count > 0) - // ccItem.ToolTypeIDs.AddRange(tools); - //} - - //var parts = multipleResultItems.Read().ToList(); - //if (ccItem != null && parts != null) - //{ - // if (parts.Count > 0) - // ccItem.PartNumberIDs.AddRange(parts); - //} - - canViewITAR = parameters.Get("@CanViewITAR"); - - } - return ccItem; - } - - /// - /// - /// - /// - internal List GetGenerations() - { - var parameters = new DynamicParameters(); - return this.db.Query("CCGetGenerations", commandType: CommandType.StoredProcedure).ToList(); - } - - /// - /// - /// - /// - internal List GetLogistics() - { - var parameters = new DynamicParameters(); - - - return this.db.Query("CCGetLogistics", commandType: CommandType.StoredProcedure).ToList(); - } - - /// - /// - /// - /// - //internal List GetToolTypes() - //{ - // var parameters = new DynamicParameters(); - // return this.db.Query("CCGetToolTypes", commandType: CommandType.StoredProcedure).ToList(); - //} - - /// - /// - /// - /// - internal List GetProcesses() - { - var parameters = new DynamicParameters(); - return this.db.Query("CCGetProcesses", commandType: CommandType.StoredProcedure).ToList(); - } - - /// - /// - /// - /// - internal List GetPartNumbers() - { - var parameters = new DynamicParameters(); - return this.db.Query("CCGetPartNumbers", commandType: CommandType.StoredProcedure).ToList(); - } - - /// - /// - /// - /// - /// - internal int UpdateChangeControl(ChangeControlViewModel model, int userID) - { - int result = 0; - var parameters = new DynamicParameters(); - using (var transaction = new TransactionScope()) - { - try - { - parameters.Add("@PlanNumber", model.PlanNumber); - parameters.Add("@ChangeLevel", model.ChangeLevel); - parameters.Add("@IsITAR", model.IsITAR); - parameters.Add("@IsMedical", model.IsMedical); - parameters.Add("@IsRadHard", model.IsRadHard); - parameters.Add("@Notes", model.Notes); - //parameters.Add("@PartNumbers", model.PartNumbers); - parameters.Add("@IsAutomotive", model.IsAutomotive); - //parameters.Add("@ToolTypes", model.ToolTypes); - parameters.Add("@Title", model.Title); - parameters.Add("@ReasonForChange", model.ReasonForChange); - parameters.Add("@ChangeDescription", model.ChangeDescription); - this.db.Execute("CCUpdateChangeControl", param: parameters, commandType: CommandType.StoredProcedure); - - //parameters = new DynamicParameters(); - //parameters.Add("@PlanNumber", model.PlanNumber); - //this.db.Execute("CCDeleteGenerations", parameters, commandType: CommandType.StoredProcedure); - //List gens = model.GenerationIDs; - //if (gens != null) - //{ - // foreach (int genId in gens) - // { - // parameters = new DynamicParameters(); - // parameters.Add("@PlanNumber", model.PlanNumber); - // parameters.Add("@GenerationID", genId); - // this.db.Execute("CCInsertGeneration", parameters, commandType: CommandType.StoredProcedure); - // } - //} - - - //parameters = new DynamicParameters(); - //parameters.Add("@PlanNumber", model.PlanNumber); - //this.db.Execute("CCDeleteLogistics", parameters, commandType: CommandType.StoredProcedure); - //List logistics = model.LogisticsIDs; - //if (logistics != null) - //{ - // foreach (int logisticsId in logistics) - // { - // parameters = new DynamicParameters(); - // parameters.Add("@PlanNumber", model.PlanNumber); - // parameters.Add("@LogisticsID", logisticsId); - // this.db.Execute("CCInsertLogistics", parameters, commandType: CommandType.StoredProcedure); - // } - //} - - //parameters = new DynamicParameters(); - //parameters.Add("@PlanNumber", model.PlanNumber); - //this.db.Execute("CCDeleteProcesses", parameters, commandType: CommandType.StoredProcedure); - //List processes = model.ProcessIDs; - //if (processes != null) - //{ - // foreach (int processId in processes) - // { - // parameters = new DynamicParameters(); - // parameters.Add("@PlanNumber", model.PlanNumber); - // parameters.Add("@ProcessID", processId); - // this.db.Execute("CCInsertProcess", parameters, commandType: CommandType.StoredProcedure); - // } - //} - - - - - //parameters = new DynamicParameters(); - //parameters.Add("@PlanNumber", model.PlanNumber); - //this.db.Execute("CCDeletePartNumbers", parameters, commandType: CommandType.StoredProcedure); - //if (model.PartNumbers != null) - //{ - // string[] parts = model.PartNumbers.Split(new char[] { ',' }); - // foreach (string part in parts) - // { - // parameters = new DynamicParameters(); - // parameters.Add("@PlanNumber", model.PlanNumber); - // parameters.Add("@PartNumber", part); - // this.db.Execute("CCInsertPartNumber", parameters, commandType: CommandType.StoredProcedure); - // } - //} - transaction.Complete(); - } - catch (Exception ex) - { - transaction.Dispose(); - throw new Exception(ex.Message + " " + ex.InnerException); - } - } - return result; - } - - /// - /// - /// - /// - /// - public IEnumerable GetMeetingDecisionSummaryList(int planNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@PlanNumber", planNumber); - var data = this.db.Query("CCGetMeetingDecisionSummaryList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - /// - /// - /// - /// - /// - public IEnumerable GetCCAttachment(int planNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@PlanNumber", planNumber); - var data = this.db.Query("CCGetCCAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - - - /// - /// - /// - /// - internal CCAttachment InsertCCAttachment(CCAttachment attachment) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", value: attachment.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@PlanNumber", attachment.PlanNumber); - parameters.Add("@Title", attachment.Title); - parameters.Add("@RequirementsNotes", attachment.RequirementsNotes); - this.db.Execute("CCInsertCCAttachment", parameters, commandType: CommandType.StoredProcedure); - attachment.ID = parameters.Get("@ID"); - - return attachment; - } - - /// - /// - /// - /// - internal void UpdateCCAttachmentDocument(CCAttachment attachment) - { - var parameters = new DynamicParameters(); - - parameters.Add("@AttachmentID", attachment.ID); - parameters.Add("@FileName", attachment.FileName); - parameters.Add("@FileGUID", attachment.FileGUID); - - parameters.Add("@UploadedByID", attachment.UploadedByID); - - this.db.Execute("CCUpdateCCAttachmentDocument", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - internal void UpdateCCAttachemnt(CCAttachment attachment) - { - - var parameters = new DynamicParameters(); - parameters.Add("@ID", attachment.ID); - parameters.Add("@Title", attachment.Title); - parameters.Add("@RequirementsNotes", attachment.RequirementsNotes); - this.db.Execute("CCUpdateCCAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - internal void DeleteCCAttachemnt(CCAttachment attachment) - { - - var parameters = new DynamicParameters(); - parameters.Add("@ID", attachment.ID); - - - this.db.Execute("CCDeleteCCAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - /// - internal string GetCCFileName(string fileGUID) - { - var parameters = new DynamicParameters(); - parameters.Add("@FileGUID", fileGUID); - var fileName = this.db.Query("CCGetCCFileName", parameters, commandType: CommandType.StoredProcedure).Single(); - return fileName; - } - - - /// - /// - /// - /// - /// - internal int InsertMeeting(int planNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@PlanNumber", planNumber); - parameters.Add("@MeetingID", value: 0, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - - this.db.Execute("CCInsertMeeting", parameters, commandType: CommandType.StoredProcedure); - int meetingID = parameters.Get("@MeetingID"); - - return meetingID; - } - - /// - /// - /// - /// - /// - internal CCMeeting GetMeeting(int meetingID, out int canViewITAR, int userID) - { - canViewITAR = 1; - CCMeeting ccMeeting = new CCMeeting(); - var parameters = new DynamicParameters(); - parameters.Add("@MeetingID", meetingID); - parameters.Add("@UserID", userID); - parameters.Add("@CanViewITAR", value: canViewITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - - //ccMeeting = this.db.Query("CCGetMeeting", parameters, commandType: CommandType.StoredProcedure).Single(); - using (var multipleResultItems = this.db.QueryMultiple("CCGetMeetingRead", parameters, commandType: CommandType.StoredProcedure)) - { - ccMeeting = multipleResultItems.Read().SingleOrDefault(); - var pcrvalues = multipleResultItems.Read().ToList(); - if (ccMeeting != null && pcrvalues != null) - { - if (pcrvalues.Count > 0) - ccMeeting.PCRValueIDs.AddRange(pcrvalues); - } - } - - return ccMeeting; - } - - - /// - /// - /// - /// - /// - internal CCMeeting GetMeetingRead(int meetingID, out int canViewITAR, int userID) - { - canViewITAR = 1; - CCMeeting ccMeeting = new CCMeeting(); - var parameters = new DynamicParameters(); - parameters.Add("@MeetingID", meetingID); - parameters.Add("@UserID", userID); - parameters.Add("@CanViewITAR", value: canViewITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - - //ccMeeting = this.db.Query("CCGetMeetingRead", parameters, commandType: CommandType.StoredProcedure).Single(); - using (var multipleResultItems = this.db.QueryMultiple("CCGetMeetingRead", parameters, commandType: CommandType.StoredProcedure)) - { - ccMeeting = multipleResultItems.Read().SingleOrDefault(); - var pcrvalues = multipleResultItems.Read().ToList(); - if (ccMeeting != null && pcrvalues != null) - { - if (pcrvalues.Count > 0) - ccMeeting.PCRValueIDs.AddRange(pcrvalues); - } - } - - - - return ccMeeting; - } - internal IEnumerable GetPCRB(int PlanNumber, string PCRB) - { - - var parameters = new DynamicParameters(); - parameters.Add("@PlanNumber", PlanNumber); - parameters.Add("@PCRB", PCRB); - var data = this.db.Query("CCGetPCRB", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - - } - - /// - /// - /// - /// - /// - internal int UpdateMeeting(CCMeeting meeting) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@MeetingID", meeting.MeetingID); - //parameters.Add("@PCRB", meeting.PCRB.ToUpper() == "SELECT" ? null : meeting.PCRB); - parameters.Add("@Decision", meeting.Decision); - parameters.Add("@MeetingDate", meeting.MeetingDate); - parameters.Add("@Notes", meeting.Notes); - - this.db.Execute("CCUpdateMeeting", parameters, commandType: CommandType.StoredProcedure); - - - parameters = new DynamicParameters(); - parameters.Add("@MeetingID", meeting.MeetingID); - this.db.Execute("CCDeleteMeetingPCRValues", parameters, commandType: CommandType.StoredProcedure); - List pcrValues = meeting.PCRValueIDs; - if (pcrValues != null) - { - foreach (string pcrValue in pcrValues) - { - parameters = new DynamicParameters(); - parameters.Add("@MeetingID", meeting.MeetingID); - parameters.Add("@PCRValue", pcrValue); - this.db.Execute("CCInsertMeetingPCRValues", parameters, commandType: CommandType.StoredProcedure); - } - } - - - return result; - } - - - public IEnumerable GetMeetingAttachments(int meetingID) - { - var parameters = new DynamicParameters(); - parameters.Add("@MeetingID", meetingID); - var data = this.db.Query("CCGetMeetingAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - - /// - /// - /// - /// - internal CCMeetingAttachment InsertMeetingAttachmentAttrib(CCMeetingAttachment attachment) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", value: attachment.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@MeetingID", attachment.MeetingID); - parameters.Add("@Title", attachment.Title); - this.db.Execute("CCInsertMeetingAttachmentAttrib", parameters, commandType: CommandType.StoredProcedure); - attachment.ID = parameters.Get("@ID"); - return attachment; - } - - - /// - /// - /// - /// - internal void UpdateMeetingAttachmentAttrib(CCMeetingAttachment attachment) - { - - var parameters = new DynamicParameters(); - parameters.Add("@ID", attachment.ID); - parameters.Add("@Title", attachment.Title); - - this.db.Execute("CCUpdateMeetingAttachmentAttrib", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - internal void UpdateMeetingAttachmentDocument(CCMeetingAttachment attachment) - { - var parameters = new DynamicParameters(); - - parameters.Add("@AttachmentID", attachment.ID); - parameters.Add("@FileName", attachment.FileName); - parameters.Add("@FileGUID", attachment.FileGUID); - - parameters.Add("@UploadedByID", attachment.UploadedByID); - - this.db.Execute("CCUpdateMeetingAttachmentDocument", parameters, commandType: CommandType.StoredProcedure); - } - - internal void DeleteMeetingAttachemnt(CCMeetingAttachment attachment) - { - - var parameters = new DynamicParameters(); - parameters.Add("@ID", attachment.ID); - - - this.db.Execute("CCDeleteMeetingAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - internal string GetMeetingFileName(string fileGUID) - { - var parameters = new DynamicParameters(); - parameters.Add("@FileGUID", fileGUID); - var fileName = this.db.Query("CCGetMeetingFileName", parameters, commandType: CommandType.StoredProcedure).Single(); - return fileName; - } - - - - internal CCDecisionSummary InsertDecisionSummary(CCDecisionSummary decision) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", value: decision.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@MeetingID", decision.MeetingID); - parameters.Add("@DecisionNotes", decision.DecisionNotes); - this.db.Execute("CCInsertDecisionSummary", parameters, commandType: CommandType.StoredProcedure); - - decision.ID = parameters.Get("@ID"); - return decision; - } - - - /// - /// - /// - /// - internal void UpdateDecisionSummary(CCDecisionSummary decision) - { - - var parameters = new DynamicParameters(); - parameters.Add("@ID", decision.ID); - parameters.Add("@DecisionNotes", decision.DecisionNotes); - - this.db.Execute("CCUpdateDecisionSummary", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - internal void DeleteDecisionSummary(CCDecisionSummary decision) - { - - var parameters = new DynamicParameters(); - parameters.Add("@ID", decision.ID); - - - this.db.Execute("CCDeleteDecisionSummary", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - internal void UpdateDecisionSummaryLinks(int id, string ecnLinks, string ldLinks) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", id); - parameters.Add("@ECNLinks", ecnLinks); - parameters.Add("@LotDispoLinks", ldLinks); - this.db.Execute("CCUpdateDecisionSummaryLinks", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - /// - internal IEnumerable GetDecisionsSummaryList(int meetingID) - { - var parameters = new DynamicParameters(); - parameters.Add("@MeetingID", meetingID); - var data = this.db.Query("CCGetDecisionsSummaryList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - - - /// - /// - /// - /// - /// - internal IEnumerable GetMeetingAttendees(int meetingID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@MeetingID", meetingID); - - - var meetingAttendee = this.db.Query("CCGetMeetingAttendees", parameters, commandType: CommandType.StoredProcedure).ToList(); - - return meetingAttendee; - } - /// - /// - /// - /// - /// - internal IEnumerable GetPCRBAttendees(int PCRBID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@PCRBID", PCRBID); - - - var pcrbAttendee = this.db.Query("CCGetPCRBAttendees", parameters, commandType: CommandType.StoredProcedure).ToList(); - - return pcrbAttendee; - } - /// - /// - /// - /// - internal void InsertMeetingAttendee(CCPCRBAttendee meetingAttendee) - { - var parameters = new DynamicParameters(); - parameters.Add("@MeetingID", meetingAttendee.PCRBID); - parameters.Add("@AttendeeID", meetingAttendee.AttendeeID); - parameters.Add("@JobTitle", meetingAttendee.JobTitle); - parameters.Add("@Location", meetingAttendee.Location); - this.db.Execute("CCInsertMeetingAttendee", parameters, commandType: CommandType.StoredProcedure); - } - internal void InsertNewMeetingAttendee(int meetingId, string attendeeName, string jobTitle, string siteName) - { - var parameters = new DynamicParameters(); - parameters.Add("@meetingId", meetingId); - parameters.Add("@AttendeeName", attendeeName); - parameters.Add("@JobTitle", jobTitle); - parameters.Add("@Site", siteName); - this.db.Execute("CCInsertNewMeetingAttendee", parameters, commandType: CommandType.StoredProcedure); - } - /// - /// / - /// - /// - internal void UpdateMeetingAttendee(int id, string attendeeName, string jobTitle,string siteName) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID",id); - parameters.Add("@AttendeeName", attendeeName); - parameters.Add("@JobTitle", jobTitle); - parameters.Add("@Site", siteName); - this.db.Execute("CCUpdateMeetingAttendee", parameters, commandType: CommandType.StoredProcedure); - } - /// - /// / - /// - /// - internal void UpdatePCRBAttendee(int id, int attendeeID, string jobTitle, string siteName) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", id); - parameters.Add("@AttendeeID", attendeeID); - parameters.Add("@JobTitle", jobTitle); - parameters.Add("@Site", siteName); - this.db.Execute("CCUpdatePCRBAttendee", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - internal void DeleteMeetingAttendee(CCMeetingAttendee meetingAttendee) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", meetingAttendee.ID); - this.db.Execute("CCDeleteMeetingAttendee", parameters, commandType: CommandType.StoredProcedure); - } - - - - internal IEnumerable GetMeetingActionItems(int meetingID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@MeetingID", meetingID); - - var meetingAttendee = this.db.Query("CCGetMeetingActionItems", parameters, commandType: CommandType.StoredProcedure).ToList(); - - return meetingAttendee; - } - internal IEnumerable GetPCRBActionItems(int pcrbID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@PCRBID", pcrbID); - - var actionItem = this.db.Query("CCGetPCRBActionItems", parameters, commandType: CommandType.StoredProcedure).ToList(); - - return actionItem; - } - - - /// - /// - /// - /// - /// - internal IEnumerable GetMeetingActionItems_All(int planNumber) - { - - var parameters = new DynamicParameters(); - parameters.Add("@PlanNumber", planNumber); - var meetingAttendee = this.db.Query("CCGetMeetingActionItems_All", parameters, commandType: CommandType.StoredProcedure).ToList(); - - return meetingAttendee; - } - - - /// - /// - /// - /// - internal void UpdateMeetingActionItem_All(CCMeetingActionItemAll meetingActionItem) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", meetingActionItem.ID); - parameters.Add("@Updates", meetingActionItem.Updates); - parameters.Add("@ClosedStatus", meetingActionItem.ClosedStatus); - parameters.Add("@DueDate", meetingActionItem.DueDate); - parameters.Add("@UserID", meetingActionItem.ClosedBy); - this.db.Execute("CCUpdateMeetingActionItem_All", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// / - /// - /// - internal void InsertMeetingActionItem(CCMeetingActionItem meetingActionItem) - { - var parameters = new DynamicParameters(); - parameters.Add("@MeetingID", meetingActionItem.MeetingID); - parameters.Add("@ActionItemName", meetingActionItem.ActionItemName); - parameters.Add("@ResponsibleID", meetingActionItem.ResponsibleID); - parameters.Add("@Gating", meetingActionItem.Gating); - parameters.Add("@DueDate", meetingActionItem.DueDate); - this.db.Execute("CCInsertMeetingActionItem", parameters, commandType: CommandType.StoredProcedure); - } - internal void InsertPCRBAttendee(CCPCRBAttendee meetingAttendee) - { - - var parameters = new DynamicParameters(); - parameters.Add("@PCRBID", meetingAttendee.PCRBID); - parameters.Add("@AttendeeID", meetingAttendee.AttendeeID); - parameters.Add("@JobTitle", meetingAttendee.JobTitle); - parameters.Add("@Location", meetingAttendee.Location); - this.db.Execute("CCAddPCRBAttendees", parameters, commandType: CommandType.StoredProcedure); - } - internal void InsertPCRBActionItem(CCPCRBActionItem pcrbActionItem) - { - var parameters = new DynamicParameters(); - parameters.Add("@PCRBID", pcrbActionItem.PCRBID); - parameters.Add("@ActionItemName", pcrbActionItem.ActionItemName); - parameters.Add("@ResponsibleID", pcrbActionItem.ResponsibleID); - parameters.Add("@Gating", pcrbActionItem.Gating); - parameters.Add("@DueDate", pcrbActionItem.DueDate); - this.db.Execute("CCInsertPCRBActionItem", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// / - /// - /// - internal void UpdateMeetingActionItem(CCMeetingActionItem meetingActionItem) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", meetingActionItem.ID); - parameters.Add("@ActionItemName", meetingActionItem.ActionItemName); - parameters.Add("@ResponsibleID", meetingActionItem.ResponsibleID); - parameters.Add("@Gating", meetingActionItem.Gating); - parameters.Add("@DueDate", meetingActionItem.DueDate); - this.db.Execute("CCUpdateMeetingActionItem", parameters, commandType: CommandType.StoredProcedure); - } - internal void UpdatePCRBActionItem(CCPCRBActionItem meetingActionItem) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", meetingActionItem.ID); - parameters.Add("@ActionItemName", meetingActionItem.ActionItemName); - parameters.Add("@ResponsibleID", meetingActionItem.ResponsibleID); - parameters.Add("@Gating", meetingActionItem.Gating); - parameters.Add("@DueDate", meetingActionItem.DueDate); - this.db.Execute("CCUpdatePCRBActionItem", parameters, commandType: CommandType.StoredProcedure); - } - - internal void ReassignMeetingActionItemResponsiblePersons(int meetingActionItemId, string newRPIds, string comments, int userId) - { - var parameters = new DynamicParameters(); - parameters.Add("@MeetingActionItemID", meetingActionItemId); - parameters.Add("@ResponsibleID", newRPIds); - parameters.Add("@Comments", comments); - parameters.Add("@UserID", userId); - this.db.Execute("CCUpdateMeetingActionItemRespPersons", parameters, commandType: CommandType.StoredProcedure); - } - - ///// - ///// - ///// - ///// - //internal void UpdateMeetingActionItemAll(CCMeetingActionItemAll meetingActionItem) - //{ - // var parameters = new DynamicParameters(); - // parameters.Add("@ID", meetingActionItem.ID); - // parameters.Add("@Updates", meetingActionItem.Updates); - // parameters.Add("@ClosedStatus", meetingActionItem.ClosedStatus); - // parameters.Add("@UserID", meetingActionItem.ClosedBy); - // this.db.Execute("CCUpdateMeetingActionItem_All", parameters, commandType: CommandType.StoredProcedure); - //} - - /// - /// - /// - /// - internal void DeleteMeetingActionItem(CCMeetingActionItem meetingAttendee) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", meetingAttendee.ID); - this.db.Execute("CCDeleteMeetingActionItem", parameters, commandType: CommandType.StoredProcedure); - } - internal void DeletePCRBActionItem(CCPCRBActionItem pcrbActionItem) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", pcrbActionItem.ID); - this.db.Execute("CCDeletePCRBActionItem", parameters, commandType: CommandType.StoredProcedure); - } - - - public IEnumerable GetMeetingList(int planNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@PlanNumber", planNumber); - - var meetingList = this.db.Query("CCGetMeetingList", parameters, commandType: CommandType.StoredProcedure).ToList(); - - foreach (var meeting in meetingList) - { - CCMeeting meetingToParse = GetMeeting(meeting.MeetingID, out int canViewITAR, 0); - meeting.PCRValueIDs = meetingToParse.PCRValueIDs; - - } - return meetingList; - - } - //public IEnumerable GetMeetingListFull(int planNumber) - //{ - // var parameters = new DynamicParameters(); - // parameters.Add("@PlanNumber", planNumber); - - // var meetingList = this.db.Query("CCGetMeetingList", parameters, commandType: CommandType.StoredProcedure).ToList(); - // return meetingList; - - //} - - /// - /// - /// - /// - internal void CompleteCC(int planNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@PlanNumber", planNumber); - this.db.Execute("CCCompleteCC", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - internal void CancelCC(int planNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@PlanNumber", planNumber); - this.db.Execute("CCCancelCC", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - internal void UpdateActionItemAttachment(CCMeetingActionItemAll attachment) - { - var parameters = new DynamicParameters(); - - parameters.Add("@ID", attachment.ID); - parameters.Add("@FileName", attachment.FileName); - parameters.Add("@FileGUID", attachment.FileGUID); - - parameters.Add("@UploadedByID", attachment.UploadedByID); - - this.db.Execute("CCUpdateActionItemAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - /// - internal string GetActionItemFileName(string fileGUID) - { - var parameters = new DynamicParameters(); - parameters.Add("@FileGUID", fileGUID); - var fileName = this.db.Query("CCGetActionItemFileName", parameters, commandType: CommandType.StoredProcedure).Single(); - return fileName; - } - - /// - /// - /// - /// - internal List GetUsers() - { - var parameters = new DynamicParameters(); - return this.db.Query("CCGetUsers", commandType: CommandType.StoredProcedure).ToList(); - } - - internal List GetActionItemResponsible() - { - var parameters = new DynamicParameters(); - return this.db.Query("CCGetActionItemResponsible", commandType: CommandType.StoredProcedure).ToList(); - } - - internal List GetSites() - { - var parameters = new DynamicParameters(); - return this.db.Query("CCGetSites", commandType: CommandType.StoredProcedure).ToList(); - } - - internal List GetPCRValues() - { - var parameters = new DynamicParameters(); - return this.db.Query("CCGetPCRValues", commandType: CommandType.StoredProcedure).ToList(); - } - - - internal void UpdateMeetingNotes(int meetingID, string notes) - { - var parameters = new DynamicParameters(); - parameters.Add("@ID", meetingID); - parameters.Add("@Notes", notes); - - this.db.Execute("CCUpdateMeetingNotes", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - internal void ReleaseLockOnDocument(int userID, int planNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@PlanNumber", planNumber); - parameters.Add("@UserID", userID); - this.db.Execute("CCReleaseLockOnCCDocuments", parameters, commandType: CommandType.StoredProcedure); - } - - public void ReassignOwner(int planNumber, int newOwnerID, string comments, int userID) - { - var parameters = new DynamicParameters(); - parameters.Add("@PlanNumber", planNumber); - parameters.Add("@NewOwnerID", newOwnerID); - parameters.Add("@Comments", comments); - parameters.Add("@UserID", userID); - - this.db.Execute("CCReassignOwner", parameters, commandType: CommandType.StoredProcedure); - } - + return cc; } -} + + internal ChangeControlViewModel GetChangeControl(int planNumber, out int canViewITAR, int userID) { + canViewITAR = 1; + ChangeControlViewModel ccItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@planNumber", planNumber); + + parameters.Add("@UserID", userID); + //parameters.Add("@UserID", GlobalVars.USER_ID); + parameters.Add("@CanViewITAR", value: canViewITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + //cc = this.db.Query("CCGetChangeControl", parameters, commandType: CommandType.StoredProcedure).SingleOrDefault(); + + using (var multipleResultItems = db.QueryMultiple("CCGetChangeControl", parameters, commandType: CommandType.StoredProcedure)) { + ccItem = multipleResultItems.Read().SingleOrDefault(); + + List gens = multipleResultItems.Read().ToList(); + //if (ccItem != null && gens != null) + //{ + // if (gens.Count > 0) + // ccItem.GenerationIDs.AddRange(gens); + //} + + List logis = multipleResultItems.Read().ToList(); + //if (ccItem != null && logis != null) + //{ + // if (logis.Count > 0) + // ccItem.LogisticsIDs.AddRange(logis); + //} + + List procs = multipleResultItems.Read().ToList(); + //if (ccItem != null && procs != null) + //{ + // if (procs.Count > 0) + // ccItem.ProcessIDs.AddRange(procs); + //} + + //var parts = multipleResultItems.Read().ToList(); + //if (ccItem != null && parts != null) + //{ + // if (parts.Count > 0) + // ccItem.PartNumberIDs.AddRange(parts); + //} + + } + return ccItem; + } + + internal ChangeControlViewModel GetChangeControlRead(int planNumber, out int canViewITAR, int userID) { + canViewITAR = 1; + ChangeControlViewModel ccItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@planNumber", planNumber); + + parameters.Add("@UserID", userID); + //parameters.Add("@UserID", GlobalVars.USER_ID); + parameters.Add("@CanViewITAR", value: canViewITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + //cc = this.db.Query("CCGetChangeControl", parameters, commandType: CommandType.StoredProcedure).SingleOrDefault(); + + using (var multipleResultItems = db.QueryMultiple("CCGetChangeControlRead", parameters, commandType: CommandType.StoredProcedure)) { + ccItem = multipleResultItems.Read().SingleOrDefault(); + + List gens = multipleResultItems.Read().ToList(); + //if (ccItem != null && gens != null) + //{ + // if (gens.Count > 0) + // ccItem.GenerationIDs.AddRange(gens); + //} + + List logis = multipleResultItems.Read().ToList(); + //if (ccItem != null && logis != null) + //{ + // if (logis.Count > 0) + // ccItem.LogisticsIDs.AddRange(logis); + //} + + List procs = multipleResultItems.Read().ToList(); + //if (ccItem != null && procs != null) + //{ + // if (procs.Count > 0) + // ccItem.ProcessIDs.AddRange(procs); + //} + + //var tools = multipleResultItems.Read().ToList(); + //if (ccItem != null && tools != null) + //{ + // if (tools.Count > 0) + // ccItem.ToolTypeIDs.AddRange(tools); + //} + + //var parts = multipleResultItems.Read().ToList(); + //if (ccItem != null && parts != null) + //{ + // if (parts.Count > 0) + // ccItem.PartNumberIDs.AddRange(parts); + //} + + canViewITAR = parameters.Get("@CanViewITAR"); + + } + return ccItem; + } + + internal List GetGenerations() { + DynamicParameters parameters = new(); + return db.Query("CCGetGenerations", commandType: CommandType.StoredProcedure).ToList(); + } + + internal List GetLogistics() { + DynamicParameters parameters = new(); + + return db.Query("CCGetLogistics", commandType: CommandType.StoredProcedure).ToList(); + } + + /// + //internal List GetToolTypes() + //{ + // var parameters = new DynamicParameters(); + // return this.db.Query("CCGetToolTypes", commandType: CommandType.StoredProcedure).ToList(); + //} + + internal List GetProcesses() { + DynamicParameters parameters = new(); + return db.Query("CCGetProcesses", commandType: CommandType.StoredProcedure).ToList(); + } + + internal List GetPartNumbers() { + DynamicParameters parameters = new(); + return db.Query("CCGetPartNumbers", commandType: CommandType.StoredProcedure).ToList(); + } + + internal int UpdateChangeControl(ChangeControlViewModel model, int userID) { + int result = 0; + DynamicParameters parameters = new(); + using (TransactionScope transaction = new()) { + try { + parameters.Add("@PlanNumber", model.PlanNumber); + parameters.Add("@ChangeLevel", model.ChangeLevel); + parameters.Add("@IsITAR", model.IsITAR); + parameters.Add("@IsMedical", model.IsMedical); + parameters.Add("@IsRadHard", model.IsRadHard); + parameters.Add("@Notes", model.Notes); + //parameters.Add("@PartNumbers", model.PartNumbers); + parameters.Add("@IsAutomotive", model.IsAutomotive); + //parameters.Add("@ToolTypes", model.ToolTypes); + parameters.Add("@Title", model.Title); + parameters.Add("@ReasonForChange", model.ReasonForChange); + parameters.Add("@ChangeDescription", model.ChangeDescription); + db.Execute("CCUpdateChangeControl", param: parameters, commandType: CommandType.StoredProcedure); + + //parameters = new DynamicParameters(); + //parameters.Add("@PlanNumber", model.PlanNumber); + //this.db.Execute("CCDeleteGenerations", parameters, commandType: CommandType.StoredProcedure); + //List gens = model.GenerationIDs; + //if (gens != null) + //{ + // foreach (int genId in gens) + // { + // parameters = new DynamicParameters(); + // parameters.Add("@PlanNumber", model.PlanNumber); + // parameters.Add("@GenerationID", genId); + // this.db.Execute("CCInsertGeneration", parameters, commandType: CommandType.StoredProcedure); + // } + //} + + //parameters = new DynamicParameters(); + //parameters.Add("@PlanNumber", model.PlanNumber); + //this.db.Execute("CCDeleteLogistics", parameters, commandType: CommandType.StoredProcedure); + //List logistics = model.LogisticsIDs; + //if (logistics != null) + //{ + // foreach (int logisticsId in logistics) + // { + // parameters = new DynamicParameters(); + // parameters.Add("@PlanNumber", model.PlanNumber); + // parameters.Add("@LogisticsID", logisticsId); + // this.db.Execute("CCInsertLogistics", parameters, commandType: CommandType.StoredProcedure); + // } + //} + + //parameters = new DynamicParameters(); + //parameters.Add("@PlanNumber", model.PlanNumber); + //this.db.Execute("CCDeleteProcesses", parameters, commandType: CommandType.StoredProcedure); + //List processes = model.ProcessIDs; + //if (processes != null) + //{ + // foreach (int processId in processes) + // { + // parameters = new DynamicParameters(); + // parameters.Add("@PlanNumber", model.PlanNumber); + // parameters.Add("@ProcessID", processId); + // this.db.Execute("CCInsertProcess", parameters, commandType: CommandType.StoredProcedure); + // } + //} + + //parameters = new DynamicParameters(); + //parameters.Add("@PlanNumber", model.PlanNumber); + //this.db.Execute("CCDeletePartNumbers", parameters, commandType: CommandType.StoredProcedure); + //if (model.PartNumbers != null) + //{ + // string[] parts = model.PartNumbers.Split(new char[] { ',' }); + // foreach (string part in parts) + // { + // parameters = new DynamicParameters(); + // parameters.Add("@PlanNumber", model.PlanNumber); + // parameters.Add("@PartNumber", part); + // this.db.Execute("CCInsertPartNumber", parameters, commandType: CommandType.StoredProcedure); + // } + //} + transaction.Complete(); + } catch (Exception ex) { + transaction.Dispose(); + throw new Exception(ex.Message + " " + ex.InnerException); + } + } + return result; + } + + public IEnumerable GetMeetingDecisionSummaryList(int planNumber) { + DynamicParameters parameters = new(); + parameters.Add("@PlanNumber", planNumber); + List data = db.Query("CCGetMeetingDecisionSummaryList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetCCAttachment(int planNumber) { + DynamicParameters parameters = new(); + parameters.Add("@PlanNumber", planNumber); + List data = db.Query("CCGetCCAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + internal CCAttachment InsertCCAttachment(CCAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@ID", value: attachment.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@PlanNumber", attachment.PlanNumber); + parameters.Add("@Title", attachment.Title); + parameters.Add("@RequirementsNotes", attachment.RequirementsNotes); + db.Execute("CCInsertCCAttachment", parameters, commandType: CommandType.StoredProcedure); + attachment.ID = parameters.Get("@ID"); + + return attachment; + } + + internal void UpdateCCAttachmentDocument(CCAttachment attachment) { + DynamicParameters parameters = new(); + + parameters.Add("@AttachmentID", attachment.ID); + parameters.Add("@FileName", attachment.FileName); + parameters.Add("@FileGUID", attachment.FileGUID); + + parameters.Add("@UploadedByID", attachment.UploadedByID); + + db.Execute("CCUpdateCCAttachmentDocument", parameters, commandType: CommandType.StoredProcedure); + } + + internal void UpdateCCAttachemnt(CCAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@ID", attachment.ID); + parameters.Add("@Title", attachment.Title); + parameters.Add("@RequirementsNotes", attachment.RequirementsNotes); + db.Execute("CCUpdateCCAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteCCAttachemnt(CCAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@ID", attachment.ID); + + db.Execute("CCDeleteCCAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal string GetCCFileName(string fileGUID) { + DynamicParameters parameters = new(); + parameters.Add("@FileGUID", fileGUID); + var fileName = db.Query("CCGetCCFileName", parameters, commandType: CommandType.StoredProcedure).Single(); + return fileName; + } + + internal int InsertMeeting(int planNumber) { + DynamicParameters parameters = new(); + parameters.Add("@PlanNumber", planNumber); + parameters.Add("@MeetingID", value: 0, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + db.Execute("CCInsertMeeting", parameters, commandType: CommandType.StoredProcedure); + int meetingID = parameters.Get("@MeetingID"); + + return meetingID; + } + + internal CCMeeting GetMeeting(int meetingID, out int canViewITAR, int userID) { + canViewITAR = 1; + CCMeeting ccMeeting = new(); + DynamicParameters parameters = new(); + parameters.Add("@MeetingID", meetingID); + parameters.Add("@UserID", userID); + parameters.Add("@CanViewITAR", value: canViewITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + //ccMeeting = this.db.Query("CCGetMeeting", parameters, commandType: CommandType.StoredProcedure).Single(); + using (var multipleResultItems = db.QueryMultiple("CCGetMeetingRead", parameters, commandType: CommandType.StoredProcedure)) { + ccMeeting = multipleResultItems.Read().SingleOrDefault(); + List pcrvalues = multipleResultItems.Read().ToList(); + if (ccMeeting != null && pcrvalues != null) { + if (pcrvalues.Count > 0) + ccMeeting.PCRValueIDs.AddRange(pcrvalues); + } + } + + return ccMeeting; + } + + internal CCMeeting GetMeetingRead(int meetingID, out int canViewITAR, int userID) { + canViewITAR = 1; + CCMeeting ccMeeting = new(); + DynamicParameters parameters = new(); + parameters.Add("@MeetingID", meetingID); + parameters.Add("@UserID", userID); + parameters.Add("@CanViewITAR", value: canViewITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + //ccMeeting = this.db.Query("CCGetMeetingRead", parameters, commandType: CommandType.StoredProcedure).Single(); + using (var multipleResultItems = db.QueryMultiple("CCGetMeetingRead", parameters, commandType: CommandType.StoredProcedure)) { + ccMeeting = multipleResultItems.Read().SingleOrDefault(); + List pcrvalues = multipleResultItems.Read().ToList(); + if (ccMeeting != null && pcrvalues != null) { + if (pcrvalues.Count > 0) + ccMeeting.PCRValueIDs.AddRange(pcrvalues); + } + } + + return ccMeeting; + } + + internal IEnumerable GetPCRB(int PlanNumber, string PCRB) { + DynamicParameters parameters = new(); + parameters.Add("@PlanNumber", PlanNumber); + parameters.Add("@PCRB", PCRB); + List data = db.Query("CCGetPCRB", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + internal int UpdateMeeting(CCMeeting meeting) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@MeetingID", meeting.MeetingID); + //parameters.Add("@PCRB", meeting.PCRB.ToUpper() == "SELECT" ? null : meeting.PCRB); + parameters.Add("@Decision", meeting.Decision); + parameters.Add("@MeetingDate", meeting.MeetingDate); + parameters.Add("@Notes", meeting.Notes); + + db.Execute("CCUpdateMeeting", parameters, commandType: CommandType.StoredProcedure); + + parameters = new DynamicParameters(); + parameters.Add("@MeetingID", meeting.MeetingID); + db.Execute("CCDeleteMeetingPCRValues", parameters, commandType: CommandType.StoredProcedure); + List pcrValues = meeting.PCRValueIDs; + if (pcrValues != null) { + foreach (string pcrValue in pcrValues) { + parameters = new DynamicParameters(); + parameters.Add("@MeetingID", meeting.MeetingID); + parameters.Add("@PCRValue", pcrValue); + db.Execute("CCInsertMeetingPCRValues", parameters, commandType: CommandType.StoredProcedure); + } + } + + return result; + } + + public IEnumerable GetMeetingAttachments(int meetingID) { + DynamicParameters parameters = new(); + parameters.Add("@MeetingID", meetingID); + List data = db.Query("CCGetMeetingAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + internal CCMeetingAttachment InsertMeetingAttachmentAttrib(CCMeetingAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@ID", value: attachment.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@MeetingID", attachment.MeetingID); + parameters.Add("@Title", attachment.Title); + db.Execute("CCInsertMeetingAttachmentAttrib", parameters, commandType: CommandType.StoredProcedure); + attachment.ID = parameters.Get("@ID"); + return attachment; + } + + internal void UpdateMeetingAttachmentAttrib(CCMeetingAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@ID", attachment.ID); + parameters.Add("@Title", attachment.Title); + + db.Execute("CCUpdateMeetingAttachmentAttrib", parameters, commandType: CommandType.StoredProcedure); + } + + internal void UpdateMeetingAttachmentDocument(CCMeetingAttachment attachment) { + DynamicParameters parameters = new(); + + parameters.Add("@AttachmentID", attachment.ID); + parameters.Add("@FileName", attachment.FileName); + parameters.Add("@FileGUID", attachment.FileGUID); + + parameters.Add("@UploadedByID", attachment.UploadedByID); + + db.Execute("CCUpdateMeetingAttachmentDocument", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteMeetingAttachemnt(CCMeetingAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@ID", attachment.ID); + + db.Execute("CCDeleteMeetingAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal string GetMeetingFileName(string fileGUID) { + DynamicParameters parameters = new(); + parameters.Add("@FileGUID", fileGUID); + var fileName = db.Query("CCGetMeetingFileName", parameters, commandType: CommandType.StoredProcedure).Single(); + return fileName; + } + + internal CCDecisionSummary InsertDecisionSummary(CCDecisionSummary decision) { + DynamicParameters parameters = new(); + parameters.Add("@ID", value: decision.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@MeetingID", decision.MeetingID); + parameters.Add("@DecisionNotes", decision.DecisionNotes); + db.Execute("CCInsertDecisionSummary", parameters, commandType: CommandType.StoredProcedure); + + decision.ID = parameters.Get("@ID"); + return decision; + } + + internal void UpdateDecisionSummary(CCDecisionSummary decision) { + DynamicParameters parameters = new(); + parameters.Add("@ID", decision.ID); + parameters.Add("@DecisionNotes", decision.DecisionNotes); + + db.Execute("CCUpdateDecisionSummary", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteDecisionSummary(CCDecisionSummary decision) { + DynamicParameters parameters = new(); + parameters.Add("@ID", decision.ID); + + db.Execute("CCDeleteDecisionSummary", parameters, commandType: CommandType.StoredProcedure); + } + + internal void UpdateDecisionSummaryLinks(int id, string ecnLinks, string ldLinks) { + DynamicParameters parameters = new(); + parameters.Add("@ID", id); + parameters.Add("@ECNLinks", ecnLinks); + parameters.Add("@LotDispoLinks", ldLinks); + db.Execute("CCUpdateDecisionSummaryLinks", parameters, commandType: CommandType.StoredProcedure); + } + + internal IEnumerable GetDecisionsSummaryList(int meetingID) { + DynamicParameters parameters = new(); + parameters.Add("@MeetingID", meetingID); + List data = db.Query("CCGetDecisionsSummaryList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + internal IEnumerable GetMeetingAttendees(int meetingID) { + DynamicParameters parameters = new(); + parameters.Add("@MeetingID", meetingID); + + List meetingAttendee = db.Query("CCGetMeetingAttendees", parameters, commandType: CommandType.StoredProcedure).ToList(); + + return meetingAttendee; + } + + internal IEnumerable GetPCRBAttendees(int PCRBID) { + DynamicParameters parameters = new(); + parameters.Add("@PCRBID", PCRBID); + + List pcrbAttendee = db.Query("CCGetPCRBAttendees", parameters, commandType: CommandType.StoredProcedure).ToList(); + + return pcrbAttendee; + } + + internal void InsertMeetingAttendee(CCPCRBAttendee meetingAttendee) { + DynamicParameters parameters = new(); + parameters.Add("@MeetingID", meetingAttendee.PCRBID); + parameters.Add("@AttendeeID", meetingAttendee.AttendeeID); + parameters.Add("@JobTitle", meetingAttendee.JobTitle); + parameters.Add("@Location", meetingAttendee.Location); + db.Execute("CCInsertMeetingAttendee", parameters, commandType: CommandType.StoredProcedure); + } + + internal void InsertNewMeetingAttendee(int meetingId, string attendeeName, string jobTitle, string siteName) { + DynamicParameters parameters = new(); + parameters.Add("@meetingId", meetingId); + parameters.Add("@AttendeeName", attendeeName); + parameters.Add("@JobTitle", jobTitle); + parameters.Add("@Site", siteName); + db.Execute("CCInsertNewMeetingAttendee", parameters, commandType: CommandType.StoredProcedure); + } + /// + /// / + /// + + internal void UpdateMeetingAttendee(int id, string attendeeName, string jobTitle, string siteName) { + DynamicParameters parameters = new(); + parameters.Add("@ID", id); + parameters.Add("@AttendeeName", attendeeName); + parameters.Add("@JobTitle", jobTitle); + parameters.Add("@Site", siteName); + db.Execute("CCUpdateMeetingAttendee", parameters, commandType: CommandType.StoredProcedure); + } + /// + /// / + /// + + internal void UpdatePCRBAttendee(int id, int attendeeID, string jobTitle, string siteName) { + DynamicParameters parameters = new(); + parameters.Add("@ID", id); + parameters.Add("@AttendeeID", attendeeID); + parameters.Add("@JobTitle", jobTitle); + parameters.Add("@Site", siteName); + db.Execute("CCUpdatePCRBAttendee", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteMeetingAttendee(CCMeetingAttendee meetingAttendee) { + DynamicParameters parameters = new(); + parameters.Add("@ID", meetingAttendee.ID); + db.Execute("CCDeleteMeetingAttendee", parameters, commandType: CommandType.StoredProcedure); + } + + internal IEnumerable GetMeetingActionItems(int meetingID) { + DynamicParameters parameters = new(); + parameters.Add("@MeetingID", meetingID); + + List meetingAttendee = db.Query("CCGetMeetingActionItems", parameters, commandType: CommandType.StoredProcedure).ToList(); + + return meetingAttendee; + } + + internal IEnumerable GetPCRBActionItems(int pcrbID) { + DynamicParameters parameters = new(); + parameters.Add("@PCRBID", pcrbID); + + List actionItem = db.Query("CCGetPCRBActionItems", parameters, commandType: CommandType.StoredProcedure).ToList(); + + return actionItem; + } + + internal IEnumerable GetMeetingActionItems_All(int planNumber) { + DynamicParameters parameters = new(); + parameters.Add("@PlanNumber", planNumber); + List meetingAttendee = db.Query("CCGetMeetingActionItems_All", parameters, commandType: CommandType.StoredProcedure).ToList(); + + return meetingAttendee; + } + + internal void UpdateMeetingActionItem_All(CCMeetingActionItemAll meetingActionItem) { + DynamicParameters parameters = new(); + parameters.Add("@ID", meetingActionItem.ID); + parameters.Add("@Updates", meetingActionItem.Updates); + parameters.Add("@ClosedStatus", meetingActionItem.ClosedStatus); + parameters.Add("@DueDate", meetingActionItem.DueDate); + parameters.Add("@UserID", meetingActionItem.ClosedBy); + db.Execute("CCUpdateMeetingActionItem_All", parameters, commandType: CommandType.StoredProcedure); + } + + /// + /// / + /// + + internal void InsertMeetingActionItem(CCMeetingActionItem meetingActionItem) { + DynamicParameters parameters = new(); + parameters.Add("@MeetingID", meetingActionItem.MeetingID); + parameters.Add("@ActionItemName", meetingActionItem.ActionItemName); + parameters.Add("@ResponsibleID", meetingActionItem.ResponsibleID); + parameters.Add("@Gating", meetingActionItem.Gating); + parameters.Add("@DueDate", meetingActionItem.DueDate); + db.Execute("CCInsertMeetingActionItem", parameters, commandType: CommandType.StoredProcedure); + } + + internal void InsertPCRBAttendee(CCPCRBAttendee meetingAttendee) { + DynamicParameters parameters = new(); + parameters.Add("@PCRBID", meetingAttendee.PCRBID); + parameters.Add("@AttendeeID", meetingAttendee.AttendeeID); + parameters.Add("@JobTitle", meetingAttendee.JobTitle); + parameters.Add("@Location", meetingAttendee.Location); + db.Execute("CCAddPCRBAttendees", parameters, commandType: CommandType.StoredProcedure); + } + + internal void InsertPCRBActionItem(CCPCRBActionItem pcrbActionItem) { + DynamicParameters parameters = new(); + parameters.Add("@PCRBID", pcrbActionItem.PCRBID); + parameters.Add("@ActionItemName", pcrbActionItem.ActionItemName); + parameters.Add("@ResponsibleID", pcrbActionItem.ResponsibleID); + parameters.Add("@Gating", pcrbActionItem.Gating); + parameters.Add("@DueDate", pcrbActionItem.DueDate); + db.Execute("CCInsertPCRBActionItem", parameters, commandType: CommandType.StoredProcedure); + } + + /// + /// / + /// + + internal void UpdateMeetingActionItem(CCMeetingActionItem meetingActionItem) { + DynamicParameters parameters = new(); + parameters.Add("@ID", meetingActionItem.ID); + parameters.Add("@ActionItemName", meetingActionItem.ActionItemName); + parameters.Add("@ResponsibleID", meetingActionItem.ResponsibleID); + parameters.Add("@Gating", meetingActionItem.Gating); + parameters.Add("@DueDate", meetingActionItem.DueDate); + db.Execute("CCUpdateMeetingActionItem", parameters, commandType: CommandType.StoredProcedure); + } + + internal void UpdatePCRBActionItem(CCPCRBActionItem meetingActionItem) { + DynamicParameters parameters = new(); + parameters.Add("@ID", meetingActionItem.ID); + parameters.Add("@ActionItemName", meetingActionItem.ActionItemName); + parameters.Add("@ResponsibleID", meetingActionItem.ResponsibleID); + parameters.Add("@Gating", meetingActionItem.Gating); + parameters.Add("@DueDate", meetingActionItem.DueDate); + db.Execute("CCUpdatePCRBActionItem", parameters, commandType: CommandType.StoredProcedure); + } + + internal void ReassignMeetingActionItemResponsiblePersons(int meetingActionItemId, string newRPIds, string comments, int userId) { + DynamicParameters parameters = new(); + parameters.Add("@MeetingActionItemID", meetingActionItemId); + parameters.Add("@ResponsibleID", newRPIds); + parameters.Add("@Comments", comments); + parameters.Add("@UserID", userId); + db.Execute("CCUpdateMeetingActionItemRespPersons", parameters, commandType: CommandType.StoredProcedure); + } + + ///// + ///// + ///// + // + //internal void UpdateMeetingActionItemAll(CCMeetingActionItemAll meetingActionItem) + //{ + // var parameters = new DynamicParameters(); + // parameters.Add("@ID", meetingActionItem.ID); + // parameters.Add("@Updates", meetingActionItem.Updates); + // parameters.Add("@ClosedStatus", meetingActionItem.ClosedStatus); + // parameters.Add("@UserID", meetingActionItem.ClosedBy); + // this.db.Execute("CCUpdateMeetingActionItem_All", parameters, commandType: CommandType.StoredProcedure); + //} + + internal void DeleteMeetingActionItem(CCMeetingActionItem meetingAttendee) { + DynamicParameters parameters = new(); + parameters.Add("@ID", meetingAttendee.ID); + db.Execute("CCDeleteMeetingActionItem", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeletePCRBActionItem(CCPCRBActionItem pcrbActionItem) { + DynamicParameters parameters = new(); + parameters.Add("@ID", pcrbActionItem.ID); + db.Execute("CCDeletePCRBActionItem", parameters, commandType: CommandType.StoredProcedure); + } + + public IEnumerable GetMeetingList(int planNumber) { + DynamicParameters parameters = new(); + parameters.Add("@PlanNumber", planNumber); + + List meetingList = db.Query("CCGetMeetingList", parameters, commandType: CommandType.StoredProcedure).ToList(); + + foreach (var meeting in meetingList) { + CCMeeting meetingToParse = GetMeeting(meeting.MeetingID, out int canViewITAR, 0); + meeting.PCRValueIDs = meetingToParse.PCRValueIDs; + + } + return meetingList; + } + + internal void CompleteCC(int planNumber) { + DynamicParameters parameters = new(); + parameters.Add("@PlanNumber", planNumber); + db.Execute("CCCompleteCC", parameters, commandType: CommandType.StoredProcedure); + } + + internal void CancelCC(int planNumber) { + DynamicParameters parameters = new(); + parameters.Add("@PlanNumber", planNumber); + db.Execute("CCCancelCC", parameters, commandType: CommandType.StoredProcedure); + } + + internal void UpdateActionItemAttachment(CCMeetingActionItemAll attachment) { + DynamicParameters parameters = new(); + + parameters.Add("@ID", attachment.ID); + parameters.Add("@FileName", attachment.FileName); + parameters.Add("@FileGUID", attachment.FileGUID); + + parameters.Add("@UploadedByID", attachment.UploadedByID); + + db.Execute("CCUpdateActionItemAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal string GetActionItemFileName(string fileGUID) { + DynamicParameters parameters = new(); + parameters.Add("@FileGUID", fileGUID); + var fileName = db.Query("CCGetActionItemFileName", parameters, commandType: CommandType.StoredProcedure).Single(); + return fileName; + } + + /// + /// + /// + internal List GetUsers() { + DynamicParameters parameters = new(); + return db.Query("CCGetUsers", commandType: CommandType.StoredProcedure).ToList(); + } + + internal List GetActionItemResponsible() { + DynamicParameters parameters = new(); + return db.Query("CCGetActionItemResponsible", commandType: CommandType.StoredProcedure).ToList(); + } + + internal List GetSites() { + DynamicParameters parameters = new(); + return db.Query("CCGetSites", commandType: CommandType.StoredProcedure).ToList(); + } + + internal List GetPCRValues() { + DynamicParameters parameters = new(); + return db.Query("CCGetPCRValues", commandType: CommandType.StoredProcedure).ToList(); + } + + internal void UpdateMeetingNotes(int meetingID, string notes) { + DynamicParameters parameters = new(); + parameters.Add("@ID", meetingID); + parameters.Add("@Notes", notes); + + db.Execute("CCUpdateMeetingNotes", parameters, commandType: CommandType.StoredProcedure); + } + + internal void ReleaseLockOnDocument(int userID, int planNumber) { + DynamicParameters parameters = new(); + parameters.Add("@PlanNumber", planNumber); + parameters.Add("@UserID", userID); + db.Execute("CCReleaseLockOnCCDocuments", parameters, commandType: CommandType.StoredProcedure); + } + + public void ReassignOwner(int planNumber, int newOwnerID, string comments, int userID) { + DynamicParameters parameters = new(); + parameters.Add("@PlanNumber", planNumber); + parameters.Add("@NewOwnerID", newOwnerID); + parameters.Add("@Comments", comments); + parameters.Add("@UserID", userID); + + db.Execute("CCReassignOwner", parameters, commandType: CommandType.StoredProcedure); + } + + public void AttachSaveCC(int planNumber, int attachID, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var ccPhysicalPath = _AppSettings.AttachmentFolder + @"ChangeControl\" + planNumber; + di = new DirectoryInfo(ccPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"ChangeControl\" + planNumber + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + CCAttachment attach = new() { + ID = attachID, + FileGUID = guid, + FileName = fileName, + UploadedByID = userId + // Title = title, + // RequirementsNotes = requirementsNotes + }; + + // InsertCCAttachment(attach); + UpdateCCAttachmentDocument(attach); + } + + public void AttachSaveMeeting(int planNumber, int attachID, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var ccPhysicalPath = _AppSettings.AttachmentFolder + @"ChangeControl\" + planNumber; + di = new DirectoryInfo(ccPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"ChangeControl\" + planNumber + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + CCMeetingAttachment attach = new() { + ID = attachID, + FileGUID = guid, + FileName = fileName, + UploadedByID = userId + }; + + // InsertCCAttachment(attach); + UpdateMeetingAttachmentDocument(attach); + } + + public void AttachSaveActionItem(int planNumber, int attachID, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var ccPhysicalPath = _AppSettings.AttachmentFolder + @"ChangeControl\" + planNumber; + di = new DirectoryInfo(ccPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"ChangeControl\" + planNumber + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + CCMeetingActionItemAll attach = new() { + ID = attachID, + FileGUID = guid, + FileName = fileName, + UploadedByID = userId + + }; + + // InsertCCAttachment(attach); + UpdateActionItemAttachment(attach); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/CorrectiveActionDMO.cs b/Fab2ApprovalSystem/DMO/CorrectiveActionDMO.cs index 3484780..8363b04 100644 --- a/Fab2ApprovalSystem/DMO/CorrectiveActionDMO.cs +++ b/Fab2ApprovalSystem/DMO/CorrectiveActionDMO.cs @@ -1,896 +1,773 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.IO; +using System.Linq; +using System.Transactions; + using Dapper; + using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.ViewModels; -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Data.SqlClient; -using System.Linq; -using System.Text; -using System.Transactions; -using System.Web; -using System.Web.Mvc; -namespace Fab2ApprovalSystem.DMO -{ - - public class CorrectiveActionDMO - { - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - WorkflowDMO wfDMO = new WorkflowDMO(); +namespace Fab2ApprovalSystem.DMO; - public CorrectiveAction InsertCA(CorrectiveAction ca) - { - var parameters = new DynamicParameters(); +public class CorrectiveActionDMO { - parameters = new DynamicParameters(); - parameters.Add("@CANo", value: ca.CANo, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@RequestorID", ca.RequestorID); + private readonly AppSettings _AppSettings; + private readonly WorkflowDMO wfDMO = new(); + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - this.db.Execute("_8DInsertCAItem", parameters, commandType: CommandType.StoredProcedure); - ca.CANo = parameters.Get("@CANo"); + public CorrectiveActionDMO(AppSettings appSettings) => + _AppSettings = appSettings; - return ca; - } + public CorrectiveAction InsertCA(CorrectiveAction ca) { + DynamicParameters parameters = new(); - /// - /// - /// - /// - public void UpdateCorrectiveAction(CorrectiveAction model) - { - var parameters = new DynamicParameters(); - - using (var transaction = new TransactionScope()) - { - try - { - parameters.Add("@CANo", model.CANo); - parameters.Add("@CATitle", model.CATitle); - parameters.Add("@RequestorID", model.RequestorID); - parameters.Add("@IssueDate", model.IssueDate); - parameters.Add("@D1AssigneeID", model.D1AssigneeID); - parameters.Add("@CAType", model.CAType); - parameters.Add("@CASourceID", model.CASourceID); - parameters.Add("@ModuleID", model.ModuleID); - parameters.Add("@QAID", model.QAID); - parameters.Add("@D8DueDate", model.D8DueDate); - parameters.Add("@Tool", model.Tools); - parameters.Add("@ApprovedDate", model.ApprovedDate); - parameters.Add("@RelatedMRB", model.RelatedMRB); - parameters.Add("@RelatedAudit", model.RelatedAudit); - parameters.Add("@D0Comments", model.D0Comments); - parameters.Add("@D2ProblemDescription", model.D2ProblemDescription); - parameters.Add("@D3RiskAssessmentNotes", model.D3RiskAssessmentNotes); - parameters.Add("@D0Completed", model.D0Completed); - parameters.Add("@D0Approved", model.D0Approved); - parameters.Add("@D3Completed", model.D3Completed); - parameters.Add("@D3Approved", model.D3Approved); - parameters.Add("@D4RootCause1", model.D4RootCause1); - parameters.Add("@D4RootCause2", model.D4RootCause2); - parameters.Add("@D4RootCause3", model.D4RootCause3); - parameters.Add("@D4RootCause4", model.D4RootCause4); - parameters.Add("@D4Completed", model.D4Completed); - parameters.Add("@D4Approved", model.D4Approved); - parameters.Add("@D5Completed", model.D5Completed); - parameters.Add("@D5Approved", model.D5Approved); - parameters.Add("@D6Validated", model.D6Validated); - parameters.Add("@D7Completed", model.D7Completed); - parameters.Add("@D8Completed", model.D8Completed); - parameters.Add("@D8Approved", model.D8Approved); - parameters.Add("@D8TeamRecognition", model.D8TeamRecognition); - parameters.Add("@D8LessonsLearned", model.D8LessonsLearned); - parameters.Add("@TeamCaptainID", model.TeamCaptainID); - parameters.Add("@CASponsorID", model.CASponsorID); - parameters.Add("@CustomerName", model.CustomerName); - parameters.Add("@CustomerPartNo", model.CustomerPartNo); - parameters.Add("@IFXPartNo", model.IFXPartNo); - parameters.Add("@PartQty", model.PartQty); - parameters.Add("@InvoiceNo", model.InvoiceNo); - parameters.Add("@PurchaseOrderNo", model.PurchaseOrderNo); - parameters.Add("@SalesOrderNo", model.SalesOrderNo); - parameters.Add("@DollarImpact", model.DollarImpact); - parameters.Add("@BackgroundInfo", model.BackgroundInfo); - parameters.Add("@Analysis", model.Analysis); - parameters.Add("@VisualVerification", model.VisualVerification); - parameters.Add("@InterimContainmentAction", model.InterimContainmentAction); - parameters.Add("@ICAVerificationResults", model.ICAVerificationResults); - parameters.Add("@ICAValidationActivities", model.ICAValidationActivities); - parameters.Add("@RootCauseVerification", model.RootCauseVerification); - parameters.Add("@EscapePoint", model.EscapePoint); - parameters.Add("@FollowUpDate", model.FollowUpDate); - parameters.Add("@CASubmitted", model.CASubmitted); - - this.db.Execute("_8DUpdateCorrectiveAction", parameters, commandType: CommandType.StoredProcedure); - EventLogDMO.Add(new WinEventLog { UserID = "System", Comments = "Saved Corrective Action", DocumentType = "9", IssueID = model.CANo, OperationType = "Status", SysDocumentID = 1 }); + parameters = new DynamicParameters(); + parameters.Add("@CANo", value: ca.CANo, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@RequestorID", ca.RequestorID); + db.Execute("_8DInsertCAItem", parameters, commandType: CommandType.StoredProcedure); + ca.CANo = parameters.Get("@CANo"); + return ca; + } - + public void UpdateCorrectiveAction(CorrectiveAction model) { + DynamicParameters parameters = new(); + using (TransactionScope transaction = new()) { + try { + parameters.Add("@CANo", model.CANo); + parameters.Add("@CATitle", model.CATitle); + parameters.Add("@RequestorID", model.RequestorID); + parameters.Add("@IssueDate", model.IssueDate); + parameters.Add("@D1AssigneeID", model.D1AssigneeID); + parameters.Add("@CAType", model.CAType); + parameters.Add("@CASourceID", model.CASourceID); + parameters.Add("@ModuleID", model.ModuleID); + parameters.Add("@QAID", model.QAID); + parameters.Add("@D8DueDate", model.D8DueDate); + parameters.Add("@Tool", model.Tools); + parameters.Add("@ApprovedDate", model.ApprovedDate); + parameters.Add("@RelatedMRB", model.RelatedMRB); + parameters.Add("@RelatedAudit", model.RelatedAudit); + parameters.Add("@D0Comments", model.D0Comments); + parameters.Add("@D2ProblemDescription", model.D2ProblemDescription); + parameters.Add("@D3RiskAssessmentNotes", model.D3RiskAssessmentNotes); + parameters.Add("@D0Completed", model.D0Completed); + parameters.Add("@D0Approved", model.D0Approved); + parameters.Add("@D3Completed", model.D3Completed); + parameters.Add("@D3Approved", model.D3Approved); + parameters.Add("@D4RootCause1", model.D4RootCause1); + parameters.Add("@D4RootCause2", model.D4RootCause2); + parameters.Add("@D4RootCause3", model.D4RootCause3); + parameters.Add("@D4RootCause4", model.D4RootCause4); + parameters.Add("@D4Completed", model.D4Completed); + parameters.Add("@D4Approved", model.D4Approved); + parameters.Add("@D5Completed", model.D5Completed); + parameters.Add("@D5Approved", model.D5Approved); + parameters.Add("@D6Validated", model.D6Validated); + parameters.Add("@D7Completed", model.D7Completed); + parameters.Add("@D8Completed", model.D8Completed); + parameters.Add("@D8Approved", model.D8Approved); + parameters.Add("@D8TeamRecognition", model.D8TeamRecognition); + parameters.Add("@D8LessonsLearned", model.D8LessonsLearned); + parameters.Add("@TeamCaptainID", model.TeamCaptainID); + parameters.Add("@CASponsorID", model.CASponsorID); + parameters.Add("@CustomerName", model.CustomerName); + parameters.Add("@CustomerPartNo", model.CustomerPartNo); + parameters.Add("@IFXPartNo", model.IFXPartNo); + parameters.Add("@PartQty", model.PartQty); + parameters.Add("@InvoiceNo", model.InvoiceNo); + parameters.Add("@PurchaseOrderNo", model.PurchaseOrderNo); + parameters.Add("@SalesOrderNo", model.SalesOrderNo); + parameters.Add("@DollarImpact", model.DollarImpact); + parameters.Add("@BackgroundInfo", model.BackgroundInfo); + parameters.Add("@Analysis", model.Analysis); + parameters.Add("@VisualVerification", model.VisualVerification); + parameters.Add("@InterimContainmentAction", model.InterimContainmentAction); + parameters.Add("@ICAVerificationResults", model.ICAVerificationResults); + parameters.Add("@ICAValidationActivities", model.ICAValidationActivities); + parameters.Add("@RootCauseVerification", model.RootCauseVerification); + parameters.Add("@EscapePoint", model.EscapePoint); + parameters.Add("@FollowUpDate", model.FollowUpDate); + parameters.Add("@CASubmitted", model.CASubmitted); + + db.Execute("_8DUpdateCorrectiveAction", parameters, commandType: CommandType.StoredProcedure); + EventLogDMO.Add(new WinEventLog { UserID = "System", Comments = "Saved Corrective Action", DocumentType = "9", IssueID = model.CANo, OperationType = "Status", SysDocumentID = 1 }); + + parameters = new DynamicParameters(); + parameters.Add("@CANo", model.CANo); + db.Execute("_8DDeleteCAModuleID", parameters, commandType: CommandType.StoredProcedure); + List moduleIDs = model.ModuleIDs; + if (moduleIDs != null) { + foreach (int moduleID in moduleIDs) { parameters = new DynamicParameters(); parameters.Add("@CANo", model.CANo); - this.db.Execute("_8DDeleteCAModuleID", parameters, commandType: CommandType.StoredProcedure); - List moduleIDs = model.ModuleIDs; - if (moduleIDs != null) - { - foreach (int moduleID in moduleIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@CANo", model.CANo); - parameters.Add("@ModuleID", moduleID); - this.db.Execute("_8DInsertCAModuleID", parameters, commandType: CommandType.StoredProcedure); - } - } - - parameters = new DynamicParameters(); - parameters.Add("@CANo", model.CANo); - this.db.Execute("_8DDeleteRiskAssessmentAres", parameters, commandType: CommandType.StoredProcedure); - List riskAssessmentAreaIDs = model.RiskAssessmentAreaIDs; - if (riskAssessmentAreaIDs != null) - { - foreach (int riskAssessmentAreaID in riskAssessmentAreaIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@CANo", model.CANo); - parameters.Add("@RiskAssessmentAreaID", riskAssessmentAreaID); - this.db.Execute("_8DInsertRiskAssessmentArea", parameters, commandType: CommandType.StoredProcedure); - } - } - - - parameters = new DynamicParameters(); - parameters.Add("@CANo", model.CANo); - this.db.Execute("_8DDeleteTeamMembers", parameters, commandType: CommandType.StoredProcedure); - List teamMemberIDs = model.TeamMemberIDs; - if (teamMemberIDs != null) - { - foreach (int teamMemberID in teamMemberIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@CANo", model.CANo); - parameters.Add("@TeamMemberID", teamMemberID); - this.db.Execute("_8DInsertTeamMemberID", parameters, commandType: CommandType.StoredProcedure); - } - } - - transaction.Complete(); - } - catch(Exception ex) - { - transaction.Dispose(); - throw new Exception(ex.Message + " " + ex.InnerException); + parameters.Add("@ModuleID", moduleID); + db.Execute("_8DInsertCAModuleID", parameters, commandType: CommandType.StoredProcedure); } } - - - - - - } - - /// - /// - /// - /// - /// - /// - public CorrectiveAction GetCAItem(int caNo, int userID) - { - CorrectiveAction ca = new CorrectiveAction(); - - //isITAR = 2; - - var parameters = new DynamicParameters(); - parameters.Add("@CANo", value: caNo); - parameters.Add("@UserID", userID); - - using (var multipleResultItems = this.db.QueryMultiple("_8DGetCAItem", parameters, commandType: CommandType.StoredProcedure)) - { - ca = multipleResultItems.Read().SingleOrDefault(); - - - var moduleIDs = multipleResultItems.Read().ToList(); - if (ca != null && moduleIDs != null) - { - if (moduleIDs.Count > 0) - ca.ModuleIDs.AddRange(moduleIDs); + parameters = new DynamicParameters(); + parameters.Add("@CANo", model.CANo); + db.Execute("_8DDeleteRiskAssessmentAres", parameters, commandType: CommandType.StoredProcedure); + List riskAssessmentAreaIDs = model.RiskAssessmentAreaIDs; + if (riskAssessmentAreaIDs != null) { + foreach (int riskAssessmentAreaID in riskAssessmentAreaIDs) { + parameters = new DynamicParameters(); + parameters.Add("@CANo", model.CANo); + parameters.Add("@RiskAssessmentAreaID", riskAssessmentAreaID); + db.Execute("_8DInsertRiskAssessmentArea", parameters, commandType: CommandType.StoredProcedure); + } } - var teamMembers = multipleResultItems.Read().ToList(); - if (ca != null && teamMembers != null) - { - if (teamMembers.Count > 0) - ca.TeamMemberIDs.AddRange(teamMembers); + parameters = new DynamicParameters(); + parameters.Add("@CANo", model.CANo); + db.Execute("_8DDeleteTeamMembers", parameters, commandType: CommandType.StoredProcedure); + List teamMemberIDs = model.TeamMemberIDs; + if (teamMemberIDs != null) { + foreach (int teamMemberID in teamMemberIDs) { + parameters = new DynamicParameters(); + parameters.Add("@CANo", model.CANo); + parameters.Add("@TeamMemberID", teamMemberID); + db.Execute("_8DInsertTeamMemberID", parameters, commandType: CommandType.StoredProcedure); + } } - var riskAssessments = multipleResultItems.Read().ToList(); - if (ca != null && riskAssessments != null) - { - if (riskAssessments.Count > 0) - ca.RiskAssessmentAreaIDs.AddRange(riskAssessments); - } + transaction.Complete(); + } catch (Exception ex) { + transaction.Dispose(); + throw new Exception(ex.Message + " " + ex.InnerException); } - - return ca; - } - - /// - /// - /// - /// - /// - /// - public CorrectiveAction GetCAItemReadOnly(int caNo, int userID) - { - CorrectiveAction ca = new CorrectiveAction(); - - //isITAR = 2; - - var parameters = new DynamicParameters(); - parameters.Add("@CANo", value: caNo); - parameters.Add("@UserID", userID); - - using (var multipleResultItems = this.db.QueryMultiple("_8DGetCAItemReadOnly", parameters, commandType: CommandType.StoredProcedure)) - { - ca = multipleResultItems.Read().SingleOrDefault(); - - var moduleIDs = multipleResultItems.Read().ToList(); - if (ca != null && moduleIDs != null) - { - if (moduleIDs.Count > 0) - ca.ModuleIDs.AddRange(moduleIDs); - } - - var teamMembers = multipleResultItems.Read().ToList(); - if (ca != null && teamMembers != null) - { - if (teamMembers.Count > 0) - ca.TeamMemberIDs.AddRange(teamMembers); - } - - var riskAssessments = multipleResultItems.Read().ToList(); - if (ca != null && riskAssessments != null) - { - if (riskAssessments.Count > 0) - ca.RiskAssessmentAreaIDs.AddRange(riskAssessments); - } - - - } - - return ca; - } - - /// - /// - /// - /// - public IEnumerable GetUserList() - { - var parameters = new DynamicParameters(); - var userList = this.db.Query("_8DGetUserList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return userList; - } - public IEnumerable GetAllUserList() - { - var parameters = new DynamicParameters(); - var userList = this.db.Query("_8DGetAllUserList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return userList; - } - public IEnumerable GetCASourceList() - { - var parameters = new DynamicParameters(); - var caSourceList = this.db.Query("_8DGetCASourceList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return caSourceList; - } - - public IEnumerable GetModuleList() - { - var parameters = new DynamicParameters(); - var moduleList = this.db.Query("_8DGetCAModuleList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return moduleList; - } - - - /// - /// - /// - /// - public void InsertCAAttachment(CA_Attachment attach) - { - var parameters = new DynamicParameters(); - parameters.Add("@CANo", attach.CANo); - parameters.Add("@D5D6CAID", attach.D5D6CAID); - parameters.Add("@D7PAID", attach.D7PAID); - parameters.Add("@CAFindingsID", attach.CAFindingsID); - parameters.Add("@UploadedByID", attach.UploadedByID); - parameters.Add("@FileName", attach.FileName); - parameters.Add("@FileGUID", attach.FileGUID); - parameters.Add("@Section", attach.Section); - - this.db.Execute("_8DInsertCAAttachment", parameters, commandType: CommandType.StoredProcedure); - - - } - - - /// - /// - /// - /// - /// - public IEnumerable GetCAAttachmentsList(int caNo, string section) - { - var parameters = new DynamicParameters(); - parameters.Add("@CANo", caNo); - parameters.Add("@Section", section); - var caAttachmentList = this.db.Query("[_8DGetCAAttachmentList]", parameters, commandType: CommandType.StoredProcedure).ToList(); - return caAttachmentList; - - } - - /// - /// - /// - /// - public void DeleteCAAttachment(int attachmentID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@AttachmentID", attachmentID); - this.db.Execute("_8DDeleteCAAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - public string GetCAAttachmentFileName(string fileGUID) - { - var parameters = new DynamicParameters(); - parameters.Add("@FileGUID", fileGUID); - var fileName = this.db.Query("_8DGetCAAttachmentFileName", parameters, commandType: CommandType.StoredProcedure).Single(); - return fileName; - } - - - /// - /// - /// - /// - /// - public IEnumerable GetD3ContainmentActions(int caNo) - { - - var parameters = new DynamicParameters(); - parameters.Add("@CANo", caNo); - var d3ContainmentActionList = this.db.Query("_8DGetD3ContainmentActions", parameters, commandType: CommandType.StoredProcedure).ToList(); - return d3ContainmentActionList; - - } - - /// - /// - /// - /// - public void UpdateD3ContainmentAction(D3ContainmentAction model) - { - - var parameters = new DynamicParameters(); - parameters.Add("@ID", model.ID); - parameters.Add("@ContainmentAction", model.ContainmentAction); - parameters.Add("@Result", model.Result); - parameters.Add("@ECNLinks", model.ECNLinks); - parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); - parameters.Add("@ECD", model.ECD); - parameters.Add("@ImplementedDate", model.ImplementedDate); - - this.db.Execute("_8DUpdateD3ContainmentAction", parameters, commandType: CommandType.StoredProcedure); - - } - - public void InsertD3ContainmentAction(D3ContainmentAction model) - { - - var parameters = new DynamicParameters(); - parameters.Add("@CANo", model.CANo); - parameters.Add("@ContainmentAction", model.ContainmentAction); - parameters.Add("@Result", model.Result); - parameters.Add("@ECNLinks", model.ECNLinks); - parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); - parameters.Add("@ECD", model.ECD); - parameters.Add("@ImplementedDate", model.ImplementedDate); - - this.db.Execute("_8DInsertD3ContainmentAction", parameters, commandType: CommandType.StoredProcedure); - - } - - - public void DeleteD3ContainmentActionItem(int d3ContainmentActionID) - { - var parameters = new DynamicParameters(); - parameters.Add("@D3ContainmentActionID", d3ContainmentActionID); - - this.db.Execute("_8DDeleteD3ContainmentActionItem", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - public IEnumerable GetD3RiskAssessmentAreas() - { - var parameters = new DynamicParameters(); - var dataList = this.db.Query("_8DGetD3RiskAssessmentAreas", parameters, commandType: CommandType.StoredProcedure).ToList(); - return dataList; - } - - /// - /// - /// - /// - /// - public IEnumerable GetD5D6CorrectivetActions(int caNo) - { - - var parameters = new DynamicParameters(); - parameters.Add("@CANo", caNo); - var dataList = this.db.Query("_8DGetD5D6_CAList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return dataList; - - } - public bool IsAIAssignee(int userId, int caId) - { - bool isAssignee = false; - int aiIndex = 0; - List actionItems = GetD5D6CorrectivetActions(caId).ToList(); - while (isAssignee == false && aiIndex < actionItems.Count()) - { - D5D6CorrectivetAction actionItem = actionItems[aiIndex]; - if(actionItem.ResponsibilityOwnerID == userId && actionItem.ImplementedDate == null && actionItem.Approved) - { - isAssignee = true; - } - aiIndex++; - } - return isAssignee; - - } - public IEnumerable GetD5D6Improvement() - { - var parameters = new DynamicParameters(); - var dataList = this.db.Query("_8DGetD5D6Improvement", parameters, commandType: CommandType.StoredProcedure).ToList(); - return dataList; - } - - /// - /// - /// - /// - public void InsertD5D6CorrectivetAction(D5D6CorrectivetAction model) - { - - var parameters = new DynamicParameters(); - parameters.Add("@CANo", model.CANo); - parameters.Add("@CorrectiveAction", model.CorrectiveAction); - parameters.Add("@Result", model.Result); - parameters.Add("@ECNLinks", model.ECNLinks); - parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); - parameters.Add("@ECD", model.ECD); - parameters.Add("@ImprovementIDs", model.ImprovementID); - parameters.Add("@ImplementedDate", model.ImplementedDate); - parameters.Add("@CARequired", (model.CARequired)); - parameters.Add("@ActionType", (model.ActionType)); - - this.db.Execute("_8DInsertD5D6CorrectiveAction", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - public void UpdateD5D6CorrectivetAction(D5D6CorrectivetAction model) - { - - var parameters = new DynamicParameters(); - parameters.Add("@D5D6CAID", model.ID); - parameters.Add("@CorrectiveAction", model.CorrectiveAction); - parameters.Add("@Result", model.Result); - parameters.Add("@ECNLinks", model.ECNLinks); - parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); - parameters.Add("@ECD", model.ECD); - parameters.Add("@ImprovementIDs", model.ImprovementID); - parameters.Add("@ImplementedDate", model.ImplementedDate); - parameters.Add("@CARequired", (model.@CARequired)); - parameters.Add("@ActionType", (model.ActionType)); - - this.db.Execute("_8DUpdateD5D6CorrectiveAction", parameters, commandType: CommandType.StoredProcedure); - - } - - - public void DeleteD5D6CorrectivetAction(int d5d6CAID) - { - var parameters = new DynamicParameters(); - parameters.Add("@D5D6CAID", d5d6CAID); - - this.db.Execute("_8DDeleteD5D6CorrectiveActionItem", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - public D5D6CorrectivetAction GetD5D5CAItem(int d5d6CAID) - { - var model = new D5D6CorrectivetAction(); - var parameters = new DynamicParameters(); - parameters.Add("@D5D6CAID", d5d6CAID); - var data = this.db.Query("_8DGetD5D6CA", parameters, commandType: CommandType.StoredProcedure).Single(); - return data; - } - - /// - /// - /// - /// - /// - public IEnumerable GetD5D6ItemAttachments(int d5d6CAID) - { - var model = new D5D6CorrectivetAction(); - var parameters = new DynamicParameters(); - parameters.Add("@D5D6CAID", d5d6CAID); - var data = this.db.Query("_8DGetD5D6ItemAttachmentList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - - - // D7================================================================================================= - - - public IEnumerable GetD7PreventiveActions(int caNo) - { - - var parameters = new DynamicParameters(); - parameters.Add("@CANo", caNo); - var dataList = this.db.Query("_8DGetD7_PAList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return dataList; - - } - - - /// - /// - /// - /// - public void InsertD7PreventiveAction(D7PreventiveAction model) - { - - var parameters = new DynamicParameters(); - parameters.Add("@CANo", model.CANo); - parameters.Add("@PreventiveAction", model.PreventiveAction); - parameters.Add("@Result", model.Result); - parameters.Add("@ECNLinks", model.ECNLinks); - parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); - parameters.Add("@ECD", model.ECD); - parameters.Add("@ImplementedDate", model.ImplementedDate); - - this.db.Execute("_8DInsertD7PreventiveAction", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - public void UpdateD7PreventiveAction(D7PreventiveAction model) - { - - var parameters = new DynamicParameters(); - parameters.Add("@D7PAID", model.ID); - parameters.Add("@PreventiveAction", model.PreventiveAction); - parameters.Add("@Result", model.Result); - parameters.Add("@ECNLinks", model.ECNLinks); - parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); - parameters.Add("@ECD", model.ECD); - parameters.Add("@ImplementedDate", model.ImplementedDate); - - this.db.Execute("_8DUpdateD7PreventiveAction", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - public D7PreventiveAction GetD7PAItem(int d7PAID) - { - var model = new D7PreventiveAction(); - var parameters = new DynamicParameters(); - parameters.Add("@D7PAID", d7PAID); - var data = this.db.Query("_8DGetD7PA", parameters, commandType: CommandType.StoredProcedure).Single(); - return data; - } - - - /// - /// - /// - /// - public void DeleteD7PreventiveActionItem(int D7PAID) - { - var parameters = new DynamicParameters(); - parameters.Add("@D7PAID", D7PAID); - - this.db.Execute("_8DDeleteD7PreventiveActionItem", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - /// - public IEnumerable GetD7ItemAttachments(int d7PAID) - { - var model = new D7PreventiveAction(); - var parameters = new DynamicParameters(); - - parameters.Add("@D7PAID", d7PAID); - var data = this.db.Query("_8DGetD7ItemAttachmentList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - - /// - /// - /// - /// - /// - public IEnumerable GetCAFindingsItemAttachments(int caFindingsID) - { - var model = new D7PreventiveAction(); - var parameters = new DynamicParameters(); - parameters.Add("@CAFindingsID", caFindingsID); - var data = this.db.Query("_8DGetCAFindingsItemAttachmentList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - - - /// - /// - /// - /// - /// - public void ReleaseLockOnDocument(int userID, int issueID) - { - var parameters = new DynamicParameters(); - parameters.Add("@CANo", issueID); - parameters.Add("@UserID", userID); - this.db.Execute("_8DReleaseLockOnCADocuments", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - /// - public List GetRejectionAssigneeEmailList(int caNo) - { - var parameters = new DynamicParameters(); - parameters.Add("@CANo", caNo); - var emailList = this.db.Query("_8DGetRejectionAssigneeEmailList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return emailList; - - } - - /// - /// - /// - /// - /// - /// - public int StartApproval(int issueID, int userID, int worlflowNumber) - { - string subRoles = wfDMO.GetSubRoleItems(issueID, (int)GlobalVars.DocumentType.CorrectiveActionSection); - - // bubble the error - int appoverCount = 0; - var parameters = new DynamicParameters(); - parameters.Add("@CANo", issueID); - parameters.Add("@UserID", userID); - parameters.Add("@DocumentTypeID", (int)GlobalVars.DocumentType.CorrectiveAction); - parameters.Add("@SubRoleCategoriesClause", subRoles); - parameters.Add("@WorkFlowNumber", worlflowNumber); - parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - - this.db.Execute("_8DSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); - - appoverCount = parameters.Get("@AppoverCount"); - return appoverCount; - - } - //public int StartSectionApproval(int issueID, int userID, int worlflowNumber) - //{ - // string subRoles = wfDMO.GetSubRoleItems(issueID, (int)GlobalVars.DocumentType.CorrectiveActionSection); - - // // bubble the error - // int appoverCount = 0; - // var parameters = new DynamicParameters(); - // parameters.Add("@CANo", issueID); - // parameters.Add("@UserID", userID); - // parameters.Add("@DocumentTypeID", (int)GlobalVars.DocumentType.CorrectiveActionSection); - // parameters.Add("@SubRoleCategoriesClause", subRoles); - // parameters.Add("@WorkFlowNumber", worlflowNumber); - // parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - - // this.db.Execute("_8DSubmitForSectionApproval", parameters, commandType: CommandType.StoredProcedure); - - // appoverCount = parameters.Get("@AppoverCount"); - // return appoverCount; - - //} - /// - /// - /// - /// - public List Get8DQA() - { - List users = new List(); - var parameters = new DynamicParameters(); - users = this.db.Query("_8DGet8DQA", parameters, commandType: CommandType.StoredProcedure).ToList(); - return users; - - } - - public void StartSectionApproval(int issueID, int userID, string DSection) - { - //string subRoles = wfDMO.GetSubRoleItems(issueID, (int)GlobalVars.DocumentType.CorrectiveActionSection); - - // bubble the error - var parameters = new DynamicParameters(); - parameters.Add("@CANo", issueID); - parameters.Add("@8DQAUserID", userID); - parameters.Add("@DSection", DSection); - - this.db.Execute("_8DSubmitForSectionApproval", parameters, commandType: CommandType.StoredProcedure); - } - public void ApproveSection(int issueID, int userID, string DSection) - { - //string subRoles = wfDMO.GetSubRoleItems(issueID, (int)GlobalVars.DocumentType.CorrectiveActionSection); - - // bubble the error - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - parameters.Add("@CANo", issueID); - parameters.Add("@DSection", DSection); - - this.db.Execute("UpdateCASectionApproval", parameters, commandType: CommandType.StoredProcedure); - } - public bool IsLastSectionApprover(int caNo, string dSection) - { - bool islastApprover = false; - - var parameters = new DynamicParameters(); - parameters.Add("@CaNo", caNo); - parameters.Add("@DSection", dSection); - parameters.Add("@IsLastApprover", islastApprover, dbType: DbType.Boolean, direction: ParameterDirection.Output); - - - - this.db.Execute("_8DIsLastSectionApprover", parameters, commandType: CommandType.StoredProcedure); - islastApprover = parameters.Get("@IsLastApprover"); - - return islastApprover; - } - public void RejectSection(int issueID, int userID, string DSection, string comments) - { - //string subRoles = wfDMO.GetSubRoleItems(issueID, (int)GlobalVars.DocumentType.CorrectiveActionSection); - - // bubble the error - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - parameters.Add("@CANo", issueID); - parameters.Add("@DSection", DSection); - parameters.Add("@Comments", comments); - - this.db.Execute("RejectCASectionApproval", parameters, commandType: CommandType.StoredProcedure); - } - public bool IsUserSectionApprover(int issueId, int userId) - { - bool isApprover = false; - var parameters = new DynamicParameters(); - parameters.Add("@issueId", issueId); - parameters.Add("@userID", userId); - parameters.Add("@isApprover", isApprover, dbType: DbType.Boolean, direction: ParameterDirection.Output); - - this.db.Execute("_8DIsUserApprover", parameters, commandType: CommandType.StoredProcedure); - - isApprover = parameters.Get("@isApprover"); - return isApprover; - } - public IEnumerable GetCASectionApprovalLog(int caNo) - { - var parameters = new DynamicParameters(); - parameters.Add("@CaNo", caNo); - var ApprovalLogList = this.db.Query("_8DGetSectionApprovalLog", parameters, commandType: CommandType.StoredProcedure).ToList(); - return ApprovalLogList; - } - public DateTime SetCAComplete(int issueID) - { - DateTime followUpDate = new DateTime(); - var parameters = new DynamicParameters(); - parameters.Add("@CaNo", issueID); - parameters.Add("@followUpDate", followUpDate, dbType: DbType.DateTime, direction: ParameterDirection.Output); - - this.db.Execute("_8DSetAsComplete", parameters, commandType: CommandType.StoredProcedure); - followUpDate = parameters.Get("@followUpDate"); - return followUpDate; - } - public DateTime SetCAD3DueDate(int issueID) - { - DateTime d3DueDate = new DateTime(); - var parameters = new DynamicParameters(); - parameters.Add("@CaNo", issueID); - parameters.Add("@D3DueDate", d3DueDate, dbType: DbType.DateTime, direction: ParameterDirection.Output); - - this.db.Execute("_8DSetD3DueDate", parameters, commandType: CommandType.StoredProcedure); - d3DueDate = parameters.Get("@D3DueDate"); - return d3DueDate; - } - public DateTime SetCAD5D7DueDate(int issueID) - { - DateTime d5d7DueDate = new DateTime(); - var parameters = new DynamicParameters(); - parameters.Add("@CaNo", issueID); - parameters.Add("@D5D7DueDate", d5d7DueDate, dbType: DbType.DateTime, direction: ParameterDirection.Output); - - this.db.Execute("_8DSetD5D7DueDate", parameters, commandType: CommandType.StoredProcedure); - d5d7DueDate = parameters.Get("@D5D7DueDate"); - return d5d7DueDate; - } - public IEnumerable GetCAD3D5D7Due() - { - var parameters = new DynamicParameters(); - var dueList = this.db.Query("_8DGetDueD3D5D7", parameters, commandType: CommandType.StoredProcedure).ToList(); - return dueList; - } - public void SetD3D5D7NotificationDate(int caNo, string section) - { - - var parameters = new DynamicParameters(); - parameters.Add("@issueId", caNo); - switch (section) - { - case "D3": - this.db.Execute("_8DSetD3LastNotificationDate", parameters, commandType: CommandType.StoredProcedure); - break; - case "D5D7": - this.db.Execute("_8DSetD5D7LastNotificationDate", parameters, commandType: CommandType.StoredProcedure); - break; - default: - break; - } - - } - - public IEnumerable GetECNList() - { - var parameters = new DynamicParameters(); - var ecnList = this.db.Query("ECNGetECNList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return ecnList; } } -} + + public CorrectiveAction GetCAItem(int caNo, int userID) { + CorrectiveAction ca = new(); + + //isITAR = 2; + + DynamicParameters parameters = new(); + parameters.Add("@CANo", value: caNo); + parameters.Add("@UserID", userID); + + using (var multipleResultItems = db.QueryMultiple("_8DGetCAItem", parameters, commandType: CommandType.StoredProcedure)) { + ca = multipleResultItems.Read().SingleOrDefault(); + + List moduleIDs = multipleResultItems.Read().ToList(); + if (ca != null && moduleIDs != null) { + if (moduleIDs.Count > 0) + ca.ModuleIDs.AddRange(moduleIDs); + } + + List teamMembers = multipleResultItems.Read().ToList(); + if (ca != null && teamMembers != null) { + if (teamMembers.Count > 0) + ca.TeamMemberIDs.AddRange(teamMembers); + } + + List riskAssessments = multipleResultItems.Read().ToList(); + if (ca != null && riskAssessments != null) { + if (riskAssessments.Count > 0) + ca.RiskAssessmentAreaIDs.AddRange(riskAssessments); + } + } + + return ca; + } + + public CorrectiveAction GetCAItemReadOnly(int caNo, int userID) { + CorrectiveAction ca = new(); + + //isITAR = 2; + + DynamicParameters parameters = new(); + parameters.Add("@CANo", value: caNo); + parameters.Add("@UserID", userID); + + using (var multipleResultItems = db.QueryMultiple("_8DGetCAItemReadOnly", parameters, commandType: CommandType.StoredProcedure)) { + ca = multipleResultItems.Read().SingleOrDefault(); + + List moduleIDs = multipleResultItems.Read().ToList(); + if (ca != null && moduleIDs != null) { + if (moduleIDs.Count > 0) + ca.ModuleIDs.AddRange(moduleIDs); + } + + List teamMembers = multipleResultItems.Read().ToList(); + if (ca != null && teamMembers != null) { + if (teamMembers.Count > 0) + ca.TeamMemberIDs.AddRange(teamMembers); + } + + List riskAssessments = multipleResultItems.Read().ToList(); + if (ca != null && riskAssessments != null) { + if (riskAssessments.Count > 0) + ca.RiskAssessmentAreaIDs.AddRange(riskAssessments); + } + + } + + return ca; + } + + public IEnumerable GetUserList() { + DynamicParameters parameters = new(); + List userList = db.Query("_8DGetUserList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return userList; + } + + public IEnumerable GetAllUserList() { + DynamicParameters parameters = new(); + List userList = db.Query("_8DGetAllUserList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return userList; + } + + public IEnumerable GetCASourceList() { + DynamicParameters parameters = new(); + List caSourceList = db.Query("_8DGetCASourceList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return caSourceList; + } + + public IEnumerable GetModuleList() { + DynamicParameters parameters = new(); + List moduleList = db.Query("_8DGetCAModuleList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return moduleList; + } + + public void InsertCAAttachment(CA_Attachment attach) { + DynamicParameters parameters = new(); + parameters.Add("@CANo", attach.CANo); + parameters.Add("@D5D6CAID", attach.D5D6CAID); + parameters.Add("@D7PAID", attach.D7PAID); + parameters.Add("@CAFindingsID", attach.CAFindingsID); + parameters.Add("@UploadedByID", attach.UploadedByID); + parameters.Add("@FileName", attach.FileName); + parameters.Add("@FileGUID", attach.FileGUID); + parameters.Add("@Section", attach.Section); + + db.Execute("_8DInsertCAAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + public IEnumerable GetCAAttachmentsList(int caNo, string section) { + DynamicParameters parameters = new(); + parameters.Add("@CANo", caNo); + parameters.Add("@Section", section); + List caAttachmentList = db.Query("[_8DGetCAAttachmentList]", parameters, commandType: CommandType.StoredProcedure).ToList(); + return caAttachmentList; + } + + public void DeleteCAAttachment(int attachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@AttachmentID", attachmentID); + db.Execute("_8DDeleteCAAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + public string GetCAAttachmentFileName(string fileGUID) { + DynamicParameters parameters = new(); + parameters.Add("@FileGUID", fileGUID); + var fileName = db.Query("_8DGetCAAttachmentFileName", parameters, commandType: CommandType.StoredProcedure).Single(); + return fileName; + } + + public IEnumerable GetD3ContainmentActions(int caNo) { + DynamicParameters parameters = new(); + parameters.Add("@CANo", caNo); + List d3ContainmentActionList = db.Query("_8DGetD3ContainmentActions", parameters, commandType: CommandType.StoredProcedure).ToList(); + return d3ContainmentActionList; + } + + public void UpdateD3ContainmentAction(D3ContainmentAction model) { + DynamicParameters parameters = new(); + parameters.Add("@ID", model.ID); + parameters.Add("@ContainmentAction", model.ContainmentAction); + parameters.Add("@Result", model.Result); + parameters.Add("@ECNLinks", model.ECNLinks); + parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); + parameters.Add("@ECD", model.ECD); + parameters.Add("@ImplementedDate", model.ImplementedDate); + + db.Execute("_8DUpdateD3ContainmentAction", parameters, commandType: CommandType.StoredProcedure); + } + + public void InsertD3ContainmentAction(D3ContainmentAction model) { + DynamicParameters parameters = new(); + parameters.Add("@CANo", model.CANo); + parameters.Add("@ContainmentAction", model.ContainmentAction); + parameters.Add("@Result", model.Result); + parameters.Add("@ECNLinks", model.ECNLinks); + parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); + parameters.Add("@ECD", model.ECD); + parameters.Add("@ImplementedDate", model.ImplementedDate); + + db.Execute("_8DInsertD3ContainmentAction", parameters, commandType: CommandType.StoredProcedure); + } + + public void DeleteD3ContainmentActionItem(int d3ContainmentActionID) { + DynamicParameters parameters = new(); + parameters.Add("@D3ContainmentActionID", d3ContainmentActionID); + + db.Execute("_8DDeleteD3ContainmentActionItem", parameters, commandType: CommandType.StoredProcedure); + } + + public IEnumerable GetD3RiskAssessmentAreas() { + DynamicParameters parameters = new(); + List dataList = db.Query("_8DGetD3RiskAssessmentAreas", parameters, commandType: CommandType.StoredProcedure).ToList(); + return dataList; + } + + public IEnumerable GetD5D6CorrectivetActions(int caNo) { + DynamicParameters parameters = new(); + parameters.Add("@CANo", caNo); + List dataList = db.Query("_8DGetD5D6_CAList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return dataList; + } + + public bool IsAIAssignee(int userId, int caId) { + bool isAssignee = false; + int aiIndex = 0; + List actionItems = GetD5D6CorrectivetActions(caId).ToList(); + while (isAssignee == false && aiIndex < actionItems.Count) { + D5D6CorrectivetAction actionItem = actionItems[aiIndex]; + if (actionItem.ResponsibilityOwnerID == userId && actionItem.ImplementedDate == null && actionItem.Approved) { + isAssignee = true; + } + aiIndex++; + } + return isAssignee; + } + + public IEnumerable GetD5D6Improvement() { + DynamicParameters parameters = new(); + List dataList = db.Query("_8DGetD5D6Improvement", parameters, commandType: CommandType.StoredProcedure).ToList(); + return dataList; + } + + public void InsertD5D6CorrectivetAction(D5D6CorrectivetAction model) { + DynamicParameters parameters = new(); + parameters.Add("@CANo", model.CANo); + parameters.Add("@CorrectiveAction", model.CorrectiveAction); + parameters.Add("@Result", model.Result); + parameters.Add("@ECNLinks", model.ECNLinks); + parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); + parameters.Add("@ECD", model.ECD); + parameters.Add("@ImprovementIDs", model.ImprovementID); + parameters.Add("@ImplementedDate", model.ImplementedDate); + parameters.Add("@CARequired", (model.CARequired)); + parameters.Add("@ActionType", (model.ActionType)); + + db.Execute("_8DInsertD5D6CorrectiveAction", parameters, commandType: CommandType.StoredProcedure); + } + + public void UpdateD5D6CorrectivetAction(D5D6CorrectivetAction model) { + DynamicParameters parameters = new(); + parameters.Add("@D5D6CAID", model.ID); + parameters.Add("@CorrectiveAction", model.CorrectiveAction); + parameters.Add("@Result", model.Result); + parameters.Add("@ECNLinks", model.ECNLinks); + parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); + parameters.Add("@ECD", model.ECD); + parameters.Add("@ImprovementIDs", model.ImprovementID); + parameters.Add("@ImplementedDate", model.ImplementedDate); + parameters.Add("@CARequired", (model.@CARequired)); + parameters.Add("@ActionType", (model.ActionType)); + + db.Execute("_8DUpdateD5D6CorrectiveAction", parameters, commandType: CommandType.StoredProcedure); + } + + public void DeleteD5D6CorrectivetAction(int d5d6CAID) { + DynamicParameters parameters = new(); + parameters.Add("@D5D6CAID", d5d6CAID); + + db.Execute("_8DDeleteD5D6CorrectiveActionItem", parameters, commandType: CommandType.StoredProcedure); + } + + public D5D6CorrectivetAction GetD5D5CAItem(int d5d6CAID) { + D5D6CorrectivetAction model = new(); + DynamicParameters parameters = new(); + parameters.Add("@D5D6CAID", d5d6CAID); + var data = db.Query("_8DGetD5D6CA", parameters, commandType: CommandType.StoredProcedure).Single(); + return data; + } + + public IEnumerable GetD5D6ItemAttachments(int d5d6CAID) { + D5D6CorrectivetAction model = new(); + DynamicParameters parameters = new(); + parameters.Add("@D5D6CAID", d5d6CAID); + List data = db.Query("_8DGetD5D6ItemAttachmentList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + // D7================================================================================================= + + public IEnumerable GetD7PreventiveActions(int caNo) { + DynamicParameters parameters = new(); + parameters.Add("@CANo", caNo); + List dataList = db.Query("_8DGetD7_PAList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return dataList; + } + + public void InsertD7PreventiveAction(D7PreventiveAction model) { + DynamicParameters parameters = new(); + parameters.Add("@CANo", model.CANo); + parameters.Add("@PreventiveAction", model.PreventiveAction); + parameters.Add("@Result", model.Result); + parameters.Add("@ECNLinks", model.ECNLinks); + parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); + parameters.Add("@ECD", model.ECD); + parameters.Add("@ImplementedDate", model.ImplementedDate); + + db.Execute("_8DInsertD7PreventiveAction", parameters, commandType: CommandType.StoredProcedure); + } + + public void UpdateD7PreventiveAction(D7PreventiveAction model) { + DynamicParameters parameters = new(); + parameters.Add("@D7PAID", model.ID); + parameters.Add("@PreventiveAction", model.PreventiveAction); + parameters.Add("@Result", model.Result); + parameters.Add("@ECNLinks", model.ECNLinks); + parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); + parameters.Add("@ECD", model.ECD); + parameters.Add("@ImplementedDate", model.ImplementedDate); + + db.Execute("_8DUpdateD7PreventiveAction", parameters, commandType: CommandType.StoredProcedure); + } + + public D7PreventiveAction GetD7PAItem(int d7PAID) { + D7PreventiveAction model = new(); + DynamicParameters parameters = new(); + parameters.Add("@D7PAID", d7PAID); + var data = db.Query("_8DGetD7PA", parameters, commandType: CommandType.StoredProcedure).Single(); + return data; + } + + public void DeleteD7PreventiveActionItem(int D7PAID) { + DynamicParameters parameters = new(); + parameters.Add("@D7PAID", D7PAID); + + db.Execute("_8DDeleteD7PreventiveActionItem", parameters, commandType: CommandType.StoredProcedure); + } + + public IEnumerable GetD7ItemAttachments(int d7PAID) { + D7PreventiveAction model = new(); + DynamicParameters parameters = new(); + + parameters.Add("@D7PAID", d7PAID); + List data = db.Query("_8DGetD7ItemAttachmentList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetCAFindingsItemAttachments(int caFindingsID) { + D7PreventiveAction model = new(); + DynamicParameters parameters = new(); + parameters.Add("@CAFindingsID", caFindingsID); + List data = db.Query("_8DGetCAFindingsItemAttachmentList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public void ReleaseLockOnDocument(int userID, int issueID) { + DynamicParameters parameters = new(); + parameters.Add("@CANo", issueID); + parameters.Add("@UserID", userID); + db.Execute("_8DReleaseLockOnCADocuments", parameters, commandType: CommandType.StoredProcedure); + } + + public List GetRejectionAssigneeEmailList(int caNo) { + DynamicParameters parameters = new(); + parameters.Add("@CANo", caNo); + List emailList = db.Query("_8DGetRejectionAssigneeEmailList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return emailList; + } + + public int StartApproval(int issueID, int userID, int worlflowNumber) { + string subRoles = wfDMO.GetSubRoleItems(issueID, (int)GlobalVars.DocumentType.CorrectiveActionSection); + + // bubble the error + int appoverCount = 0; + DynamicParameters parameters = new(); + parameters.Add("@CANo", issueID); + parameters.Add("@UserID", userID); + parameters.Add("@DocumentTypeID", (int)GlobalVars.DocumentType.CorrectiveAction); + parameters.Add("@SubRoleCategoriesClause", subRoles); + parameters.Add("@WorkFlowNumber", worlflowNumber); + parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); + + db.Execute("_8DSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); + + appoverCount = parameters.Get("@AppoverCount"); + return appoverCount; + } + + public List Get8DQA() { + List users = new(); + DynamicParameters parameters = new(); + users = db.Query("_8DGet8DQA", parameters, commandType: CommandType.StoredProcedure).ToList(); + return users; + } + + public void StartSectionApproval(int issueID, int userID, string DSection) { + //string subRoles = wfDMO.GetSubRoleItems(issueID, (int)GlobalVars.DocumentType.CorrectiveActionSection); + + // bubble the error + DynamicParameters parameters = new(); + parameters.Add("@CANo", issueID); + parameters.Add("@8DQAUserID", userID); + parameters.Add("@DSection", DSection); + + db.Execute("_8DSubmitForSectionApproval", parameters, commandType: CommandType.StoredProcedure); + } + + public void ApproveSection(int issueID, int userID, string DSection) { + //string subRoles = wfDMO.GetSubRoleItems(issueID, (int)GlobalVars.DocumentType.CorrectiveActionSection); + + // bubble the error + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + parameters.Add("@CANo", issueID); + parameters.Add("@DSection", DSection); + + db.Execute("UpdateCASectionApproval", parameters, commandType: CommandType.StoredProcedure); + } + + public bool IsLastSectionApprover(int caNo, string dSection) { + bool islastApprover = false; + + DynamicParameters parameters = new(); + parameters.Add("@CaNo", caNo); + parameters.Add("@DSection", dSection); + parameters.Add("@IsLastApprover", islastApprover, dbType: DbType.Boolean, direction: ParameterDirection.Output); + + db.Execute("_8DIsLastSectionApprover", parameters, commandType: CommandType.StoredProcedure); + islastApprover = parameters.Get("@IsLastApprover"); + + return islastApprover; + } + + public void RejectSection(int issueID, int userID, string DSection, string comments) { + //string subRoles = wfDMO.GetSubRoleItems(issueID, (int)GlobalVars.DocumentType.CorrectiveActionSection); + + // bubble the error + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + parameters.Add("@CANo", issueID); + parameters.Add("@DSection", DSection); + parameters.Add("@Comments", comments); + + db.Execute("RejectCASectionApproval", parameters, commandType: CommandType.StoredProcedure); + } + + public bool IsUserSectionApprover(int issueId, int userId) { + bool isApprover = false; + DynamicParameters parameters = new(); + parameters.Add("@issueId", issueId); + parameters.Add("@userID", userId); + parameters.Add("@isApprover", isApprover, dbType: DbType.Boolean, direction: ParameterDirection.Output); + + db.Execute("_8DIsUserApprover", parameters, commandType: CommandType.StoredProcedure); + + isApprover = parameters.Get("@isApprover"); + return isApprover; + } + + public IEnumerable GetCASectionApprovalLog(int caNo) { + DynamicParameters parameters = new(); + parameters.Add("@CaNo", caNo); + List ApprovalLogList = db.Query("_8DGetSectionApprovalLog", parameters, commandType: CommandType.StoredProcedure).ToList(); + return ApprovalLogList; + } + + public DateTime SetCAComplete(int issueID) { + DateTime followUpDate = new(); + DynamicParameters parameters = new(); + parameters.Add("@CaNo", issueID); + parameters.Add("@followUpDate", followUpDate, dbType: DbType.DateTime, direction: ParameterDirection.Output); + + db.Execute("_8DSetAsComplete", parameters, commandType: CommandType.StoredProcedure); + followUpDate = parameters.Get("@followUpDate"); + return followUpDate; + } + + public DateTime SetCAD3DueDate(int issueID) { + DateTime d3DueDate = new(); + DynamicParameters parameters = new(); + parameters.Add("@CaNo", issueID); + parameters.Add("@D3DueDate", d3DueDate, dbType: DbType.DateTime, direction: ParameterDirection.Output); + + db.Execute("_8DSetD3DueDate", parameters, commandType: CommandType.StoredProcedure); + d3DueDate = parameters.Get("@D3DueDate"); + return d3DueDate; + } + + public DateTime SetCAD5D7DueDate(int issueID) { + DateTime d5d7DueDate = new(); + DynamicParameters parameters = new(); + parameters.Add("@CaNo", issueID); + parameters.Add("@D5D7DueDate", d5d7DueDate, dbType: DbType.DateTime, direction: ParameterDirection.Output); + + db.Execute("_8DSetD5D7DueDate", parameters, commandType: CommandType.StoredProcedure); + d5d7DueDate = parameters.Get("@D5D7DueDate"); + return d5d7DueDate; + } + + public IEnumerable GetCAD3D5D7Due() { + DynamicParameters parameters = new(); + List dueList = db.Query("_8DGetDueD3D5D7", parameters, commandType: CommandType.StoredProcedure).ToList(); + return dueList; + } + + public void SetD3D5D7NotificationDate(int caNo, string section) { + DynamicParameters parameters = new(); + parameters.Add("@issueId", caNo); + switch (section) { + case "D3": + db.Execute("_8DSetD3LastNotificationDate", parameters, commandType: CommandType.StoredProcedure); + break; + case "D5D7": + db.Execute("_8DSetD5D7LastNotificationDate", parameters, commandType: CommandType.StoredProcedure); + break; + default: + break; + } + + } + + public IEnumerable GetECNList() { + DynamicParameters parameters = new(); + List ecnList = db.Query("ECNGetECNList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return ecnList; + } + + public void AttachSave(int caNo, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var ccPhysicalPath = _AppSettings.AttachmentFolder + @"CorrectiveAction\" + caNo; + di = new DirectoryInfo(ccPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + CA_Attachment attach = new() { + CANo = caNo, + FileGUID = guid, + FileName = fileName, + UploadedByID = userId, + Section = Functions.CASectionMapper(GlobalVars.CASection.Main) + }; + + // InsertCCAttachment(attach); + InsertCAAttachment(attach); + } + + public void D4FilesAttachSave(int caNo, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var ccPhysicalPath = _AppSettings.AttachmentFolder + @"CorrectiveAction\" + caNo; + di = new DirectoryInfo(ccPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + CA_Attachment attach = new() { + CANo = caNo, + FileGUID = guid, + FileName = fileName, + UploadedByID = userId, + Section = Functions.CASectionMapper(GlobalVars.CASection.D4) + + }; + + //InsertCCAttachment(attach); + InsertCAAttachment(attach); + } + + public void SaveD7PA_Attachemnt(int d7PAID, int caNo, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var ccPhysicalPath = _AppSettings.AttachmentFolder + @"CorrectiveAction\" + caNo; + di = new DirectoryInfo(ccPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + CA_Attachment attach = new() { + D7PAID = d7PAID, + CANo = caNo, + FileGUID = guid, + FileName = fileName, + UploadedByID = userId, + Section = Functions.CASectionMapper(GlobalVars.CASection.D7) + + }; + + InsertCAAttachment(attach); + } + + public void SaveD5D6CA_Attachemnt(int d5d6CAID, int caNo, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var ccPhysicalPath = _AppSettings.AttachmentFolder + @"CorrectiveAction\" + caNo; + di = new DirectoryInfo(ccPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + CA_Attachment attach = new() { + D5D6CAID = d5d6CAID, + CANo = caNo, + FileGUID = guid, + FileName = fileName, + UploadedByID = userId, + Section = Functions.CASectionMapper(GlobalVars.CASection.D5) + + }; + + InsertCAAttachment(attach); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/ECNTypeChangeLogDMO.cs b/Fab2ApprovalSystem/DMO/ECNTypeChangeLogDMO.cs index 6eb323f..bd41908 100644 --- a/Fab2ApprovalSystem/DMO/ECNTypeChangeLogDMO.cs +++ b/Fab2ApprovalSystem/DMO/ECNTypeChangeLogDMO.cs @@ -1,41 +1,24 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; using System.Data; using System.Data.SqlClient; -using Fab2ApprovalSystem.Models; + using Dapper; -using System.Configuration; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.DMO -{ - /// - /// - /// - public static class ECNTypeChangeLogDMO - { - private static IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); +namespace Fab2ApprovalSystem.DMO; - /// - /// - /// - /// - public static void Add(ECNTypeChangeLog changeLog) - { +public static class ECNTypeChangeLogDMO { + private static readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", changeLog.ECNNumber); - parameters.Add("@UserID", changeLog.UserID); - parameters.Add("@ECNTypeFrom", changeLog.ECNTypeFrom); - parameters.Add("@ECNTypeTo", changeLog.ECNTypeTo); - - db.Execute("ECNInsertECNTypeChangeLog", parameters, commandType: CommandType.StoredProcedure); - } + public static void Add(ECNTypeChangeLog changeLog) { + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", changeLog.ECNNumber); + parameters.Add("@UserID", changeLog.UserID); + parameters.Add("@ECNTypeFrom", changeLog.ECNTypeFrom); + parameters.Add("@ECNTypeTo", changeLog.ECNTypeTo); + db.Execute("ECNInsertECNTypeChangeLog", parameters, commandType: CommandType.StoredProcedure); } - - -} +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/ECN_DMO.cs b/Fab2ApprovalSystem/DMO/ECN_DMO.cs index a69dfbd..ccec594 100644 --- a/Fab2ApprovalSystem/DMO/ECN_DMO.cs +++ b/Fab2ApprovalSystem/DMO/ECN_DMO.cs @@ -1,1072 +1,792 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.Data; using System.Data.SqlClient; +using System.IO; using System.Linq; using System.Text; -using System.Web; -using Fab2ApprovalSystem.Models; -using Dapper; using System.Transactions; -using Fab2ApprovalSystem.ViewModels; -using System.Reflection; + +using Dapper; + using Fab2ApprovalSystem.Misc; -using ICSharpCode.SharpZipLib; +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.ViewModels; -namespace Fab2ApprovalSystem.DMO -{ - public class ECN_DMO - { - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - WorkflowDMO wfDMO = new WorkflowDMO(); - +namespace Fab2ApprovalSystem.DMO; - /// - /// - /// - /// - /// - internal ECN InsertECN(ECN ecn) - { +public class ECN_DMO { + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + private readonly WorkflowDMO wfDMO = new(); - var parameters = new DynamicParameters(); - - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", value: ecn.ECNNumber, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@OriginatorID", ecn.OriginatorID); + internal ECN InsertECN(ECN ecn) { + DynamicParameters parameters = new(); - this.db.Execute("ECNInsertItem", parameters, commandType: CommandType.StoredProcedure); - ecn.ECNNumber = parameters.Get("@ECNNumber"); - - return ecn; - } + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", value: ecn.ECNNumber, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@OriginatorID", ecn.OriginatorID); - /// - /// - /// - /// - internal void UpdateECN(ECN ecn) - { + db.Execute("ECNInsertItem", parameters, commandType: CommandType.StoredProcedure); + ecn.ECNNumber = parameters.Get("@ECNNumber"); - //ECN temp = GetECN(ecn.ECNNumber); - //if (temp.Equals(ecn)) - //{ - // string s = "good to go..."; - //} + return ecn; + } - var parameters = new DynamicParameters(); - using (var transanction = new TransactionScope()) - { - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - parameters.Add("@Title", ecn.Title); - parameters.Add("@IsECN", ecn.IsECN); - parameters.Add("@IsTECN", ecn.IsTECN); - parameters.Add("@IsEmergencyTECN", ecn.IsEmergencyTECN); - parameters.Add("@ExpirationDate", ecn.ExpirationDate); - parameters.Add("@ExtensionDate", ecn.ExtensionDate); - parameters.Add("@CancellationDate", ecn.CancellationDate); - parameters.Add("@AcknowledgementRequired", ecn.AcknowledgementRequired); - parameters.Add("@TrainingRequired", ecn.TrainingRequired); - parameters.Add("@AreaID", ecn.AreaID); - parameters.Add("@TechnologyID", ecn.TechnologyID); - parameters.Add("@PCRBRequired", ecn.PCRBRequired); - parameters.Add("@PCRBNumber", ecn.PCRBNumber); - parameters.Add("@TestProgramChangeRequired", ecn.TestProgramChangeRequired); - parameters.Add("@MetrologyChangeRequired", ecn.MetrologyChangeRequired); - parameters.Add("@SPCChangeRequired", ecn.SPCChangeRequired); - parameters.Add("@NewPartFlowRequired", ecn.NewPartFlowRequired); - parameters.Add("@SPNChangeRequired", ecn.SPNChangeRequired); - parameters.Add("@ImplementationDetails", ecn.ImplementationDetails); - parameters.Add("@ImpactOnEnvironment", ecn.ImpactOnEnvironment); - parameters.Add("@ImpactOnEnvironmentDescription", ecn.ImpactOnEnvironmentDescription); - parameters.Add("@ImpactOnCapacity", ecn.ImpactOnCapacity); - parameters.Add("@ImpactOnCapacityDescription", ecn.ImpactOnCapacityDescription); - parameters.Add("@IsMA", ecn.IsMA); - parameters.Add("@IsRH", ecn.IsRH); - parameters.Add("@IsAU", ecn.IsAU); - parameters.Add("@IsIndustrial", ecn.IsIndustrial); - parameters.Add("@MaterialConsumptionChangeRequired", ecn.MaterialConsumptionChangeRequired); - parameters.Add("@MaterialConsumptionChangeDescription", ecn.MaterialConsumptionChangeDescription); - parameters.Add("@ReasonForChange", ecn.ReasonForChange); - parameters.Add("@DescriptionOfChange", ecn.DescriptionOfChange); - parameters.Add("@NotAFlowChange", ecn.NotAFlowChange); - parameters.Add("@AttachECN_TECNToLots", ecn.AttachECN_TECNToLots); - parameters.Add("@SPNFlowChangeAtSingleStep", ecn.SPNFlowChangeAtSingleStep); - parameters.Add("@SPNFlowChangeAtMultipleSteps", ecn.SPNFlowChangeAtMultipleSteps); - parameters.Add("@CategoryID", ecn.CategoryID); - parameters.Add("@FIChangeRequired", ecn.FIChangeRequired); - parameters.Add("@NumberOfLotsAffected", ecn.NumberOfLotsAffected); - parameters.Add("@RecipeChange", ecn.RecipeChange); - //RJK ITAR/EC - parameters.Add("@IsDocEC", ecn.IsDocEC); - this.db.Execute("ECNUpdate", parameters, commandType: CommandType.StoredProcedure); - - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - this.db.Execute("ECNDeleteAffectedDepartments", parameters, commandType: CommandType.StoredProcedure); - List ecnDepIDs = ecn.DepartmentIDs; - if (ecnDepIDs != null) - { - foreach (int depId in ecnDepIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - parameters.Add("@DepartmentID", depId); - this.db.Execute("ECNInsertAffectedDepartments", parameters, commandType: CommandType.StoredProcedure); - } - } - - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - this.db.Execute("ECNDeleteAffectedModules", parameters, commandType: CommandType.StoredProcedure); - - List ecnModuleIDs = ecn.ModuleIDs; - if (ecnModuleIDs != null) - { - foreach (int moduleID in ecnModuleIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - parameters.Add("@ModuleID", moduleID); - this.db.Execute("ECNInsertAffectedModules", parameters, commandType: CommandType.StoredProcedure); - } - } - - - List ecnAreaIDs = ecn.AreaIDs; - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - this.db.Execute("ECNDeleteAffectedAreas", parameters, commandType: CommandType.StoredProcedure); - - if (ecnAreaIDs != null) - { - - foreach (int ecnAreaID in ecnAreaIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - parameters.Add("@AreaID", ecnAreaID); - this.db.Execute("ECNInsertAffectedAreas", parameters, commandType: CommandType.StoredProcedure); - } - } - - List ecnTechnologyIDs = ecn.TechnologyIDs; - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - this.db.Execute("ECNDeleteAffectedTechnologies", parameters, commandType: CommandType.StoredProcedure); - - if (ecnTechnologyIDs != null) - { - - foreach (int ecnTechnologyID in ecnTechnologyIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - - parameters.Add("@TechnologyID", ecnTechnologyID); - this.db.Execute("ECNInsertAffectedTechnologies", parameters, commandType: CommandType.StoredProcedure); - } - } - - - List ecnAcknowledgementByIDs = ecn.AcknowledgementByIDs; - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - this.db.Execute("ECNDeleteAcknowledgementBy", parameters, commandType: CommandType.StoredProcedure); - - if (ecnAcknowledgementByIDs != null) - { - - foreach (int ecnAcknowledgementByID in ecnAcknowledgementByIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - - parameters.Add("@AcknowledgementByID", ecnAcknowledgementByID); - this.db.Execute("ECNInsertAcknowledgementBy", parameters, commandType: CommandType.StoredProcedure); - } - } - - - List ecnTrainingByIDs = ecn.TrainingByIDs; - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - this.db.Execute("ECNDeleteTrainingBy", parameters, commandType: CommandType.StoredProcedure); - - if (ecnTrainingByIDs != null) - { - foreach (int ecnTrainingByID in ecnTrainingByIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - - parameters.Add("@TrainingByID", ecnTrainingByID); - this.db.Execute("ECNInsertTrainingBy", parameters, commandType: CommandType.StoredProcedure); - } - } - - - List ecnProductFamilyIDs = ecn.ProductFamilyIDs; - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - this.db.Execute("ECNDeleteAffectedProductFamilies", parameters, commandType: CommandType.StoredProcedure); - - if (ecnProductFamilyIDs != null) - { - foreach (int ecnProductFamilyID in ecnProductFamilyIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecn.ECNNumber); - - parameters.Add("@ProductFamilyID", ecnProductFamilyID); - this.db.Execute("ECNInsertAffectedProductFamilies", parameters, commandType: CommandType.StoredProcedure); - } - } - - transanction.Complete(); - } - } - - /// - /// - /// - /// - /// - internal ECN GetECN(int ecnNumber, out int isITAR, int userID) - { - /* IsITAR - 0 = false - 1 = true - 2 = not required - */ - isITAR = 2; - - var ecnItem = new ECN(); - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", value: ecnNumber); - parameters.Add("@UserID", userID); - //parameters.Add("@UserID", GlobalVars.USER_ID); - parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - //StringBuilder query = new StringBuilder("ECNGetItem"); - - - using (var multipleResultItems = this.db.QueryMultiple("ECNGetItem", parameters, commandType: CommandType.StoredProcedure)) - { - ecnItem = multipleResultItems.Read().SingleOrDefault(); - - var departments = multipleResultItems.Read().ToList(); - if (ecnItem != null && departments != null) - { - if (departments.Count > 0) - ecnItem.DepartmentIDs.AddRange(departments); - } - - var modules = multipleResultItems.Read().ToList(); - if (ecnItem != null && modules != null) - { - if (modules.Count > 0) - ecnItem.ModuleIDs.AddRange(modules); - } - - var areas = multipleResultItems.Read().ToList(); - if (ecnItem != null && areas != null) - { - if (areas.Count > 0) - ecnItem.AreaIDs.AddRange(areas); - } - - var technologies = multipleResultItems.Read().ToList(); - if (ecnItem != null && technologies != null) - { - if (technologies.Count > 0) - ecnItem.TechnologyIDs.AddRange(technologies); - } - - var acknowledgmentby = multipleResultItems.Read().ToList(); - if (ecnItem != null && acknowledgmentby != null) - { - if (acknowledgmentby.Count > 0) - ecnItem.AcknowledgementByIDs.AddRange(acknowledgmentby); - } - - var trainingby = multipleResultItems.Read().ToList(); - if (ecnItem != null && trainingby != null) - { - if (trainingby.Count > 0) - ecnItem.TrainingByIDs.AddRange(trainingby); - } - - var productfamilies = multipleResultItems.Read().ToList(); - if (ecnItem != null && productfamilies != null) - { - if (productfamilies.Count > 0) - ecnItem.ProductFamilyIDs.AddRange(productfamilies); - } - - } - - isITAR = parameters.Get("@IsITAR"); - - return ecnItem; - - } - - /// - /// - /// - /// - /// - public int PCRBExists(int pcrb) - { - int result = 0; - var ecnItem = new ECN(); - var parameters = new DynamicParameters(); - parameters.Add("@PCRB", value: pcrb); - parameters.Add("@Result", value: result, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - this.db.Execute("ECNPCRBExists", parameters, commandType: CommandType.StoredProcedure); - result = parameters.Get("@Result"); - - return result; - } - - /// - /// - /// - /// - /// - /// - /// - internal ECN GetECNForRead(int ecnNumber, out int isITAR, int userID) - { - /* IsITAR - 0 = false - 1 = true - 2 = not required - */ - isITAR = 2; - - var ecnItem = new ECN(); - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", value: ecnNumber); - parameters.Add("@UserID", userID); - //parameters.Add("@UserID", GlobalVars.USER_ID); - parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - //StringBuilder query = new StringBuilder("ECNGetItem"); - - - using (var multipleResultItems = this.db.QueryMultiple("ECNGetItemForRead", parameters, commandType: CommandType.StoredProcedure)) - { - ecnItem = multipleResultItems.Read().SingleOrDefault(); - - var departments = multipleResultItems.Read().ToList(); - if (ecnItem != null && departments != null) - { - if (departments.Count > 0) - ecnItem.DepartmentIDs.AddRange(departments); - } - - var modules = multipleResultItems.Read().ToList(); - if (ecnItem != null && modules != null) - { - if (modules.Count > 0) - ecnItem.ModuleIDs.AddRange(modules); - } - - var areas = multipleResultItems.Read().ToList(); - if (ecnItem != null && areas != null) - { - if (areas.Count > 0) - ecnItem.AreaIDs.AddRange(areas); - } - - var technologies = multipleResultItems.Read().ToList(); - if (ecnItem != null && technologies != null) - { - if (technologies.Count > 0) - ecnItem.TechnologyIDs.AddRange(technologies); - } - - var acknowledgmentby = multipleResultItems.Read().ToList(); - if (ecnItem != null && acknowledgmentby != null) - { - if (acknowledgmentby.Count > 0) - ecnItem.AcknowledgementByIDs.AddRange(acknowledgmentby); - } - - var trainingby = multipleResultItems.Read().ToList(); - if (ecnItem != null && trainingby != null) - { - if (trainingby.Count > 0) - ecnItem.TrainingByIDs.AddRange(trainingby); - } - - var productfamilies = multipleResultItems.Read().ToList(); - if (ecnItem != null && productfamilies != null) - { - if (productfamilies.Count > 0) - ecnItem.ProductFamilyIDs.AddRange(productfamilies); - } - - } - - isITAR = parameters.Get("@IsITAR"); - - return ecnItem; - - } - - /// - /// - /// - /// - /// - internal ECNPdf GetECNPdf(int ecnNumber) - { - - var ecnItem = new ECNPdf(); - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", value: ecnNumber); - - //StringBuilder query = new StringBuilder("ECNGetItem"); - - - using (var multipleResultItems = this.db.QueryMultiple("ECNGetPdfItem", parameters, commandType: CommandType.StoredProcedure)) - { - ecnItem = multipleResultItems.Read().SingleOrDefault(); - - var departments = multipleResultItems.Read().ToList(); - //if (ecnItem != null && departments != null) - //{ - // if (departments.Count > 0) - // ecnItem.AffectedDepartments.AddRange(departments); - //} - - var modules = multipleResultItems.Read().ToList(); - //if (ecnItem != null && modules != null) - //{ - // if (modules.Count > 0) - // ecnItem.AffectedModules.AddRange(modules); - //} - - var attachments = multipleResultItems.Read().ToList(); - if (ecnItem != null && attachments != null) - { - if (attachments.Count > 0) - ecnItem.Attachments.AddRange(attachments); - } - - var approvalLog = multipleResultItems.Read().ToList(); - if (ecnItem != null && approvalLog != null) - { - if (approvalLog.Count > 0) - ecnItem.Approvalog.AddRange(approvalLog); - } - - var affectedAreas = multipleResultItems.Read().ToList(); - var affectedTechnologies = multipleResultItems.Read().ToList(); - var acknowledgementBy = multipleResultItems.Read().ToList(); - var trainingBy = multipleResultItems.Read().ToList(); - var productfamilies = multipleResultItems.Read().ToList(); - - ecnItem.AffectedModules = String.Join(", ", modules); - ecnItem.AffectedDepartments = String.Join(", ", departments); - ecnItem.AffectedAreas = String.Join(",", affectedAreas); - ecnItem.AffectedTechnologies = String.Join(",", affectedTechnologies); - ecnItem.TrainingBy = String.Join(",", trainingBy); - ecnItem.AcknowledgementBy = String.Join(",", acknowledgementBy); - ecnItem.AffectedProductFamilies = String.Join(",", productfamilies); - - } - return ecnItem; - } - - /// - /// - /// - /// - /// - internal ECN GetECN(int ecnNumber) - { - ECN ecnItem = new ECN(); - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", value: ecnNumber); - - ecnItem = this.db.Query("ECNGetECNData", parameters, commandType: CommandType.StoredProcedure).Single(); - - return ecnItem; - } - - /// - /// - /// - /// - internal List GetDepartments() - { - var departments = this.db.Query("ECNGetDepartments", null, commandType: CommandType.StoredProcedure).ToList(); - return departments; - } - - /// - /// - /// - /// - internal List GetModules() - { - var modules = this.db.Query("ECNGetModules", null, commandType: CommandType.StoredProcedure).ToList(); - return modules; - - } - - internal List GetCategories() - { - var r = this.db.Query("ECNGetCategories", null, commandType: CommandType.StoredProcedure).ToList(); - return r; - } - - /// - /// - /// - /// - internal List GetECNAreas() - { - - StringBuilder query = new StringBuilder("SELECT AreaID , Area FROM ECNArea ORDER BY Area"); - return this.db.Query(query.ToString()).ToList(); - - } - - /// - /// - /// - /// - /// - //internal List GetECNTechnology(int? areaId) + internal void UpdateECN(ECN ecn) { + //ECN temp = GetECN(ecn.ECNNumber); + //if (temp.Equals(ecn)) //{ - // var parameters = new DynamicParameters(); - // parameters.Add("@AreaId", value: areaId); - - // StringBuilder query = new StringBuilder("SELECT TechnologyID, Technology FROM ECNTechnology WHERE AreaID = @AreaId ORDER BY Technology"); - // return this.db.Query(query.ToString(), parameters ).ToList(); - + // string s = "good to go..."; //} - internal List GetECNTechnologies() - { - var parameters = new DynamicParameters(); - - - StringBuilder query = new StringBuilder("SELECT DISTINCT TechnologyID, Technology FROM ECNTechnology ORDER BY Technology"); - return this.db.Query(query.ToString()).ToList(); - - } - - internal List GetECNAcknowledgementTrainingBy() - { - var parameters = new DynamicParameters(); - - - StringBuilder query = new StringBuilder("SELECT DISTINCT AcknowledgementTrainingByID, AcknowledgementTrainingBy FROM ECNAcknowledgementTrainingBy ORDER BY AcknowledgementTrainingBy"); - return this.db.Query(query.ToString()).ToList(); - } - - - /// - /// - /// - /// - /// - public IEnumerable GetECNAttachments(int ecnNumber) - { - StringBuilder sql = new StringBuilder(); - sql.Append("SELECT A.AttachmentID, A.ECNNumber, A.FileName, A.UserID, CONVERT(VARCHAR(10), A.UploadDate, 101) AS UploadDate, U.FirstName + ' ' + U.LastName AS FullName "); - sql.Append("FROM ECNAttachment A INNER JOIN Users U ON A.UserID = U.UserID WHERE ECNNumber = @ECNNumber "); - var attachments = this.db.Query(sql.ToString(), new { ECNNumber = ecnNumber }).ToList(); - return attachments; - } - - - public IEnumerable GetECNApprovalLogHistory(int ecnNumber) - { - - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - var approverList = this.db.Query("ECNGetECNApprovalLogHistory", parameters, commandType: CommandType.StoredProcedure).ToList(); - return approverList; - } - - public IEnumerable GetTECNNotificationUsers() - { - string sql = "select T.UserId from TECNNotificationsUsers T"; - var result = this.db.Query(sql).ToList(); - return result; - } - - - - /// - /// - /// - /// - public void DeleteECNAttachment(int attachmentID) - { - var parameters = new DynamicParameters(); - parameters.Add("@AttachmentID", attachmentID); - this.db.Execute("ECNDeleteAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - public void InsertECNAttachment(ECNAttachment attach) - { - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", attach.ECNNumber); - parameters.Add("@UserID", attach.UserID); - parameters.Add("@FileName", attach.FileName); - - this.db.Execute("ECNInsertAttachment", parameters, commandType: CommandType.StoredProcedure); - - - } - - /// - /// - /// - /// - /// - public List GetRejectionOrginatorEmailList(int ecnNumber) - { - - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - var emailList = this.db.Query("ECNGetRejectionOrginatorEmailList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return emailList; - - } - - /// - /// - /// - /// - /// - /// - /// - public int SubmitDocument(int issueID, int userID, int documentType, out int allowedITAR) - { - allowedITAR = 1; - string subRoles = ""; - if (documentType != (int)GlobalVars.DocumentType.EECN) - subRoles = wfDMO.GetSubRoleItems(issueID, documentType); - - // bubble the error - int appoverCount = 0; - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", issueID); - parameters.Add("@UserID", userID); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@SubRoleCategoriesClause", subRoles); - parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - parameters.Add("@AllowedITAR", allowedITAR, dbType: DbType.Int32, direction: ParameterDirection.Output); - this.db.Execute("ECNSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); - - appoverCount = parameters.Get("@AppoverCount"); - allowedITAR = parameters.Get("@AllowedITAR"); - - return appoverCount; - - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public int ReSubmitDocument(int issueID, int userID, int documentType, out int allowedITAR, string descriptionOfChange, string reasonForChange, string ecnTypeString, out int newECNNumber, int categoryId) - { - newECNNumber = 0; - allowedITAR = 1; - string subRoles = ""; - if (documentType != (int)GlobalVars.DocumentType.EECN) - subRoles = wfDMO.GetSubRoleItems(issueID, documentType); - - // bubble the error - int appoverCount = 0; - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", issueID); - parameters.Add("@UserID", userID); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@SubRoleCategoriesClause", subRoles); - parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - parameters.Add("@DescriptionOfChange", descriptionOfChange); - parameters.Add("@ReasonForChange", reasonForChange); - parameters.Add("@NewECNTypeString", ecnTypeString); - parameters.Add("NewECNNumber", newECNNumber, direction: ParameterDirection.Output); - parameters.Add("@CategoryID", categoryId); - this.db.Execute("ECNReSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); - - - appoverCount = parameters.Get("@AppoverCount"); - //allowedITAR = parameters.Get("@AllowedITAR"); - newECNNumber = parameters.Get("@NewECNNumber"); - return appoverCount; - - } - - /// - /// - /// - /// - /// - /// - /// - public int SubmitForCancellation(int issueID, byte currentStep, int userID, int documentType, string ecnType, int TECNOperationType) - { - string subRoles = ""; - if (documentType != (int)GlobalVars.DocumentType.EECN) - subRoles = wfDMO.GetSubRoleItems(issueID, documentType); - - // bubble the error - int appoverCount = 0; - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", issueID); - parameters.Add("@UserID", userID); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@ECNType", ecnType); - parameters.Add("@Step", currentStep); - parameters.Add("@SubRoleCategoriesClause", subRoles); - parameters.Add("@OperationType", TECNOperationType); - parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - - this.db.Execute("ECNSubmitCancellation_Expiration", parameters, commandType: CommandType.StoredProcedure); - - appoverCount = parameters.Get("@AppoverCount"); - return appoverCount; - - } - - - - - - /// - /// - /// - /// - /// - /// - /// - /// - public int SubmitTECNExtensionDocument(int issueID, int userID, int documentType, DateTime extensionDate) - { - string subRoles = ""; - if (documentType != (int)GlobalVars.DocumentType.EECN) - subRoles = wfDMO.GetSubRoleItems(issueID, documentType); - - // bubble the error - int appoverCount = 0; - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", issueID); - parameters.Add("@UserID", userID); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@TECNExtensionDate", extensionDate); - parameters.Add("@SubRoleCategoriesClause", subRoles); - parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - - this.db.Execute("ECN_TECNExtensionSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); - - appoverCount = parameters.Get("@AppoverCount"); - return appoverCount; - - } - - - /// - /// - /// - /// - /// - public void SaveAfterSubmitByApprover(int ecnNumber, string implementationDetails) - { - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - parameters.Add("@ImplementationDetails", implementationDetails); - - this.db.Execute("ECNSaveAfterSubmitByApprover", parameters, commandType: CommandType.StoredProcedure); - - } - - - /// - /// - /// - /// - /// - public void TECNExtensionLog(int ecnNumber, DateTime extensionDate ) - { - - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - parameters.Add("@ExtensionDate", extensionDate); - - this.db.Execute("ECN_TECNExtensionLogUpdate", parameters, commandType: CommandType.StoredProcedure); - - - } - - /// - /// Cancels the document before the approval loopmis closed - /// - /// - public void DeleteDocument(int ecnNumber, int userid, string ecnTypeString) - { - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userid); - parameters.Add("@ECNNumber", ecnNumber); - parameters.Add("@ECNType", ecnTypeString); - - this.db.Execute("ECNDeleteDocument", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - public void UpdateECNType(int ecnNumber, string ecnType) - { - string updateSql = ""; - if (ecnType == "ECN") - updateSql = "UPDATE ECN SET IsECN = 1 , IsTECN = 0, IsEmergencyTECN = 0 WHERE ECNNumber = @ECNNumber " ; - else if (ecnType == "TECN") - updateSql = "UPDATE ECN SET IsECN = 0 , IsTECN = 1, IsEmergencyTECN = 0 WHERE ECNNumber = @ECNNumber " ; - - this.db.Execute(updateSql, new { ECNNumber = ecnNumber }, commandType: CommandType.Text); - - } - - /// - /// - /// - /// - /// - /// - /// - /// - public void SetToExecutionStep(int ecnNumber, int userid, int documentType, string ecnTypeString) - { - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - parameters.Add("@UserID", userid); - parameters.Add("@DocumentType", documentType); - parameters.Add("@ECNType", ecnTypeString); - - - this.db.Execute("ECNSetToExecutionStep", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public bool ECNApproveCancelled_ExpiredDocument(int issueID, byte step, string comments, out bool lastStep, int userID, int documentType) - { - string subRolesInClause = wfDMO.GetSubRoleItems(issueID, documentType); - - lastStep = false; - bool lastApproverInCurrentStep = false; - - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID); - parameters.Add("@CurrentStep", step); - parameters.Add("@ItemStatus", (int)GlobalVars.ApprovalOption.Approved); - parameters.Add("@UserID", userID); - parameters.Add("@Comments", comments); - parameters.Add("@SubRoleCategoriesClause", subRolesInClause); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@LastStep", lastStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); - parameters.Add("@LastApproverInCurrentStep", lastApproverInCurrentStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); - - this.db.Execute("UpdateApproval", parameters, commandType: CommandType.StoredProcedure); - - lastStep = parameters.Get("@LastStep"); - lastApproverInCurrentStep = parameters.Get("@LastApproverInCurrentStep"); - - return lastApproverInCurrentStep; - - } - - - /// - /// - /// - /// - public IEnumerable GetECN_TECNPendingApprovals(int userID) - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var data = this.db.Query("ECNGetECN_TECNPendingApprovalsByOriginator", new { userID }, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - /// - /// - /// - /// - /// - public IEnumerable GetMyExpiredTECNs(int userID, int maxDays) - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var data = this.db.Query("ECNGetExpiredTECNByOriginator", new { userID, maxDays }, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - /// - /// - /// - /// - /// - public IEnumerable GetAllTECNs() - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var data = this.db.Query("ECNGetAllTECN", commandType: CommandType.StoredProcedure).ToList(); - return data; - } - /// - /// - /// - /// - /// - /// - public IEnumerable GetMyConvertedTECNsToECNs(int userID, int maxDays) - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var data = this.db.Query("ECNGetTECNConvertedToECNByOriginator", new { userID, maxDays }, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - /// - /// - /// - /// - /// - /// - public IEnumerable GetMyExpiringTECNs(int userID, int maxDays) - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var data = this.db.Query("ECNGetExpiringTECNByOriginator", new { userID, maxDays }, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - - /// - /// - /// - /// - public void CancelECN(int? ecnNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", ecnNumber); - - this.db.Execute("ECNCancelECN", parameters, commandType: CommandType.StoredProcedure); - - } - - - /// - /// - /// - /// - public void ECNResetTECNAtRejection(int ecnNumber, int userID, int docType) - { - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - parameters.Add("@UserID", userID); - parameters.Add("@DocumentTypeID", docType); - - this.db.Execute("ECNResetTECNAtRejection", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - public bool CanSubmitECN(int ecnNumber) - { - bool tecnExtensionState = false; - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - parameters.Add("@TECNExtensionState", value: tecnExtensionState, dbType: DbType.Boolean, direction: ParameterDirection.InputOutput); - - this.db.Execute("ECNCanSubmitECN", parameters, commandType: CommandType.StoredProcedure); - - - tecnExtensionState = parameters.Get("@TECNExtensionState"); - - return tecnExtensionState; - } - - - /// - /// - /// - /// - /// - public void ReleaseLockOnDocument(int userID, int issueID) - { - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID); - parameters.Add("@UserID", userID); - this.db.Execute("ECNReleaseLockOnECNDocuments", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - public string GetFileName(string attachmentID) - { - var parameters = new DynamicParameters(); - parameters.Add("@AttachmentID", attachmentID); - var fileName = this.db.Query("ECNGetFileName", parameters, commandType: CommandType.StoredProcedure).Single(); - return fileName; - } - - - public void ReassignOriginatorECN(int ecnNumber, int newOriginatorID, string comments, int userID) - { - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - parameters.Add("@NewOriginatorID", newOriginatorID); - parameters.Add("@Comments", comments); - parameters.Add("@UserID", userID); - - this.db.Execute("ECNReassignOriginator", parameters, commandType: CommandType.StoredProcedure); - } - - internal List GetProductFamilies() - { - var r = this.db.Query("ECNGetProductFamilies", null, commandType: CommandType.StoredProcedure).ToList(); - return r; + DynamicParameters parameters = new(); + using (TransactionScope transanction = new()) { + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + parameters.Add("@Title", ecn.Title); + parameters.Add("@IsECN", ecn.IsECN); + parameters.Add("@IsTECN", ecn.IsTECN); + parameters.Add("@IsEmergencyTECN", ecn.IsEmergencyTECN); + parameters.Add("@ExpirationDate", ecn.ExpirationDate); + parameters.Add("@ExtensionDate", ecn.ExtensionDate); + parameters.Add("@CancellationDate", ecn.CancellationDate); + parameters.Add("@AcknowledgementRequired", ecn.AcknowledgementRequired); + parameters.Add("@TrainingRequired", ecn.TrainingRequired); + parameters.Add("@AreaID", ecn.AreaID); + parameters.Add("@TechnologyID", ecn.TechnologyID); + parameters.Add("@PCRBRequired", ecn.PCRBRequired); + parameters.Add("@PCRBNumber", ecn.PCRBNumber); + parameters.Add("@TestProgramChangeRequired", ecn.TestProgramChangeRequired); + parameters.Add("@MetrologyChangeRequired", ecn.MetrologyChangeRequired); + parameters.Add("@SPCChangeRequired", ecn.SPCChangeRequired); + parameters.Add("@NewPartFlowRequired", ecn.NewPartFlowRequired); + parameters.Add("@SPNChangeRequired", ecn.SPNChangeRequired); + parameters.Add("@ImplementationDetails", ecn.ImplementationDetails); + parameters.Add("@ImpactOnEnvironment", ecn.ImpactOnEnvironment); + parameters.Add("@ImpactOnEnvironmentDescription", ecn.ImpactOnEnvironmentDescription); + parameters.Add("@ImpactOnCapacity", ecn.ImpactOnCapacity); + parameters.Add("@ImpactOnCapacityDescription", ecn.ImpactOnCapacityDescription); + parameters.Add("@IsMA", ecn.IsMA); + parameters.Add("@IsRH", ecn.IsRH); + parameters.Add("@IsAU", ecn.IsAU); + parameters.Add("@IsIndustrial", ecn.IsIndustrial); + parameters.Add("@MaterialConsumptionChangeRequired", ecn.MaterialConsumptionChangeRequired); + parameters.Add("@MaterialConsumptionChangeDescription", ecn.MaterialConsumptionChangeDescription); + parameters.Add("@ReasonForChange", ecn.ReasonForChange); + parameters.Add("@DescriptionOfChange", ecn.DescriptionOfChange); + parameters.Add("@NotAFlowChange", ecn.NotAFlowChange); + parameters.Add("@AttachECN_TECNToLots", ecn.AttachECN_TECNToLots); + parameters.Add("@SPNFlowChangeAtSingleStep", ecn.SPNFlowChangeAtSingleStep); + parameters.Add("@SPNFlowChangeAtMultipleSteps", ecn.SPNFlowChangeAtMultipleSteps); + parameters.Add("@CategoryID", ecn.CategoryID); + parameters.Add("@FIChangeRequired", ecn.FIChangeRequired); + parameters.Add("@NumberOfLotsAffected", ecn.NumberOfLotsAffected); + parameters.Add("@RecipeChange", ecn.RecipeChange); + //RJK ITAR/EC + parameters.Add("@IsDocEC", ecn.IsDocEC); + db.Execute("ECNUpdate", parameters, commandType: CommandType.StoredProcedure); + + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + db.Execute("ECNDeleteAffectedDepartments", parameters, commandType: CommandType.StoredProcedure); + List ecnDepIDs = ecn.DepartmentIDs; + if (ecnDepIDs != null) { + foreach (int depId in ecnDepIDs) { + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + parameters.Add("@DepartmentID", depId); + db.Execute("ECNInsertAffectedDepartments", parameters, commandType: CommandType.StoredProcedure); + } + } + + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + db.Execute("ECNDeleteAffectedModules", parameters, commandType: CommandType.StoredProcedure); + + List ecnModuleIDs = ecn.ModuleIDs; + if (ecnModuleIDs != null) { + foreach (int moduleID in ecnModuleIDs) { + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + parameters.Add("@ModuleID", moduleID); + db.Execute("ECNInsertAffectedModules", parameters, commandType: CommandType.StoredProcedure); + } + } + + List ecnAreaIDs = ecn.AreaIDs; + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + db.Execute("ECNDeleteAffectedAreas", parameters, commandType: CommandType.StoredProcedure); + + if (ecnAreaIDs != null) { + foreach (int ecnAreaID in ecnAreaIDs) { + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + parameters.Add("@AreaID", ecnAreaID); + db.Execute("ECNInsertAffectedAreas", parameters, commandType: CommandType.StoredProcedure); + } + } + + List ecnTechnologyIDs = ecn.TechnologyIDs; + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + db.Execute("ECNDeleteAffectedTechnologies", parameters, commandType: CommandType.StoredProcedure); + + if (ecnTechnologyIDs != null) { + foreach (int ecnTechnologyID in ecnTechnologyIDs) { + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + + parameters.Add("@TechnologyID", ecnTechnologyID); + db.Execute("ECNInsertAffectedTechnologies", parameters, commandType: CommandType.StoredProcedure); + } + } + + List ecnAcknowledgementByIDs = ecn.AcknowledgementByIDs; + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + db.Execute("ECNDeleteAcknowledgementBy", parameters, commandType: CommandType.StoredProcedure); + + if (ecnAcknowledgementByIDs != null) { + foreach (int ecnAcknowledgementByID in ecnAcknowledgementByIDs) { + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + + parameters.Add("@AcknowledgementByID", ecnAcknowledgementByID); + db.Execute("ECNInsertAcknowledgementBy", parameters, commandType: CommandType.StoredProcedure); + } + } + + List ecnTrainingByIDs = ecn.TrainingByIDs; + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + db.Execute("ECNDeleteTrainingBy", parameters, commandType: CommandType.StoredProcedure); + + if (ecnTrainingByIDs != null) { + foreach (int ecnTrainingByID in ecnTrainingByIDs) { + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + + parameters.Add("@TrainingByID", ecnTrainingByID); + db.Execute("ECNInsertTrainingBy", parameters, commandType: CommandType.StoredProcedure); + } + } + + List ecnProductFamilyIDs = ecn.ProductFamilyIDs; + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + db.Execute("ECNDeleteAffectedProductFamilies", parameters, commandType: CommandType.StoredProcedure); + + if (ecnProductFamilyIDs != null) { + foreach (int ecnProductFamilyID in ecnProductFamilyIDs) { + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecn.ECNNumber); + + parameters.Add("@ProductFamilyID", ecnProductFamilyID); + db.Execute("ECNInsertAffectedProductFamilies", parameters, commandType: CommandType.StoredProcedure); + } + } + + transanction.Complete(); } } -} + + internal ECN GetECN(int ecnNumber, out int isITAR, int userID) { + /* IsITAR + 0 = false + 1 = true + 2 = not required + */ + isITAR = 2; + + ECN ecnItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", value: ecnNumber); + parameters.Add("@UserID", userID); + //parameters.Add("@UserID", GlobalVars.USER_ID); + parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + //StringBuilder query = new StringBuilder("ECNGetItem"); + + using (var multipleResultItems = db.QueryMultiple("ECNGetItem", parameters, commandType: CommandType.StoredProcedure)) { + ecnItem = multipleResultItems.Read().SingleOrDefault(); + + List departments = multipleResultItems.Read().ToList(); + if (ecnItem != null && departments != null) { + if (departments.Count > 0) + ecnItem.DepartmentIDs.AddRange(departments); + } + + List modules = multipleResultItems.Read().ToList(); + if (ecnItem != null && modules != null) { + if (modules.Count > 0) + ecnItem.ModuleIDs.AddRange(modules); + } + + List areas = multipleResultItems.Read().ToList(); + if (ecnItem != null && areas != null) { + if (areas.Count > 0) + ecnItem.AreaIDs.AddRange(areas); + } + + List technologies = multipleResultItems.Read().ToList(); + if (ecnItem != null && technologies != null) { + if (technologies.Count > 0) + ecnItem.TechnologyIDs.AddRange(technologies); + } + + List acknowledgmentby = multipleResultItems.Read().ToList(); + if (ecnItem != null && acknowledgmentby != null) { + if (acknowledgmentby.Count > 0) + ecnItem.AcknowledgementByIDs.AddRange(acknowledgmentby); + } + + List trainingby = multipleResultItems.Read().ToList(); + if (ecnItem != null && trainingby != null) { + if (trainingby.Count > 0) + ecnItem.TrainingByIDs.AddRange(trainingby); + } + + List productfamilies = multipleResultItems.Read().ToList(); + if (ecnItem != null && productfamilies != null) { + if (productfamilies.Count > 0) + ecnItem.ProductFamilyIDs.AddRange(productfamilies); + } + + } + + isITAR = parameters.Get("@IsITAR"); + + return ecnItem; + } + + public int PCRBExists(int pcrb) { + int result = 0; + ECN ecnItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@PCRB", value: pcrb); + parameters.Add("@Result", value: result, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + db.Execute("ECNPCRBExists", parameters, commandType: CommandType.StoredProcedure); + result = parameters.Get("@Result"); + + return result; + } + + internal ECN GetECNForRead(int ecnNumber, out int isITAR, int userID) { + /* IsITAR + 0 = false + 1 = true + 2 = not required + */ + isITAR = 2; + + ECN ecnItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", value: ecnNumber); + parameters.Add("@UserID", userID); + //parameters.Add("@UserID", GlobalVars.USER_ID); + parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + //StringBuilder query = new StringBuilder("ECNGetItem"); + + using (var multipleResultItems = db.QueryMultiple("ECNGetItemForRead", parameters, commandType: CommandType.StoredProcedure)) { + ecnItem = multipleResultItems.Read().SingleOrDefault(); + + List departments = multipleResultItems.Read().ToList(); + if (ecnItem != null && departments != null) { + if (departments.Count > 0) + ecnItem.DepartmentIDs.AddRange(departments); + } + + List modules = multipleResultItems.Read().ToList(); + if (ecnItem != null && modules != null) { + if (modules.Count > 0) + ecnItem.ModuleIDs.AddRange(modules); + } + + List areas = multipleResultItems.Read().ToList(); + if (ecnItem != null && areas != null) { + if (areas.Count > 0) + ecnItem.AreaIDs.AddRange(areas); + } + + List technologies = multipleResultItems.Read().ToList(); + if (ecnItem != null && technologies != null) { + if (technologies.Count > 0) + ecnItem.TechnologyIDs.AddRange(technologies); + } + + List acknowledgmentby = multipleResultItems.Read().ToList(); + if (ecnItem != null && acknowledgmentby != null) { + if (acknowledgmentby.Count > 0) + ecnItem.AcknowledgementByIDs.AddRange(acknowledgmentby); + } + + List trainingby = multipleResultItems.Read().ToList(); + if (ecnItem != null && trainingby != null) { + if (trainingby.Count > 0) + ecnItem.TrainingByIDs.AddRange(trainingby); + } + + List productfamilies = multipleResultItems.Read().ToList(); + if (ecnItem != null && productfamilies != null) { + if (productfamilies.Count > 0) + ecnItem.ProductFamilyIDs.AddRange(productfamilies); + } + + } + + isITAR = parameters.Get("@IsITAR"); + + return ecnItem; + } + + internal ECNPdf GetECNPdf(int ecnNumber) { + ECNPdf ecnItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", value: ecnNumber); + + //StringBuilder query = new StringBuilder("ECNGetItem"); + + using (var multipleResultItems = db.QueryMultiple("ECNGetPdfItem", parameters, commandType: CommandType.StoredProcedure)) { + ecnItem = multipleResultItems.Read().SingleOrDefault(); + + List departments = multipleResultItems.Read().ToList(); + //if (ecnItem != null && departments != null) + //{ + // if (departments.Count > 0) + // ecnItem.AffectedDepartments.AddRange(departments); + //} + + List modules = multipleResultItems.Read().ToList(); + //if (ecnItem != null && modules != null) + //{ + // if (modules.Count > 0) + // ecnItem.AffectedModules.AddRange(modules); + //} + + List attachments = multipleResultItems.Read().ToList(); + if (ecnItem != null && attachments != null) { + if (attachments.Count > 0) + ecnItem.Attachments.AddRange(attachments); + } + + List approvalLog = multipleResultItems.Read().ToList(); + if (ecnItem != null && approvalLog != null) { + if (approvalLog.Count > 0) + ecnItem.Approvalog.AddRange(approvalLog); + } + + List affectedAreas = multipleResultItems.Read().ToList(); + List affectedTechnologies = multipleResultItems.Read().ToList(); + List acknowledgementBy = multipleResultItems.Read().ToList(); + List trainingBy = multipleResultItems.Read().ToList(); + List productfamilies = multipleResultItems.Read().ToList(); + + ecnItem.AffectedModules = string.Join(", ", modules); + ecnItem.AffectedDepartments = string.Join(", ", departments); + ecnItem.AffectedAreas = string.Join(",", affectedAreas); + ecnItem.AffectedTechnologies = string.Join(",", affectedTechnologies); + ecnItem.TrainingBy = string.Join(",", trainingBy); + ecnItem.AcknowledgementBy = string.Join(",", acknowledgementBy); + ecnItem.AffectedProductFamilies = string.Join(",", productfamilies); + + } + return ecnItem; + } + + internal ECN GetECN(int ecnNumber) { + ECN ecnItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", value: ecnNumber); + + ecnItem = db.Query("ECNGetECNData", parameters, commandType: CommandType.StoredProcedure).Single(); + + return ecnItem; + } + + internal List GetDepartments() { + List departments = db.Query("ECNGetDepartments", null, commandType: CommandType.StoredProcedure).ToList(); + return departments; + } + + internal List GetModules() { + List modules = db.Query("ECNGetModules", null, commandType: CommandType.StoredProcedure).ToList(); + return modules; + } + + internal List GetCategories() { + List r = db.Query("ECNGetCategories", null, commandType: CommandType.StoredProcedure).ToList(); + return r; + } + + internal List GetECNAreas() { + StringBuilder query = new("SELECT AreaID , Area FROM ECNArea ORDER BY Area"); + return db.Query(query.ToString()).ToList(); + } + + /// + //internal List GetECNTechnology(int? areaId) + //{ + // var parameters = new DynamicParameters(); + // parameters.Add("@AreaId", value: areaId); + + // StringBuilder query = new StringBuilder("SELECT TechnologyID, Technology FROM ECNTechnology WHERE AreaID = @AreaId ORDER BY Technology"); + // return this.db.Query(query.ToString(), parameters ).ToList(); + + //} + + internal List GetECNTechnologies() { + DynamicParameters parameters = new(); + + StringBuilder query = new("SELECT DISTINCT TechnologyID, Technology FROM ECNTechnology ORDER BY Technology"); + return db.Query(query.ToString()).ToList(); + } + + internal List GetECNAcknowledgementTrainingBy() { + DynamicParameters parameters = new(); + + StringBuilder query = new("SELECT DISTINCT AcknowledgementTrainingByID, AcknowledgementTrainingBy FROM ECNAcknowledgementTrainingBy ORDER BY AcknowledgementTrainingBy"); + return db.Query(query.ToString()).ToList(); + } + + public IEnumerable GetECNAttachments(int ecnNumber) { + StringBuilder sql = new(); + sql.Append("SELECT A.AttachmentID, A.ECNNumber, A.FileName, A.UserID, CONVERT(VARCHAR(10), A.UploadDate, 101) AS UploadDate, U.FirstName + ' ' + U.LastName AS FullName "); + sql.Append("FROM ECNAttachment A INNER JOIN Users U ON A.UserID = U.UserID WHERE ECNNumber = @ECNNumber "); + List attachments = db.Query(sql.ToString(), new { ECNNumber = ecnNumber }).ToList(); + return attachments; + } + + public IEnumerable GetECNApprovalLogHistory(int ecnNumber) { + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", ecnNumber); + List approverList = db.Query("ECNGetECNApprovalLogHistory", parameters, commandType: CommandType.StoredProcedure).ToList(); + return approverList; + } + + public IEnumerable GetTECNNotificationUsers() { + string sql = "select T.UserId from TECNNotificationsUsers T"; + List result = db.Query(sql).ToList(); + return result; + } + + public void DeleteECNAttachment(int attachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@AttachmentID", attachmentID); + db.Execute("ECNDeleteAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + public void InsertECNAttachment(ECNAttachment attach) { + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", attach.ECNNumber); + parameters.Add("@UserID", attach.UserID); + parameters.Add("@FileName", attach.FileName); + + db.Execute("ECNInsertAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + public List GetRejectionOrginatorEmailList(int ecnNumber) { + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", ecnNumber); + List emailList = db.Query("ECNGetRejectionOrginatorEmailList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return emailList; + } + + public int SubmitDocument(int issueID, int userID, int documentType, out int allowedITAR) { + allowedITAR = 1; + string subRoles = ""; + if (documentType != (int)GlobalVars.DocumentType.EECN) + subRoles = wfDMO.GetSubRoleItems(issueID, documentType); + + // bubble the error + int appoverCount = 0; + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", issueID); + parameters.Add("@UserID", userID); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@SubRoleCategoriesClause", subRoles); + parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); + parameters.Add("@AllowedITAR", allowedITAR, dbType: DbType.Int32, direction: ParameterDirection.Output); + db.Execute("ECNSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); + + appoverCount = parameters.Get("@AppoverCount"); + allowedITAR = parameters.Get("@AllowedITAR"); + + return appoverCount; + } + + public int ReSubmitDocument(int issueID, int userID, int documentType, out int allowedITAR, string descriptionOfChange, string reasonForChange, string ecnTypeString, out int newECNNumber, int categoryId) { + newECNNumber = 0; + allowedITAR = 1; + string subRoles = ""; + if (documentType != (int)GlobalVars.DocumentType.EECN) + subRoles = wfDMO.GetSubRoleItems(issueID, documentType); + + // bubble the error + int appoverCount = 0; + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", issueID); + parameters.Add("@UserID", userID); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@SubRoleCategoriesClause", subRoles); + parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); + parameters.Add("@DescriptionOfChange", descriptionOfChange); + parameters.Add("@ReasonForChange", reasonForChange); + parameters.Add("@NewECNTypeString", ecnTypeString); + parameters.Add("NewECNNumber", newECNNumber, direction: ParameterDirection.Output); + parameters.Add("@CategoryID", categoryId); + db.Execute("ECNReSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); + + appoverCount = parameters.Get("@AppoverCount"); + //allowedITAR = parameters.Get("@AllowedITAR"); + newECNNumber = parameters.Get("@NewECNNumber"); + return appoverCount; + } + + public int SubmitForCancellation(int issueID, byte currentStep, int userID, int documentType, string ecnType, int TECNOperationType) { + string subRoles = ""; + if (documentType != (int)GlobalVars.DocumentType.EECN) + subRoles = wfDMO.GetSubRoleItems(issueID, documentType); + + // bubble the error + int appoverCount = 0; + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", issueID); + parameters.Add("@UserID", userID); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@ECNType", ecnType); + parameters.Add("@Step", currentStep); + parameters.Add("@SubRoleCategoriesClause", subRoles); + parameters.Add("@OperationType", TECNOperationType); + parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); + + db.Execute("ECNSubmitCancellation_Expiration", parameters, commandType: CommandType.StoredProcedure); + + appoverCount = parameters.Get("@AppoverCount"); + return appoverCount; + } + + public int SubmitTECNExtensionDocument(int issueID, int userID, int documentType, DateTime extensionDate) { + string subRoles = ""; + if (documentType != (int)GlobalVars.DocumentType.EECN) + subRoles = wfDMO.GetSubRoleItems(issueID, documentType); + + // bubble the error + int appoverCount = 0; + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", issueID); + parameters.Add("@UserID", userID); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@TECNExtensionDate", extensionDate); + parameters.Add("@SubRoleCategoriesClause", subRoles); + parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); + + db.Execute("ECN_TECNExtensionSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); + + appoverCount = parameters.Get("@AppoverCount"); + return appoverCount; + } + + public void SaveAfterSubmitByApprover(int ecnNumber, string implementationDetails) { + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", ecnNumber); + parameters.Add("@ImplementationDetails", implementationDetails); + + db.Execute("ECNSaveAfterSubmitByApprover", parameters, commandType: CommandType.StoredProcedure); + } + + public void TECNExtensionLog(int ecnNumber, DateTime extensionDate) { + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", ecnNumber); + parameters.Add("@ExtensionDate", extensionDate); + + db.Execute("ECN_TECNExtensionLogUpdate", parameters, commandType: CommandType.StoredProcedure); + } + + /// + /// Cancels the document before the approval loopmis closed + /// + + public void DeleteDocument(int ecnNumber, int userid, string ecnTypeString) { + DynamicParameters parameters = new(); + parameters.Add("@UserID", userid); + parameters.Add("@ECNNumber", ecnNumber); + parameters.Add("@ECNType", ecnTypeString); + + db.Execute("ECNDeleteDocument", parameters, commandType: CommandType.StoredProcedure); + } + + public void UpdateECNType(int ecnNumber, string ecnType) { + string updateSql = ""; + if (ecnType == "ECN") + updateSql = "UPDATE ECN SET IsECN = 1 , IsTECN = 0, IsEmergencyTECN = 0 WHERE ECNNumber = @ECNNumber "; + else if (ecnType == "TECN") + updateSql = "UPDATE ECN SET IsECN = 0 , IsTECN = 1, IsEmergencyTECN = 0 WHERE ECNNumber = @ECNNumber "; + + db.Execute(updateSql, new { ECNNumber = ecnNumber }, commandType: CommandType.Text); + } + + public void SetToExecutionStep(int ecnNumber, int userid, int documentType, string ecnTypeString) { + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", ecnNumber); + parameters.Add("@UserID", userid); + parameters.Add("@DocumentType", documentType); + parameters.Add("@ECNType", ecnTypeString); + + db.Execute("ECNSetToExecutionStep", parameters, commandType: CommandType.StoredProcedure); + } + + public bool ECNApproveCancelled_ExpiredDocument(int issueID, byte step, string comments, out bool lastStep, int userID, int documentType) { + string subRolesInClause = wfDMO.GetSubRoleItems(issueID, documentType); + + lastStep = false; + bool lastApproverInCurrentStep = false; + + DynamicParameters parameters = new(); + parameters.Add("@IssueID", issueID); + parameters.Add("@CurrentStep", step); + parameters.Add("@ItemStatus", (int)GlobalVars.ApprovalOption.Approved); + parameters.Add("@UserID", userID); + parameters.Add("@Comments", comments); + parameters.Add("@SubRoleCategoriesClause", subRolesInClause); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@LastStep", lastStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); + parameters.Add("@LastApproverInCurrentStep", lastApproverInCurrentStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); + + db.Execute("UpdateApproval", parameters, commandType: CommandType.StoredProcedure); + + lastStep = parameters.Get("@LastStep"); + lastApproverInCurrentStep = parameters.Get("@LastApproverInCurrentStep"); + + return lastApproverInCurrentStep; + } + + public IEnumerable GetECN_TECNPendingApprovals(int userID) { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + List data = db.Query("ECNGetECN_TECNPendingApprovalsByOriginator", new { userID }, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetMyExpiredTECNs(int userID, int maxDays) { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + List data = db.Query("ECNGetExpiredTECNByOriginator", new { userID, maxDays }, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetAllTECNs() { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + List data = db.Query("ECNGetAllTECN", commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetMyConvertedTECNsToECNs(int userID, int maxDays) { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + List data = db.Query("ECNGetTECNConvertedToECNByOriginator", new { userID, maxDays }, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetMyExpiringTECNs(int userID, int maxDays) { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + List data = db.Query("ECNGetExpiringTECNByOriginator", new { userID, maxDays }, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public void CancelECN(int? ecnNumber) { + DynamicParameters parameters = new(); + parameters.Add("@IssueID", ecnNumber); + + db.Execute("ECNCancelECN", parameters, commandType: CommandType.StoredProcedure); + } + + public void ECNResetTECNAtRejection(int ecnNumber, int userID, int docType) { + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", ecnNumber); + parameters.Add("@UserID", userID); + parameters.Add("@DocumentTypeID", docType); + + db.Execute("ECNResetTECNAtRejection", parameters, commandType: CommandType.StoredProcedure); + } + + public bool CanSubmitECN(int ecnNumber) { + bool tecnExtensionState = false; + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", ecnNumber); + parameters.Add("@TECNExtensionState", value: tecnExtensionState, dbType: DbType.Boolean, direction: ParameterDirection.InputOutput); + + db.Execute("ECNCanSubmitECN", parameters, commandType: CommandType.StoredProcedure); + + tecnExtensionState = parameters.Get("@TECNExtensionState"); + + return tecnExtensionState; + } + + public void ReleaseLockOnDocument(int userID, int issueID) { + DynamicParameters parameters = new(); + parameters.Add("@IssueID", issueID); + parameters.Add("@UserID", userID); + db.Execute("ECNReleaseLockOnECNDocuments", parameters, commandType: CommandType.StoredProcedure); + } + + public string GetFileName(string attachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@AttachmentID", attachmentID); + var fileName = db.Query("ECNGetFileName", parameters, commandType: CommandType.StoredProcedure).Single(); + return fileName; + } + + public void ReassignOriginatorECN(int ecnNumber, int newOriginatorID, string comments, int userID) { + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", ecnNumber); + parameters.Add("@NewOriginatorID", newOriginatorID); + parameters.Add("@Comments", comments); + parameters.Add("@UserID", userID); + + db.Execute("ECNReassignOriginator", parameters, commandType: CommandType.StoredProcedure); + } + + internal List GetProductFamilies() { + List r = db.Query("ECNGetProductFamilies", null, commandType: CommandType.StoredProcedure).ToList(); + return r; + } + + public string AttachSave(AppSettings appSettings, int ecnNumber, string returnString, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + var fileName = Path.GetFileName(fullFileName); + + string ecnFolderPath = appSettings.AttachmentFolder + "ECN\\" + ecnNumber.ToString(); + + DirectoryInfo di = new(ecnFolderPath); + if (!di.Exists) + try { + di.Create(); + } catch { + returnString = "Error creating ECN directory."; + } + if (returnString == "") { + var physicalPath = Path.Combine(ecnFolderPath, fileName); + if (!File.Exists(physicalPath)) { + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + ECNAttachment attach = new() { + ECNNumber = ecnNumber, + FileName = fileName, + UserID = userId, + }; + if (File.Exists(physicalPath)) { + InsertECNAttachment(attach); + } else { + returnString = "File was not uploaded to server."; + } + } else { + returnString = "Cannot have duplicate file names."; + } + } + + return returnString; + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/EventLogDMO.cs b/Fab2ApprovalSystem/DMO/EventLogDMO.cs index 0843e05..9763203 100644 --- a/Fab2ApprovalSystem/DMO/EventLogDMO.cs +++ b/Fab2ApprovalSystem/DMO/EventLogDMO.cs @@ -1,51 +1,25 @@ -using System; -using System.Collections.Generic; -using System.Configuration; using System.Data; using System.Data.SqlClient; -using System.Linq; -using System.Text; -using System.Web; -using Fab2ApprovalSystem.Models; + using Dapper; -using System.Transactions; -using Fab2ApprovalSystem.ViewModels; -using System.Reflection; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.DMO -{ +namespace Fab2ApprovalSystem.DMO; - public static class EventLogDMO - { - private static IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - - //public static void Add(WinEventLog eventLog) - //{ - // var parameters = new DynamicParameters(); - // parameters.Add("@IssueID", eventLog.IssueID); - // parameters.Add("@UserID", eventLog.UserID); - // parameters.Add("@OperationType", eventLog.OperationType); - // parameters.Add("@Comments", eventLog.Comments); - - // db.Execute("InsertEventLog", parameters, commandType: CommandType.StoredProcedure); - - //} - - - public static void Add(WinEventLog eventLog) - { - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", eventLog.IssueID); - parameters.Add("@UserID", eventLog.UserID); - parameters.Add("@DocumentType", eventLog.DocumentType); - parameters.Add("@OperationType", eventLog.OperationType); - parameters.Add("@Comments", eventLog.Comments); - - db.Execute("InsertEventLogByDocument", parameters, commandType: CommandType.StoredProcedure); - - } +public static class EventLogDMO { + private static readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + public static void Add(WinEventLog eventLog) { + DynamicParameters parameters = new(); + parameters.Add("@IssueID", eventLog.IssueID); + parameters.Add("@UserID", eventLog.UserID); + parameters.Add("@DocumentType", eventLog.DocumentType); + parameters.Add("@OperationType", eventLog.OperationType); + parameters.Add("@Comments", eventLog.Comments); + db.Execute("InsertEventLogByDocument", parameters, commandType: CommandType.StoredProcedure); } -} + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/LotDispositionDMO.cs b/Fab2ApprovalSystem/DMO/LotDispositionDMO.cs index a2531a5..4a75255 100644 --- a/Fab2ApprovalSystem/DMO/LotDispositionDMO.cs +++ b/Fab2ApprovalSystem/DMO/LotDispositionDMO.cs @@ -2,1422 +2,1095 @@ using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; +using System.IO; using System.Linq; -using System.Text; -using Fab2ApprovalSystem.Models; -using Dapper; -using System.Transactions; -using Fab2ApprovalSystem.ViewModels; using System.Reflection; +using System.Text; +using System.Transactions; + +using Dapper; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.ViewModels; -namespace Fab2ApprovalSystem.DMO { - public class LotDispositionDMO - { - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); +namespace Fab2ApprovalSystem.DMO; - //LotDispositionDMO ldDMO = new LotDispositionDMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); +public class LotDispositionDMO { - public IEnumerable GetTaskList(int userID) - { - // eventually, the View Model will refer to a generic task list instead of the just Lot Disposition Items - //var lotDispostions = this.db.Query("GetLotDispositionsByUser", new { UserID = userID }, commandType: CommandType.StoredProcedure).ToList(); + private readonly AppSettings _AppSettings; + private readonly WorkflowDMO wfDMO = new(); + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); + public LotDispositionDMO(AppSettings appSettings) => + _AppSettings = appSettings; - var lotDispostions = this.db.Query("GetTaskListByUser", parameters, commandType: CommandType.StoredProcedure).ToList(); - return lotDispostions; - } + public IEnumerable GetTaskList(int userID) { + // eventually, the View Model will refer to a generic task list instead of the just Lot Disposition Items + //var lotDispostions = this.db.Query("GetLotDispositionsByUser", new { UserID = userID }, commandType: CommandType.StoredProcedure).ToList(); + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); - /// - /// - /// - /// - /// - public IEnumerable GetMyOpenActionItems(int userID) - { - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); + List lotDispostions = db.Query("GetTaskListByUser", parameters, commandType: CommandType.StoredProcedure).ToList(); + return lotDispostions; + } - var lotDispostions = this.db.Query("GetOpenActionItemsByUser", parameters, commandType: CommandType.StoredProcedure).ToList(); - return lotDispostions; - } + public IEnumerable GetMyOpenActionItems(int userID) { + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + List lotDispostions = db.Query("GetOpenActionItemsByUser", parameters, commandType: CommandType.StoredProcedure).ToList(); + return lotDispostions; + } - /// - /// - /// - /// - public IEnumerable GetLotDispositions() - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var lotDispostions = this.db.Query("GetLotDispositions", null, commandType: CommandType.StoredProcedure).ToList(); - return lotDispostions; - } + public IEnumerable GetLotDispositions() { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + List lotDispostions = db.Query("GetLotDispositions", null, commandType: CommandType.StoredProcedure).ToList(); + return lotDispostions; + } - /// - /// - /// - /// - public IEnumerable GetDocuments() - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var lotDispostions = this.db.Query("GetDocuments", null, commandType: CommandType.StoredProcedure).ToList(); - return lotDispostions; - } + public IEnumerable GetDocuments() { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + List lotDispostions = db.Query("GetDocuments", null, commandType: CommandType.StoredProcedure).ToList(); + return lotDispostions; + } + public IEnumerable GetWorkRequests() { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + List workReqs = db.Query("LTGetWorkRequests", null, commandType: CommandType.StoredProcedure).ToList(); + return workReqs; + } - /// - /// - /// - /// - public IEnumerable GetWorkRequests() - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var workReqs = this.db.Query("LTGetWorkRequests", null, commandType: CommandType.StoredProcedure).ToList(); - return workReqs; - } + public IEnumerable GetAuditList(int userID) { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + List al = db.Query("_8DGetAuditList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return al; + } + public IEnumerable GetCorrectiveActionList(int userID) { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + List cal = db.Query("_8DGetCorrectiveActionList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return cal; + } - /// - /// - /// - /// - public IEnumerable GetAuditList(int userID) - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - var al = this.db.Query("_8DGetAuditList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return al; - } + public IEnumerable GetChangeControls(int userID) { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + List cc = db.Query("CCGetChangeControlList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return cc; + } + public IEnumerable GetMRBList(int userID) { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + List cc = db.Query("MRBGetMRBList", null, commandType: CommandType.StoredProcedure).ToList(); + return cc; + } - /// - /// - /// - /// - /// - public IEnumerable GetCorrectiveActionList(int userID) - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - var cal = this.db.Query("_8DGetCorrectiveActionList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return cal; - } + public IEnumerable GetECNList(int userID) { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + List cc = db.Query("ECNGetECNList", null, commandType: CommandType.StoredProcedure).ToList(); + return cc; + } - /// - /// - /// - /// - /// - public IEnumerable GetChangeControls(int userID) - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - var cc = this.db.Query("CCGetChangeControlList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return cc; - } + public IEnumerable GetLotDispositionList(int userID) { + // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + List cc = db.Query("GetLotDispositionList", null, commandType: CommandType.StoredProcedure).ToList(); + return cc; + } - public IEnumerable GetMRBList(int userID) - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - var cc = this.db.Query("MRBGetMRBList", null, commandType: CommandType.StoredProcedure).ToList(); - return cc; - } + public LotDisposition GetLotDispositionItem(int issueID, out int isITAR, int userID) { + /* IsITAR + 0 = false + 1 = true + 2 = not required + */ + isITAR = 2; + LotDisposition issueItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@IssueID", value: issueID); + parameters.Add("@UserID", userID); + //parameters.Add("@UserID", GlobalVars.USER_ID); + parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - public IEnumerable GetECNList(int userID) - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - var cc = this.db.Query("ECNGetECNList", null, commandType: CommandType.StoredProcedure).ToList(); - return cc; - } - - - - public IEnumerable GetLotDispositionList(int userID) - { - // later on the View Model will refer to a generic task list instead of the just Lot Disposition Items - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - var cc = this.db.Query("GetLotDispositionList", null, commandType: CommandType.StoredProcedure).ToList(); - return cc; - } - - - - - /// - /// - /// - /// - /// - /// - /// - public LotDisposition GetLotDispositionItem(int issueID, out int isITAR, int userID) - { - /* IsITAR - 0 = false - 1 = true - 2 = not required - */ - isITAR = 2; - var issueItem = new LotDisposition(); - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", value: issueID); - parameters.Add("@UserID", userID); - //parameters.Add("@UserID", GlobalVars.USER_ID); - parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - using (var multipleResultItems = this.db.QueryMultiple("GetLotDispositionItem", parameters, commandType: CommandType.StoredProcedure)) - { - issueItem = multipleResultItems.Read().SingleOrDefault(); - - - var departments = multipleResultItems.Read().ToList(); - if (issueItem != null && departments != null) - { - issueItem.DepartmentIDs.AddRange(departments); - } - - - isITAR = parameters.Get("@IsITAR"); - + using (var multipleResultItems = db.QueryMultiple("GetLotDispositionItem", parameters, commandType: CommandType.StoredProcedure)) { + issueItem = multipleResultItems.Read().SingleOrDefault(); + List departments = multipleResultItems.Read().ToList(); + if (issueItem != null && departments != null) { + issueItem.DepartmentIDs.AddRange(departments); } - return issueItem; + + isITAR = parameters.Get("@IsITAR"); + } + return issueItem; + } + public LotDisposition GetLotDispositionItemForRead(int issueID, out int isITAR, int userID) { + /* IsITAR + 0 = false + 1 = true + 2 = not required + */ + isITAR = 2; + LotDisposition issueItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@IssueID", value: issueID); + parameters.Add("@UserID", userID); + //parameters.Add("@UserID", GlobalVars.USER_ID); + parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - /// - /// - /// - /// - /// - /// - /// - public LotDisposition GetLotDispositionItemForRead(int issueID, out int isITAR, int userID) - { - /* IsITAR - 0 = false - 1 = true - 2 = not required - */ - isITAR = 2; - var issueItem = new LotDisposition(); - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", value: issueID); - parameters.Add("@UserID", userID); - //parameters.Add("@UserID", GlobalVars.USER_ID); - parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - using (var multipleResultItems = this.db.QueryMultiple("GetLotDispositionItemForRead", parameters, commandType: CommandType.StoredProcedure)) - { - issueItem = multipleResultItems.Read().SingleOrDefault(); - - - var departments = multipleResultItems.Read().ToList(); - if (issueItem != null && departments != null) - { - issueItem.DepartmentIDs.AddRange(departments); - } - - - isITAR = parameters.Get("@IsITAR"); - + using (var multipleResultItems = db.QueryMultiple("GetLotDispositionItemForRead", parameters, commandType: CommandType.StoredProcedure)) { + issueItem = multipleResultItems.Read().SingleOrDefault(); + List departments = multipleResultItems.Read().ToList(); + if (issueItem != null && departments != null) { + issueItem.DepartmentIDs.AddRange(departments); } - return issueItem; + + isITAR = parameters.Get("@IsITAR"); + } + return issueItem; + } - /// - /// - /// - /// - /// - public int GetRHLotCount(int issueID) - { - StringBuilder query = new StringBuilder("SELECT COUNT(*) FROM dbo.fnGetLot_RH(@IssueID) "); - //query.Append("WHERE UserID = @UserID AND AND EmployeeStatus = 'Active'"); - return this.db.Query(query.ToString(), new { IssueID = issueID }).SingleOrDefault(); - } + public int GetRHLotCount(int issueID) { + StringBuilder query = new("SELECT COUNT(*) FROM dbo.fnGetLot_RH(@IssueID) "); + //query.Append("WHERE UserID = @UserID AND AND EmployeeStatus = 'Active'"); + return db.Query(query.ToString(), new { IssueID = issueID }).SingleOrDefault(); + } - - /// - /// - /// - /// - public List GetDepartments() - { + public List GetDepartments() { + List departments = db.Query("GetLotDispositionDepartments", null, commandType: CommandType.StoredProcedure).ToList(); + return departments; + } - var departments = this.db.Query("GetLotDispositionDepartments", null, commandType: CommandType.StoredProcedure).ToList(); - return departments; - - } + #region LotDisposition + public LotDisposition InsertLotDisposition(LotDisposition lotDispo) { + DynamicParameters parameters = new(); + using (TransactionScope transanction = new()) { + // Lot Disposition + parameters = new DynamicParameters(); + parameters.Add("@IssueID", value: lotDispo.IssueID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@Title", lotDispo.Title); + parameters.Add("@IssueDescription", lotDispo.IssueDescription); + parameters.Add("@PERequired", lotDispo.PERequired); + parameters.Add("@ResponsibilityID", lotDispo.ResponsibilityID); + parameters.Add("@IssueDate", lotDispo.IssueDate); + parameters.Add("@OriginatorID", lotDispo.OriginatorID); + parameters.Add("@ReasonForDisposition", lotDispo.ReasonForDisposition); + parameters.Add("@ResponsibilityIssueID", lotDispo.ResponsibilityIssueID); + parameters.Add("@SPNScrapCode", lotDispo.SPNScrapCode); + parameters.Add("@CurrentStep", lotDispo.CurrentStep); - #region LotDisposition - public LotDisposition InsertLotDisposition(LotDisposition lotDispo) - { - var parameters = new DynamicParameters(); - using (var transanction = new TransactionScope()) - { - // Lot Disposition - parameters = new DynamicParameters(); - parameters.Add("@IssueID", value: lotDispo.IssueID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@Title", lotDispo.Title); - parameters.Add("@IssueDescription", lotDispo.IssueDescription); - parameters.Add("@PERequired", lotDispo.PERequired); - parameters.Add("@ResponsibilityID", lotDispo.ResponsibilityID); - parameters.Add("@IssueDate", lotDispo.IssueDate); - parameters.Add("@OriginatorID", lotDispo.OriginatorID); - parameters.Add("@ReasonForDisposition", lotDispo.ReasonForDisposition); - parameters.Add("@ResponsibilityIssueID", lotDispo.ResponsibilityIssueID); - parameters.Add("@SPNScrapCode", lotDispo.SPNScrapCode); - parameters.Add("@CurrentStep", lotDispo.CurrentStep); + db.Execute("InsertLotDisposition", parameters, commandType: CommandType.StoredProcedure); + lotDispo.IssueID = parameters.Get("@IssueID"); - this.db.Execute("InsertLotDisposition", parameters, commandType: CommandType.StoredProcedure); - lotDispo.IssueID = parameters.Get("@IssueID"); + // Lot Update + //parameters = new DynamicParameters(); + //IEnumerable lots = lotDispo.Lots; + //foreach (Lot lot in lots) + //{ + // parameters = new DynamicParameters(); + // parameters.Add("@LotNumber", lot.LotNumber); + // parameters.Add("@IssueID", lotDispo.IssueID); + // parameters.Add("@Description", lot.Description); + // parameters.Add("@NewPartNo", lot.NewPartNo); + // parameters.Add("@WipPartNo", lot.WipPartNo); + // parameters.Add("@DiePartNo", lot.DiePartNo); + // parameters.Add("@ProductFamily", lot.ProductFamily); + // parameters.Add("@Gen", lot.Gen); - // Lot Update + // parameters.Add("@Channel", lot.Channel); + // parameters.Add("@Hexsize", lot.Hexsize); - //parameters = new DynamicParameters(); - //IEnumerable lots = lotDispo.Lots; - //foreach (Lot lot in lots) - //{ - // parameters = new DynamicParameters(); - // parameters.Add("@LotNumber", lot.LotNumber); - // parameters.Add("@IssueID", lotDispo.IssueID); - // parameters.Add("@Description", lot.Description); - // parameters.Add("@NewPartNo", lot.NewPartNo); - // parameters.Add("@WipPartNo", lot.WipPartNo); - // parameters.Add("@DiePartNo", lot.DiePartNo); - // parameters.Add("@ProductFamily", lot.ProductFamily); - // parameters.Add("@Gen", lot.Gen); + // parameters.Add("@Voltage", lot.Voltage); + // parameters.Add("@WaferCount", lot.WaferCount); + // parameters.Add("@DieCount", lot.DieCount); - // parameters.Add("@Channel", lot.Channel); - // parameters.Add("@Hexsize", lot.Hexsize); + // parameters.Add("@Location", lot.Location); + // parameters.Add("@TotalCost", lot.TotalCost); + // parameters.Add("@LotStatusOptionID", lot.LotStatusOption.LotStatusOptionID); - // parameters.Add("@Voltage", lot.Voltage); - // parameters.Add("@WaferCount", lot.WaferCount); - // parameters.Add("@DieCount", lot.DieCount); + // this.db.Execute("InsertLot", parameters, commandType: CommandType.StoredProcedure); - // parameters.Add("@Location", lot.Location); - // parameters.Add("@TotalCost", lot.TotalCost); - // parameters.Add("@LotStatusOptionID", lot.LotStatusOption.LotStatusOptionID); + //} - // this.db.Execute("InsertLot", parameters, commandType: CommandType.StoredProcedure); + // LotDispoDepartment + List lotDispDepIDs = lotDispo.DepartmentIDs; - - //} - - - // LotDispoDepartment - List lotDispDepIDs = lotDispo.DepartmentIDs; - - if (lotDispDepIDs != null) - { - foreach (int depIds in lotDispDepIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@IssueID", depIds); - parameters.Add("@DepartMentID", lotDispo.IssueID); - this.db.Execute("InsertLotDispoDepartment", parameters, commandType: CommandType.StoredProcedure); - } + if (lotDispDepIDs != null) { + foreach (int depIds in lotDispDepIDs) { + parameters = new DynamicParameters(); + parameters.Add("@IssueID", depIds); + parameters.Add("@DepartMentID", lotDispo.IssueID); + db.Execute("InsertLotDispoDepartment", parameters, commandType: CommandType.StoredProcedure); } - - transanction.Complete(); - - return lotDispo; - - } - + + transanction.Complete(); + + return lotDispo; + } + } - /// - /// - /// - /// - /// - /// - public ScrapLot GetLotStausDetail(int issueID, string lotNumber) - { - return this.db.Query("SELECT L.WaferCount, S.* FROM ScrapLot S INNER JOIN Lot L ON S.IssueID = L.IssueID AND S.LotNo = L.LotNumber WHERE S.IssueID = @IssueID AND LotNo = @lotNumber", new { IssueID = issueID, lotNumber = lotNumber }).SingleOrDefault(); - } + public ScrapLot GetLotStausDetail(int issueID, string lotNumber) => + db.Query("SELECT L.WaferCount, S.* FROM ScrapLot S INNER JOIN Lot L ON S.IssueID = L.IssueID AND S.LotNo = L.LotNumber WHERE S.IssueID = @IssueID AND LotNo = @lotNumber", new { IssueID = issueID, lotNumber = lotNumber }).SingleOrDefault(); + public void UpdateLotDisposition(LotDisposition lotDispo) { + DynamicParameters parameters = new(); + using (TransactionScope transanction = new()) { + // Lot Disposition + parameters = new DynamicParameters(); + parameters.Add("@IssueID", lotDispo.IssueID); + parameters.Add("@Title", lotDispo.Title); + parameters.Add("@IssueDescription", lotDispo.IssueDescription); + parameters.Add("@PERequired", lotDispo.PERequired); + parameters.Add("@MRBRequired", lotDispo.MRBRequired); + parameters.Add("@DispositionByOCAP", lotDispo.DispositionByOCAP); + parameters.Add("@CANo", lotDispo.CANo); + parameters.Add("@ResponsibilityID", lotDispo.ResponsibilityID); + parameters.Add("@IssueDate", lotDispo.IssueDate); + parameters.Add("@ReasonForDisposition", lotDispo.ReasonForDisposition); + parameters.Add("@ResponsibilityIssueID", lotDispo.ResponsibilityIssueID); + parameters.Add("@SPNScrapCode", lotDispo.SPNScrapCode); - /// - /// - /// - /// - public void UpdateLotDisposition(LotDisposition lotDispo) - { - var parameters = new DynamicParameters(); - using (var transanction = new TransactionScope()) - { - // Lot Disposition + db.Execute("UpdateLotDisposition", parameters, commandType: CommandType.StoredProcedure); + + List lotDispDepIDs = lotDispo.DepartmentIDs; + + if (lotDispDepIDs != null) { parameters = new DynamicParameters(); parameters.Add("@IssueID", lotDispo.IssueID); - parameters.Add("@Title", lotDispo.Title); - parameters.Add("@IssueDescription", lotDispo.IssueDescription); - parameters.Add("@PERequired", lotDispo.PERequired); - parameters.Add("@MRBRequired", lotDispo.MRBRequired); - parameters.Add("@DispositionByOCAP", lotDispo.DispositionByOCAP); - parameters.Add("@CANo", lotDispo.CANo); - parameters.Add("@ResponsibilityID", lotDispo.ResponsibilityID); - parameters.Add("@IssueDate", lotDispo.IssueDate); - parameters.Add("@ReasonForDisposition", lotDispo.ReasonForDisposition); - parameters.Add("@ResponsibilityIssueID", lotDispo.ResponsibilityIssueID); - parameters.Add("@SPNScrapCode", lotDispo.SPNScrapCode); + db.Execute("DeleteLotDispositionDepartment", parameters, commandType: CommandType.StoredProcedure); - this.db.Execute("UpdateLotDisposition", parameters, commandType: CommandType.StoredProcedure); - - List lotDispDepIDs = lotDispo.DepartmentIDs; - - if (lotDispDepIDs != null) - { + foreach (int depIds in lotDispDepIDs) { parameters = new DynamicParameters(); parameters.Add("@IssueID", lotDispo.IssueID); - this.db.Execute("DeleteLotDispositionDepartment", parameters, commandType: CommandType.StoredProcedure); - - foreach (int depIds in lotDispDepIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@IssueID",lotDispo.IssueID ); - parameters.Add("@DepartmentID", depIds); - this.db.Execute("InsertLotDispositionDepartment", parameters, commandType: CommandType.StoredProcedure); - } - } - transanction.Complete(); - } - } - - #endregion - - #region LotDispoitio Lot - /// - /// - /// - /// - /// - public int InsertLot(Lot lot, bool getLotInfo) - { - if (getLotInfo) - { - MiscDMO.GetLotInformation(lot); - } - - var parameters = new DynamicParameters(); - parameters.Add("@LotID", value: lot.LotID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@LotNumber", lot.LotNumber); - parameters.Add("@DieLotNumber", lot.DieLotNumber); - parameters.Add("@IssueID", lot.IssueID); - parameters.Add("@Description", lot.Description); - parameters.Add("@NewPartNo", lot.NewPartNo); - parameters.Add("@WipPartNo", lot.WipPartNo); - parameters.Add("@DiePartNo", lot.DiePartNo); - parameters.Add("@ProductFamily", lot.ProductFamily); - parameters.Add("@Gen", lot.Gen); - - parameters.Add("@Channel", lot.Channel); - parameters.Add("@Hexsize", lot.Hexsize); - - parameters.Add("@Voltage", lot.Voltage); - parameters.Add("@WaferCount", lot.WaferCount); - parameters.Add("@DieCount", lot.DieCount); - - parameters.Add("@Location", lot.Location); - parameters.Add("@TotalCost", lot.TotalCost); - parameters.Add("@LotStatusOptionID", lot.LotStatusOption.LotStatusOptionID); - parameters.Add("@QualityCode", lot.QualityCode); - parameters.Add("@OpenIssueWithExistingLot", dbType: DbType.Int32, direction: ParameterDirection.Output); - - - this.db.Execute("InsertLotDispositionLot", parameters, commandType: CommandType.StoredProcedure); - - - int lotID = parameters.Get("@LotID"); - if (parameters.Get("@OpenIssueWithExistingLot") != 0) - { - - lot.OpenIssueWithExistingLots = parameters.Get("@OpenIssueWithExistingLot"); - } - - return lotID; - - } - - /// - /// - /// - /// - /// - public IEnumerable GetMRBsFromSPN(string lotNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@LotNo", lotNumber); - var mrbList = this.db.Query("GetMRBsFromSPN", parameters, commandType: CommandType.StoredProcedure).ToList(); - - - return mrbList; - - } - - /// - /// - /// - /// - public void InsertChildLot_NotInTheMRB(string lotNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@LotNo", lotNumber); - this.db.Execute("InsertChildLot_NotInTheMRB_LD", parameters, commandType: CommandType.StoredProcedure); - - } - - public void DeleteCADocument(int CANo, int userID, string caTypeString) - { - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - parameters.Add("@CANo", CANo); - parameters.Add("@CAType", caTypeString); - - this.db.Execute("_8DDeleteCADocument", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - - public void DeleteLotDispoLot(int lotID) - { - var parameters = new DynamicParameters(); - parameters.Add("@LotID", lotID); - this.db.Execute("DeleteLotDispositionLot", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - public void DeleteAllLotDispoLot(int issueID) - { - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID); - this.db.Execute("DeleteLotDispositionAllLots", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - public void UpdateLotDispoLot(Lot lot) - { - var parameters = new DynamicParameters(); - parameters.Add("@LotID", lot.LotID); - parameters.Add("@LotNumber", lot.LotNumber); - parameters.Add("@DieLotNumber", lot.DieLotNumber); - parameters.Add("@IssueID", lot.IssueID); - parameters.Add("@Description", lot.Description); - parameters.Add("@NewPartNo", lot.NewPartNo); - parameters.Add("@WipPartNo", lot.WipPartNo); - parameters.Add("@DiePartNo", lot.DiePartNo); - parameters.Add("@ProductFamily", lot.ProductFamily); - parameters.Add("@Gen", lot.Gen); - - parameters.Add("@Channel", lot.Channel); - parameters.Add("@Hexsize", lot.Hexsize); - - parameters.Add("@Voltage", lot.Voltage); - parameters.Add("@WaferCount", lot.WaferCount); - parameters.Add("@DieCount", lot.DieCount); - - parameters.Add("@Location", lot.Location); - parameters.Add("@TotalCost", lot.TotalCost); - parameters.Add("@LotStatusOptionID", lot.LotStatusOption.LotStatusOptionID); - - this.db.Execute("UpdateLotDispositionLot", parameters, commandType: CommandType.StoredProcedure); - - - // Update the Scrap Lot table ===================================================================== - ScrapLot sl = new ScrapLot(); - sl.IssueID = lot.IssueID; - sl.LotNo = lot.LotNumber; - sl.WaferCount = lot.WaferCount; - - foreach (PropertyInfo pi in sl.GetType().GetProperties()) - { - if (pi.Name.ToLower().StartsWith("lot") && pi.Name.ToLower().EndsWith("state")) - { - if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.Release) - pi.SetValue(sl, (byte)1, null); - else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.Scrap) - pi.SetValue(sl, (byte)2, null); - else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.NotAvailable) - pi.SetValue(sl, (byte)3, null); - else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.M_Suffix) - pi.SetValue(sl, (byte)4, null); - else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.Select_Wafers) - pi.SetValue(sl, (byte)5, null); - else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.CloseToQDB) - pi.SetValue(sl, (byte)6, null); - else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.SplitOffHold) - pi.SetValue(sl, (byte)7, null); + parameters.Add("@DepartmentID", depIds); + db.Execute("InsertLotDispositionDepartment", parameters, commandType: CommandType.StoredProcedure); } } - - // if the Lot Status is M_Suffix, the whole lot is automatically in a Release state per Hans - if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.Release - || lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.M_Suffix - || lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.CloseToQDB) - { - sl.ScrapCount = 0; - sl.ReleaseCount = lot.WaferCount > 0 ? lot.WaferCount : lot.DieCount; - lot.ScrapCount = 0; - lot.ReleaseCount = sl.ReleaseCount; - - - } - else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.Scrap) - { - sl.ScrapCount = lot.WaferCount > 0 ? lot.WaferCount : lot.DieCount; - sl.ReleaseCount = 0; - - lot.ScrapCount = lot.WaferCount > 0 ? lot.WaferCount : lot.DieCount; - lot.ReleaseCount = 0; - } - else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.SplitOffHold - || lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.NotAvailable) - { - sl.ScrapCount = 0; - sl.ReleaseCount = 0; - - lot.ScrapCount = 0; - lot.ReleaseCount = 0; - } - //else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.NotAvailable) - //{ - // sl.ScrapCount = 0; - // sl.ReleaseCount = 0; - - // lot.ScrapCount = 0; - // lot.ReleaseCount = 0; - //} - - UpdateLotScrapReleaseStatus(sl); - - - } - - /// - /// Updates the Lot object with additional info based on Lot data downlaoded from SPN - /// - /// - //void GetLotInformation(Lot lot) - //{ - // string qryLotInfo = "SELECT WP_LOT_NO, WP_PART_NUMBER, MP_PRODUCT_FAMILY, MP_DESCRIPTION, WP_CURRENT_QTY, WP_CURRENT_LOCATION, DieLotNumber, DiePartNo, DieCount FROM SPNLot WHERE WP_Lot_No = @LotNumber "; - // var lotInfoRow = this.db.Query(qryLotInfo, new { lot.LotNumber }).ToList(); - - // //lot.LotNumber = lotInfoRow.Get("@WP_LOT_NO"); - // //lot.WipPartNo = lotInfoRow.Get("@WP_Part_Number"); - // ////lotInfoRow.WP_LOT_NO; - // //lot.WipPartNo = lotInfoRow.WP_Part_Number; - - - // foreach (dynamic lotInfoColumn in lotInfoRow) - // { - - - // lot.LotNumber = lotInfoColumn.WP_LOT_NO; - // lot.DieLotNumber = lotInfoColumn.DieLotNumber; - - // if (lotInfoColumn.WP_PART_NUMBER != null) - // lot.WipPartNo = lotInfoColumn.WP_PART_NUMBER.Trim(); - - // if (lotInfoColumn.WP_CURRENT_LOCATION != null) - // { - // lot.Location = lotInfoColumn.WP_CURRENT_LOCATION; - // } - - - - - // if (lotInfoColumn.MP_DESCRIPTION != null) - // { - // lot.Description = lotInfoColumn.MP_DESCRIPTION; - // if (lot.Description.Length > 0) - // { - // string[] temp = lot.Description.Split(new char[] { ',' }); - // if (temp.Length > 0) - // { - // try - // { - // lot.ProductFamily = temp[0]; - // } - // catch { } // ignore the error - - // try - // { - // lot.Gen = double.Parse(temp[2].Substring(1,temp[2].Length - 1)); - // } - // catch { }// ignore the error - // try - // { - // lot.Hexsize = double.Parse(temp[6]); - // } - // catch { }// ignore the error - - // } - // } - // } - - // if (lotInfoColumn.DieCount != null) - // lot.DieCount = int.Parse(lotInfoColumn.DieCount.ToString()); - - // if (lotInfoColumn.DiePartNo != null) - // lot.DiePartNo = lotInfoColumn.DiePartNo.Trim(); - - // if (lotInfoColumn.WP_CURRENT_QTY != null) - // lot.WaferCount = lotInfoColumn.WP_CURRENT_QTY; - - // if (lot.WipPartNo.Length > 0 || lot.DiePartNo.Length > 0) - // { - // qryLotInfo = "SELECT DiePartNo, SourceFAB, Diameter, Silicon, Gen, Layers,HexSize,Voltage,Channel, Type AS ProductFamily, WaferCost, DieCost FROM FabApprovalSystem.dbo.StdCost WHERE WIPWaferNo = @WIPPartNo OR DiePartNo = @DiePartNo "; - // var moreLotInfoRow = this.db.Query(qryLotInfo, new { lot.WipPartNo, lot.DiePartNo }).ToList(); - - // foreach (var moreLotInfoColumn in moreLotInfoRow) - // { - // lot.DieCost = double.Parse(moreLotInfoColumn.DieCost.ToString()); - // lot.WaferCost = double.Parse(moreLotInfoColumn.WaferCost.ToString()); - - // if (moreLotInfoColumn.Channel != null) - // lot.Channel = moreLotInfoColumn.Channel; - - // //if (moreLotInfoColumn.ProductFamily != null) - // // lot.ProductFamily = moreLotInfoColumn.ProductFamily; - - // if (moreLotInfoColumn.Hexsize != null) - // lot.Hexsize = moreLotInfoColumn.Hexsize; - - // if (moreLotInfoColumn.Voltage != null) - // lot.Voltage = moreLotInfoColumn.Voltage; - - // //if (moreLotInfoColumn.Gen != null) - // // lot.Gen = moreLotInfoColumn.Gen; - - // if (lot.DieCount == 0) - // lot.TotalCost = Math.Round(lot.WaferCount * lot.WaferCost,2); - // else - // lot.TotalCost = Math.Round(lot.DieCount * lot.DieCost,2); - // } - - // } - - // } - - // //return lotStatusOption; - - //} - - #endregion - - public IEnumerable GetLotStatusOptions() - { - - var lotStatusOption = this.db.Query("SELECT * FROM LotStatusOption").ToList(); - return lotStatusOption; - - - } - - - /// - /// - /// - /// - /// - public IEnumerable GetLotDispositionLots(int issueID) - { - - // NOTE: Any new fields that needs to be added to select list , needs to be referenced prior to the "LS.LotStatusOptionID , LS.LotStatusOption" fields - - db.Open(); - #region Commented Code - /* - StringBuilder sql = new StringBuilder(); - sql.Append("SELECT DISTINCT SQ.IssueIDs AS MRBsLinkedToLot , DispoType.MRBDispoType, SQP.IssueIDs AS IssueIDWithoutMRB, "); - sql.Append("CASE WHEN L.LotStatusOptionID = 2 THEN 1 "); - sql.Append("WHEN PATINDEX('%B%', DispoType.MRBDispoType) > 0 AND L.LotStatusOptionID <> 2 THEN 0 "); - sql.Append("WHEN PATINDEX('%X%', DispoType.MRBDispoType) > 0 AND PATINDEX('%B%', DispoType.MRBDispoType) = 0 THEN 0 "); - - sql.Append("WHEN (PATINDEX('%D%', DispoType.MRBDispoType) > 0 "); - sql.Append(" AND PATINDEX('%X%', DispoType.MRBDispoType) = 0 "); - sql.Append(" AND PATINDEX('%B%', DispoType.MRBDispoType) = 0 "); - sql.Append(" AND LS.LotStatusOptionID <> 6 ) "); - sql.Append(" AND (LTRIM(RTRIM(Location)) <> 'QDB' AND LTRIM(RTRIM(Location)) <> 'EDB') THEN 0 "); - - sql.Append("ELSE 1 "); - sql.Append("END AS GoodToSubmit, "); - - sql.Append("CASE WHEN L.LotStatusOptionID = 2 THEN 'NA' "); - sql.Append("WHEN (PATINDEX('%B%', DispoType.MRBDispoType) > 0 AND L.LotStatusOptionID <> 2) "); - sql.Append("OR ( "); - sql.Append(" (PATINDEX('%D%', DispoType.MRBDispoType) > 0 "); - sql.Append(" AND PATINDEX('%X%', DispoType.MRBDispoType) = 0 "); - sql.Append(" AND PATINDEX('%B%', DispoType.MRBDispoType) = 0 "); - sql.Append(" AND LS.LotStatusOptionID <> 6 AND (LTRIM(RTRIM(Location)) <> 'QDB' AND LTRIM(RTRIM(Location)) <> 'EDB')) "); - sql.Append(" )"); - sql.Append(" THEN 'MRB Disposition different from Lot Dispostion' "); - - sql.Append("WHEN PATINDEX('%X%', DispoType.MRBDispoType) > 0 AND PATINDEX('%B%', DispoType.MRBDispoType) = 0 THEN 'MRB Dispo missing' "); - sql.Append("ELSE 'NA' "); - sql.Append("END AS SubmitErrorMessage, "); - - sql.Append(" "); - sql.Append("L.LotID, L.LotNumber, L.IssueID ,L.DieLotNumber ,L.Description ,L.NewPartNo ,L.WipPartNo ,L.DiePartNo ,L.ProductFamily, "); - sql.Append("L.Gen ,L.Channel, L.HexSize, L.Voltage, L.WaferCount, L.DieCount, L.Location, L.TotalCost, L.LotStatusOptionID,"); - sql.Append("S.ReleaseCount, S.ScrapCount, L.QualityCode, LS.LotStatusOptionID , LS.LotStatusOption FROM Lot L "); - sql.Append("INNER JOIN LotStatusOption LS ON L.LotStatusOptionID = LS.LotStatusOptionID "); - sql.Append("LEFT JOIN ScrapLot S ON L.LotNumber = S.LotNo AND L.IssueID = S.IssueID "); - - sql.Append("LEFT JOIN "); - sql.Append("(SELECT DISTINCT L.LotID, STUFF "); - // Code changed 12/11/2019 RJK - //sql.Append("((SELECT DISTINCT ',' + CAST(ML.MRBNumber AS varchar(512)) "); - sql.Append("((SELECT DISTINCT ',' + CAST(ML.MRBNumber AS varchar(512)) + '_' + CAST(ISNULL(ML.DispoType,'') AS varchar(512)) "); - sql.Append("FROM vMRBLot ML "); - //sql.Append("WHERE SUBSTRING(LTRIM(RTRIM(L.LotNumber)),1,7) = SUBSTRING(LTRIM(RTRIM(ML.LotNumber)),1,7) "); - sql.Append("WHERE LTRIM(RTRIM(L.LotNumber)) = LTRIM(RTRIM(ML.LotNumber)) "); - sql.Append("FOR XML PATH('')), 1, 1, '') AS IssueIDs "); - sql.Append("FROM Lot L) AS SQ "); - sql.Append("ON L.LotID = SQ.LotID "); - - - sql.Append("LEFT JOIN "); - sql.Append("(SELECT DISTINCT L.LotID, STUFF "); - sql.Append("((SELECT DISTINCT ',' + CAST(ML.MRBNumber AS varchar(512)) "); - sql.Append("FROM vMRBLot ML "); - sql.Append("WHERE LTRIM(RTRIM(L.LotNumber)) = LTRIM(RTRIM(ML.LotNumber)) "); - sql.Append("FOR XML PATH('')), 1, 1, '') AS IssueIDs "); - sql.Append("FROM Lot L) AS SQP "); - sql.Append("ON L.LotID = SQP.LotID "); - - - sql.Append("LEFT JOIN "); - sql.Append("(SELECT DISTINCT L.LotID, STUFF "); - sql.Append("((SELECT DISTINCT ',' + CAST(ISNULL(ML.DispoType, 'X') AS varchar(512)) "); - sql.Append("FROM vMRBLot ML "); - sql.Append("WHERE LTRIM(RTRIM(L.LotNumber)) = LTRIM(RTRIM(ML.LotNumber)) "); - sql.Append("FOR XML PATH('')), 1, 1, '') AS MRBDispoType "); - sql.Append("FROM Lot L) AS DispoType "); - sql.Append("ON L.LotID = DispoType.LotID "); - - sql.Append("WHERE L.IssueID = " + issueID); - - var data = this.db.Query - (sql.ToString(), (lot, lotstatusoption) => - { - lot.LotStatusOption = lotstatusoption; - return lot; - }, - splitOn: "LotStatusOptionID").ToList(); - - */ - #endregion - - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID, DbType.Int32); - var data = this.db.Query - ("GetLotDispositionLots", (lot, lotstatusoption) => - { - lot.LotStatusOption = lotstatusoption; - return lot; - }, - param:parameters, - commandType: CommandType.StoredProcedure, - splitOn: "LotStatusOptionID").ToList(); - - return data; - - - } - - - public IEnumerable GetLotDispoAttachments(int issueID) - { - var attachments = this.db.Query("SELECT A.AttachmentID, A.IssueID, A.FileName, A.UserID, CONVERT(VARCHAR(10), A.UploadDate, 101) AS UploadDate, U.FirstName + ' ' + U.LastName AS FullName FROM Attachment A INNER JOIN Users U ON A.UserID = U.UserID WHERE IssueID = @IssueID ", new { IssueID = issueID }).ToList(); - return attachments; - } - - public void DeleteLotDispoAttachment(int attachmentID) - { - var parameters = new DynamicParameters(); - parameters.Add("@AttachmentID", attachmentID); - this.db.Execute("DeleteLotDispositionAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - public void InsertLotDispositionAttachment(Attachment attach) - { - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", attach.IssueID); - parameters.Add("@UserID", attach.UserID); - parameters.Add("@FileName", attach.FileName); - - this.db.Execute("InsertLotDispositionAttachment", parameters, commandType: CommandType.StoredProcedure); - - - } - - public IEnumerable SearchLots(string searchText) - { - - // string sql = "SELECT WP_LOT_NO AS LotNumber FROM SPNLot WHERE WP_LOT_NO LIKE '%" + searchText + "%' OR DieLotNumber LIKE '%" + searchText + "%'"; - string sql = "SELECT WP_LOT_NO AS LotNumber FROM SPNLot WHERE WP_LOT_NO LIKE '%" + searchText + "%' "; - var lotList = this.db.Query(sql).ToList(); - return lotList; - - - } - - - public IEnumerable GetUserList() - { - StringBuilder sql = new StringBuilder(); - sql.Append("SELECT FirstName + ' ' + LastName AS OriginatorName, U.UserID AS OriginatorID, FirstName "); - sql.Append("FROM Users U "); - sql.Append("ORDER BY FirstName"); - - return this.db.Query(sql.ToString()).ToList(); - } - - - - //public IEnumerable GetScrapIssueList() - //{ - // StringBuilder sql = new StringBuilder(); - // sql.Append("SELECT ScrapID, ScrapDescription "); - // sql.Append("FROM ScrapIssue "); - // sql.Append("ORDER BY ScrapDescription "); - - // return this.db.Query(sql.ToString()).ToList(); - //} - - - /// - /// - /// - /// - //public List GetResponsibilityAreaList() - //{ - - // var departments = this.db.Query("GetLotDispositionResponsibilityAreas", null, commandType: CommandType.StoredProcedure).ToList(); - // return departments; - - - //} - - /// - /// - /// - /// - public List GetResponsibilityList() - { - var departments = this.db.Query("SELECT ResponsibilityID, ResponsibilityName FROM Responsibility ORDER BY ResponsibilityName ", null, commandType: CommandType.Text).ToList(); - return departments; - } - - - /// - /// - /// - /// - /// - public List GetResponsibilityIssueList(int responsibilityID) - { - var respIssue = this.db.Query("SELECT ResponsibilityIssueID, Issue FROM ResponsibilityIssue WHERE ResponsibilityID = @ResponsibilityID ORDER BY Issue ", new { @ResponsibilityID = responsibilityID }, commandType: CommandType.Text).ToList(); - return respIssue; - } - - - /// - /// - /// - /// - public void UpdateLotScrapReleaseStatus(ScrapLot scrap) - { - - StringBuilder qryInsert = new StringBuilder(); - qryInsert.Append("DELETE FROM ScrapLot WHERE LotNo = @LotNo AND IssueID = @IssueID"); - qryInsert.Append(" INSERT INTO ScrapLot(LotNo,IssueID,ScrapCount,ReleaseCount, Lot1State,Lot2State,Lot3State,Lot4State,Lot5State,Lot6State,Lot7State,Lot8State,Lot9State,Lot10State, "); - qryInsert.Append(" Lot11State,Lot12State,Lot13State,Lot14State,Lot15State,Lot16State,Lot17State,Lot18State,Lot19State,Lot20State, "); - qryInsert.Append(" Lot21State,Lot22State,Lot23State,Lot24State,Lot25State,Lot26State,Lot27State,Lot28State,Lot29State,Lot30State, "); - qryInsert.Append(" Lot31State,Lot32State,Lot33State,Lot34State,Lot35State,Lot36State,Lot37State,Lot38State,Lot39State,Lot40State, "); - qryInsert.Append(" Lot41State,Lot42State,Lot43State,Lot44State,Lot45State,Lot46State,Lot47State,Lot48State,Lot49State,Lot50State) "); - qryInsert.Append(" VALUES(@LotNo,@IssueID,@ScrapCount,@ReleaseCount,@Lot1State,@Lot2State,@Lot3State,@Lot4State,@Lot5State,@Lot6State,@Lot7State,@Lot8State,@Lot9State,@Lot10State,"); - qryInsert.Append(" @Lot11State,@Lot12State,@Lot13State,@Lot14State,@Lot15State,@Lot16State,@Lot17State,@Lot18State,@Lot19State,@Lot20State,"); - qryInsert.Append(" @Lot21State,@Lot22State,@Lot23State,@Lot24State,@Lot25State,@Lot26State,@Lot27State,@Lot28State,@Lot29State,@Lot30State,"); - qryInsert.Append(" @Lot31State,@Lot32State,@Lot33State,@Lot34State,@Lot35State,@Lot36State,@Lot37State,@Lot38State,@Lot39State,@Lot40State,"); - qryInsert.Append(" @Lot41State,@Lot42State,@Lot43State,@Lot44State,@Lot45State,@Lot46State,@Lot47State,@Lot48State,@Lot49State,@Lot50State)"); - - var parameters = new DynamicParameters(); - parameters.Add("@LotNo", scrap.LotNo); - parameters.Add("@IssueID", scrap.IssueID); - parameters.Add("@ScrapCount", scrap.ScrapCount); - parameters.Add("@ReleaseCount", scrap.ReleaseCount); - parameters.Add("@Lot1State", scrap.Lot1State); - parameters.Add("@Lot2State", scrap.Lot2State); - parameters.Add("@Lot3State", scrap.Lot3State); - parameters.Add("@Lot4State", scrap.Lot4State); - parameters.Add("@Lot5State", scrap.Lot5State); - parameters.Add("@Lot6State", scrap.Lot6State); - parameters.Add("@Lot7State", scrap.Lot7State); - parameters.Add("@Lot8State", scrap.Lot8State); - parameters.Add("@Lot9State", scrap.Lot9State); - parameters.Add("@Lot10State", scrap.Lot10State); - parameters.Add("@Lot11State", scrap.Lot11State); - parameters.Add("@Lot12State", scrap.Lot12State); - parameters.Add("@Lot13State", scrap.Lot13State); - parameters.Add("@Lot14State", scrap.Lot14State); - parameters.Add("@Lot15State", scrap.Lot15State); - parameters.Add("@Lot16State", scrap.Lot16State); - parameters.Add("@Lot17State", scrap.Lot17State); - parameters.Add("@Lot18State", scrap.Lot18State); - parameters.Add("@Lot19State", scrap.Lot19State); - parameters.Add("@Lot20State", scrap.Lot20State); - parameters.Add("@Lot21State", scrap.Lot21State); - parameters.Add("@Lot22State", scrap.Lot22State); - parameters.Add("@Lot23State", scrap.Lot23State); - parameters.Add("@Lot24State", scrap.Lot24State); - parameters.Add("@Lot25State", scrap.Lot25State); - parameters.Add("@Lot26State", scrap.Lot26State); - parameters.Add("@Lot27State", scrap.Lot27State); - parameters.Add("@Lot28State", scrap.Lot28State); - parameters.Add("@Lot29State", scrap.Lot29State); - parameters.Add("@Lot30State", scrap.Lot30State); - parameters.Add("@Lot31State", scrap.Lot31State); - parameters.Add("@Lot32State", scrap.Lot32State); - parameters.Add("@Lot33State", scrap.Lot33State); - parameters.Add("@Lot34State", scrap.Lot34State); - parameters.Add("@Lot35State", scrap.Lot35State); - parameters.Add("@Lot36State", scrap.Lot36State); - parameters.Add("@Lot37State", scrap.Lot37State); - parameters.Add("@Lot38State", scrap.Lot38State); - parameters.Add("@Lot39State", scrap.Lot39State); - parameters.Add("@Lot40State", scrap.Lot40State); - parameters.Add("@Lot41State", scrap.Lot41State); - parameters.Add("@Lot42State", scrap.Lot42State); - parameters.Add("@Lot43State", scrap.Lot43State); - parameters.Add("@Lot44State", scrap.Lot44State); - parameters.Add("@Lot45State", scrap.Lot45State); - parameters.Add("@Lot46State", scrap.Lot46State); - parameters.Add("@Lot47State", scrap.Lot47State); - parameters.Add("@Lot48State", scrap.Lot48State); - parameters.Add("@Lot49State", scrap.Lot49State); - parameters.Add("@Lot50State", scrap.Lot50State); - - - this.db.Execute(qryInsert.ToString(), parameters, commandType: CommandType.Text); - - } - - - /// - /// - /// - /// - public void UpdateLotStatus(ScrapLot lotStatus) - { - //if all the wafers in a lot is either "RELEASE" or "SCRAP" from the "SELECT WAFERS SCREEN" set the Lot Status Option accodingly for the particula lot - int tempLotStatus; - if ((lotStatus.ReleaseCount == lotStatus.WaferCount || lotStatus.ScrapCount == lotStatus.WaferCount) && (lotStatus.ReleaseCount > 0 || lotStatus.WaferCount > 0)) - { - // set the LotStatus appropriately because the entire lot either is set to "RELEASE" or "SCRAP"' - tempLotStatus = lotStatus.ReleaseCount == lotStatus.WaferCount ? (int)GlobalVars.LotStatusOption.Release : (int)GlobalVars.LotStatusOption.Scrap; - - // Close to QDB is count as "Release" - if ((lotStatus.CloseToQDBCount == lotStatus.WaferCount) && (lotStatus.CloseToQDBCount > 0 || lotStatus.WaferCount > 0)) - { - tempLotStatus = (int)GlobalVars.LotStatusOption.CloseToQDB; - } - } - else if ((lotStatus.SplitOfHoldCount == lotStatus.WaferCount) && (lotStatus.SplitOfHoldCount > 0 || lotStatus.WaferCount > 0)) - { - tempLotStatus = (int)GlobalVars.LotStatusOption.SplitOffHold; - } - - - else - { - tempLotStatus = (int)GlobalVars.LotStatusOption.Select_Wafers; - } - var parameters = new DynamicParameters(); - parameters.Add("@LotNo", lotStatus.LotNo); - parameters.Add("@IssueID", lotStatus.IssueID); - parameters.Add("@LotStatus", tempLotStatus); - this.db.Execute("UpdateLotStatus", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// Update the Status of all the lots for a given Lot disposition document - /// - /// - public void UpdateLotStatusAll(ScrapLot scrap, int lotStatus) - { - - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", scrap.IssueID); - parameters.Add("@LotStatus", lotStatus); - parameters.Add("@ScrapCount", 0); - parameters.Add("@Lot1State", scrap.Lot1State); - parameters.Add("@Lot2State", scrap.Lot2State); - parameters.Add("@Lot3State", scrap.Lot3State); - parameters.Add("@Lot4State", scrap.Lot4State); - parameters.Add("@Lot5State", scrap.Lot5State); - parameters.Add("@Lot6State", scrap.Lot6State); - parameters.Add("@Lot7State", scrap.Lot7State); - parameters.Add("@Lot8State", scrap.Lot8State); - parameters.Add("@Lot9State", scrap.Lot9State); - parameters.Add("@Lot10State", scrap.Lot10State); - parameters.Add("@Lot11State", scrap.Lot11State); - parameters.Add("@Lot12State", scrap.Lot12State); - parameters.Add("@Lot13State", scrap.Lot13State); - parameters.Add("@Lot14State", scrap.Lot14State); - parameters.Add("@Lot15State", scrap.Lot15State); - parameters.Add("@Lot16State", scrap.Lot16State); - parameters.Add("@Lot17State", scrap.Lot17State); - parameters.Add("@Lot18State", scrap.Lot18State); - parameters.Add("@Lot19State", scrap.Lot19State); - parameters.Add("@Lot20State", scrap.Lot20State); - parameters.Add("@Lot21State", scrap.Lot21State); - parameters.Add("@Lot22State", scrap.Lot22State); - parameters.Add("@Lot23State", scrap.Lot23State); - parameters.Add("@Lot24State", scrap.Lot24State); - parameters.Add("@Lot25State", scrap.Lot25State); - parameters.Add("@Lot26State", scrap.Lot26State); - parameters.Add("@Lot27State", scrap.Lot27State); - parameters.Add("@Lot28State", scrap.Lot28State); - parameters.Add("@Lot29State", scrap.Lot29State); - parameters.Add("@Lot30State", scrap.Lot30State); - parameters.Add("@Lot31State", scrap.Lot31State); - parameters.Add("@Lot32State", scrap.Lot32State); - parameters.Add("@Lot33State", scrap.Lot33State); - parameters.Add("@Lot34State", scrap.Lot34State); - parameters.Add("@Lot35State", scrap.Lot35State); - parameters.Add("@Lot36State", scrap.Lot36State); - parameters.Add("@Lot37State", scrap.Lot37State); - parameters.Add("@Lot38State", scrap.Lot38State); - parameters.Add("@Lot39State", scrap.Lot39State); - parameters.Add("@Lot40State", scrap.Lot40State); - parameters.Add("@Lot41State", scrap.Lot41State); - parameters.Add("@Lot42State", scrap.Lot42State); - parameters.Add("@Lot43State", scrap.Lot43State); - parameters.Add("@Lot44State", scrap.Lot44State); - parameters.Add("@Lot45State", scrap.Lot45State); - parameters.Add("@Lot46State", scrap.Lot46State); - parameters.Add("@Lot47State", scrap.Lot47State); - parameters.Add("@Lot48State", scrap.Lot48State); - parameters.Add("@Lot49State", scrap.Lot49State); - parameters.Add("@Lot50State", scrap.Lot50State); - - - this.db.Execute("UpdateScrapLotAll", parameters, commandType: CommandType.StoredProcedure); - - } - - - public LotDispositionLotSummaryViewModel GetLotDispositionLotSummary(int issueID) - { - StringBuilder sql = new StringBuilder(); - sql.Append("SELECT L.WaferCount AS 'TotalWaferCount', L.DieCount AS 'TotalDieCount', L.TotalCost AS 'TotalCost', S.ScrapCount AS 'ScrapWaferCount', S.ReleaseCount AS 'ReleaseWaferCount', L.LotStatusOptionID AS 'LotStatusOption' "); - sql.Append("FROM ScrapLot S INNER JOIN Lot L ON S.IssueID = L.IssueID AND S.LotNo = L.LotNumber "); - sql.Append("WHERE S.IssueID = @issueID" ); - - var LotDispositionLotList = this.db.Query(sql.ToString(), new { issueID = issueID }).ToList(); - int lotCount = 0; - - int totalWaferScrapCount = 0; - int totalDieScrapCount = 0; - double totalScrapCost = 0; - - int totalWaferReleaseCount = 0; - int totalDieReleaseCount = 0; - double totalReleaseCost = 0; - - int releaseWaferCount = 0; - double releaseCost = 0; - int releaseDieCount = 0; - - int scrapWaferCount = 0; - double scrapCost = 0; - int scrapDieCount = 0; - - foreach (LotDispositionLotSummaryViewModel ld in LotDispositionLotList) - { - releaseWaferCount = 0; - releaseCost = 0; - releaseDieCount = 0; - - scrapWaferCount = 0; - scrapCost = 0; - scrapDieCount = 0; - - - // Wafer=================================================================== - if (ld.ScrapWaferCount > 0 && ld.TotalWaferCount > 0 && ld.TotalCost > 0) - { - scrapWaferCount = ld.ScrapWaferCount; - double perWaferCost = ld.TotalCost / ld.TotalWaferCount; - scrapCost = scrapWaferCount * perWaferCost; - } - else if (ld.ScrapWaferCount == 0) - { - scrapWaferCount = ld.ScrapWaferCount; - scrapCost = 0; - } - - - if (ld.ReleaseWaferCount > 0 && ld.TotalWaferCount > 0 && ld.TotalCost > 0) - { - releaseWaferCount = ld.ReleaseWaferCount; - double perWaferCost = ld.TotalCost / ld.TotalWaferCount; - releaseCost = releaseWaferCount * perWaferCost; - } - else if (ld.ReleaseWaferCount == 0) - { - releaseWaferCount = ld.ReleaseWaferCount; - releaseCost = 0; - } - - // Die =================================================================== - if ( - (ld.LotStatusOption == (int)GlobalVars.LotStatusOption.Release - || ld.LotStatusOption == (int)GlobalVars.LotStatusOption.M_Suffix - || ld.LotStatusOption == (int)GlobalVars.LotStatusOption.CloseToQDB ) - && ld.TotalDieCount > 0) - { - releaseDieCount = ld.TotalDieCount;// - releaseCost = ld.TotalCost; - } - - - if (ld.LotStatusOption == (int)GlobalVars.LotStatusOption.Scrap && ld.TotalDieCount > 0) - { - scrapDieCount = ld.TotalDieCount ;// - scrapCost = ld.TotalCost; - } - - - // Summarize - lotCount++; - totalWaferScrapCount = totalWaferScrapCount + scrapWaferCount; - totalWaferReleaseCount = totalWaferReleaseCount + releaseWaferCount; - - totalDieScrapCount = totalDieScrapCount + scrapDieCount; - totalDieReleaseCount = totalDieReleaseCount + releaseDieCount; - - totalScrapCost = totalScrapCost + scrapCost; - totalReleaseCost = totalReleaseCost + releaseCost; - } - - - //} - - - return new LotDispositionLotSummaryViewModel() - { - LotCount = lotCount, - ReleaseCost = String.Format("{0:C}", totalReleaseCost), - //Math.Round(totalReleaseCost, 2).ToString(, - ReleaseWaferCount = totalWaferReleaseCount, - ReleaseDieCount = totalDieReleaseCount, - ScrapCost = String.Format("{0:C}", totalScrapCost), - //Math.Round(totalScrapCost, 2), - ScrapWaferCount = totalWaferScrapCount, - ScrapDieCount = totalDieScrapCount - - }; - - } - - - public int SubmitDocument(int issueID, bool peRequired, bool mrbRequired, int userID) - { - string subRoles = wfDMO.GetSubRoleItems(issueID, (int)GlobalVars.DocumentType.LotDisposition); - - // bubble the error - int appoverCount = 0; - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID); - parameters.Add("@UserID", userID ); - parameters.Add("@PERequired", peRequired); - parameters.Add("@MRBRequired", mrbRequired); - parameters.Add("@DocumentTypeID", 1); // Lot Dispostion - parameters.Add("@SubRoleCategoriesClause", subRoles); - parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - - this.db.Execute("SubmitForApproval_LotDisposition", parameters, commandType: CommandType.StoredProcedure); - - appoverCount = parameters.Get("@AppoverCount"); - return appoverCount; - - } - - - - /// - /// NOT IN USE - /// - /// - /// - /// - //public List GetApproverEmailList(int issueID, byte step) - //{ - // var parameters = new DynamicParameters(); - // parameters.Add("@IssueID", issueID); - // parameters.Add("@Step", step); - // var emailList = this.db.Query("GetApproverEmailList", parameters, commandType: CommandType.StoredProcedure).ToList(); - // return emailList; - - //} - - - /// - /// - /// - /// - /// - public List GetRejectionOrginatorEmailList(int issueID) - { - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID); - var emailList = this.db.Query("GetRejectionOrginatorEmailList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return emailList; - - } - - - /// - /// - /// - /// - /// - public void UpdateReasonForDisposition(int issueID, string reasonForDisposition) - { - var parameters = new DynamicParameters(); - - parameters.Add("@IssueID", issueID); - parameters.Add("@ReasonForDisposition", reasonForDisposition); - this.db.Execute("UpdateReasonForDisposition", parameters, commandType: CommandType.StoredProcedure); - } - - - - public void InsertComments(int issueID, string comments, int commentedBy) - { - var parameters = new DynamicParameters(); - - parameters.Add("@IssueID", issueID); - parameters.Add("@Comments", comments); - parameters.Add("@CommentedBy", commentedBy); - this.db.Execute("InsertComments", parameters, commandType: CommandType.StoredProcedure); - } - - - - - /// - /// - /// - /// - internal void DeleteLotDisposition(int issueID) - { - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID); - this.db.Execute("DeleteLotDisposition", parameters, commandType: CommandType.StoredProcedure); - } - - - internal IEnumerable GetComments(int issueID) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - return db.Query("GetComments", new { @IssueID = issueID}, commandType: CommandType.StoredProcedure).ToList(); - - } - - - - // NOT IN USE - //public List GetApproversList(int issueID, byte step) - //{ - // var parameters = new DynamicParameters(); - // parameters.Add("@IssueID", issueID); - // parameters.Add("@Step", step); - // var approverList = this.db.Query("GetApproversList", parameters, commandType: CommandType.StoredProcedure).ToList(); - // return approverList; - //} - - //public List GetPendingApproversList(int issueID, byte step) - //{ - // var parameters = new DynamicParameters(); - // parameters.Add("@IssueID", issueID); - // parameters.Add("@Step", step); - // var approverList = this.db.Query("GetPendingApproversList", parameters, commandType: CommandType.StoredProcedure).ToList(); - // return approverList; - //} - - - /// - /// Not In USE - /// - /// - /// - /// - //public IEnumerable GetApprovedApproversList(int issueID, int currentStep) - //{ - - // return this.db.Query("GetApprovedApproversList", new { @IssueID = issueID, @Step = currentStep }, commandType: CommandType.StoredProcedure).ToList(); - - //} - - - /// - /// - /// - /// - /// - public void ReleaseLockOnDocument(int userID, int issueID) - { - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID); - parameters.Add("@UserID", userID); - this.db.Execute("ReleaseLockOnLotDispoDoc", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - /// - public string GetFileName(string attachmentID) - { - var parameters = new DynamicParameters(); - parameters.Add("@AttachmentID", attachmentID); - var fileName = this.db.Query("GetFileName", parameters, commandType: CommandType.StoredProcedure).Single(); - return fileName; + transanction.Complete(); } } -} + + #endregion + + #region LotDispoitio Lot + + public int InsertLot(Lot lot, bool getLotInfo) { + if (getLotInfo) { + MiscDMO.GetLotInformation(lot); + } + + DynamicParameters parameters = new(); + parameters.Add("@LotID", value: lot.LotID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@LotNumber", lot.LotNumber); + parameters.Add("@DieLotNumber", lot.DieLotNumber); + parameters.Add("@IssueID", lot.IssueID); + parameters.Add("@Description", lot.Description); + parameters.Add("@NewPartNo", lot.NewPartNo); + parameters.Add("@WipPartNo", lot.WipPartNo); + parameters.Add("@DiePartNo", lot.DiePartNo); + parameters.Add("@ProductFamily", lot.ProductFamily); + parameters.Add("@Gen", lot.Gen); + + parameters.Add("@Channel", lot.Channel); + parameters.Add("@Hexsize", lot.Hexsize); + + parameters.Add("@Voltage", lot.Voltage); + parameters.Add("@WaferCount", lot.WaferCount); + parameters.Add("@DieCount", lot.DieCount); + + parameters.Add("@Location", lot.Location); + parameters.Add("@TotalCost", lot.TotalCost); + parameters.Add("@LotStatusOptionID", lot.LotStatusOption.LotStatusOptionID); + parameters.Add("@QualityCode", lot.QualityCode); + parameters.Add("@OpenIssueWithExistingLot", dbType: DbType.Int32, direction: ParameterDirection.Output); + + db.Execute("InsertLotDispositionLot", parameters, commandType: CommandType.StoredProcedure); + + int lotID = parameters.Get("@LotID"); + if (parameters.Get("@OpenIssueWithExistingLot") != 0) { + lot.OpenIssueWithExistingLots = parameters.Get("@OpenIssueWithExistingLot"); + } + + return lotID; + } + + public IEnumerable GetMRBsFromSPN(string lotNumber) { + DynamicParameters parameters = new(); + parameters.Add("@LotNo", lotNumber); + List mrbList = db.Query("GetMRBsFromSPN", parameters, commandType: CommandType.StoredProcedure).ToList(); + + return mrbList; + } + + public void InsertChildLot_NotInTheMRB(string lotNumber) { + DynamicParameters parameters = new(); + parameters.Add("@LotNo", lotNumber); + db.Execute("InsertChildLot_NotInTheMRB_LD", parameters, commandType: CommandType.StoredProcedure); + } + + public void DeleteCADocument(int CANo, int userID, string caTypeString) { + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + parameters.Add("@CANo", CANo); + parameters.Add("@CAType", caTypeString); + + db.Execute("_8DDeleteCADocument", parameters, commandType: CommandType.StoredProcedure); + } + + public void DeleteLotDispoLot(int lotID) { + DynamicParameters parameters = new(); + parameters.Add("@LotID", lotID); + db.Execute("DeleteLotDispositionLot", parameters, commandType: CommandType.StoredProcedure); + } + + public void DeleteAllLotDispoLot(int issueID) { + DynamicParameters parameters = new(); + parameters.Add("@IssueID", issueID); + db.Execute("DeleteLotDispositionAllLots", parameters, commandType: CommandType.StoredProcedure); + } + + public void UpdateLotDispoLot(Lot lot) { + DynamicParameters parameters = new(); + parameters.Add("@LotID", lot.LotID); + parameters.Add("@LotNumber", lot.LotNumber); + parameters.Add("@DieLotNumber", lot.DieLotNumber); + parameters.Add("@IssueID", lot.IssueID); + parameters.Add("@Description", lot.Description); + parameters.Add("@NewPartNo", lot.NewPartNo); + parameters.Add("@WipPartNo", lot.WipPartNo); + parameters.Add("@DiePartNo", lot.DiePartNo); + parameters.Add("@ProductFamily", lot.ProductFamily); + parameters.Add("@Gen", lot.Gen); + + parameters.Add("@Channel", lot.Channel); + parameters.Add("@Hexsize", lot.Hexsize); + + parameters.Add("@Voltage", lot.Voltage); + parameters.Add("@WaferCount", lot.WaferCount); + parameters.Add("@DieCount", lot.DieCount); + + parameters.Add("@Location", lot.Location); + parameters.Add("@TotalCost", lot.TotalCost); + parameters.Add("@LotStatusOptionID", lot.LotStatusOption.LotStatusOptionID); + + db.Execute("UpdateLotDispositionLot", parameters, commandType: CommandType.StoredProcedure); + + // Update the Scrap Lot table ===================================================================== + ScrapLot sl = new(); + sl.IssueID = lot.IssueID; + sl.LotNo = lot.LotNumber; + sl.WaferCount = lot.WaferCount; + + foreach (PropertyInfo pi in sl.GetType().GetProperties()) { + if (pi.Name.ToLower().StartsWith("lot") && pi.Name.ToLower().EndsWith("state")) { + if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.Release) + pi.SetValue(sl, (byte)1, null); + else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.Scrap) + pi.SetValue(sl, (byte)2, null); + else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.NotAvailable) + pi.SetValue(sl, (byte)3, null); + else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.M_Suffix) + pi.SetValue(sl, (byte)4, null); + else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.Select_Wafers) + pi.SetValue(sl, (byte)5, null); + else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.CloseToQDB) + pi.SetValue(sl, (byte)6, null); + else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.SplitOffHold) + pi.SetValue(sl, (byte)7, null); + } + } + + // if the Lot Status is M_Suffix, the whole lot is automatically in a Release state per Hans + if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.Release + || lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.M_Suffix + || lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.CloseToQDB) { + sl.ScrapCount = 0; + sl.ReleaseCount = lot.WaferCount > 0 ? lot.WaferCount : lot.DieCount; + lot.ScrapCount = 0; + lot.ReleaseCount = sl.ReleaseCount; + + } else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.Scrap) { + sl.ScrapCount = lot.WaferCount > 0 ? lot.WaferCount : lot.DieCount; + sl.ReleaseCount = 0; + + lot.ScrapCount = lot.WaferCount > 0 ? lot.WaferCount : lot.DieCount; + lot.ReleaseCount = 0; + } else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.SplitOffHold + || lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.NotAvailable) { + sl.ScrapCount = 0; + sl.ReleaseCount = 0; + + lot.ScrapCount = 0; + lot.ReleaseCount = 0; + } + //else if (lot.LotStatusOption.LotStatusOptionID == (int)GlobalVars.LotStatusOption.NotAvailable) + //{ + // sl.ScrapCount = 0; + // sl.ReleaseCount = 0; + + // lot.ScrapCount = 0; + // lot.ReleaseCount = 0; + //} + + UpdateLotScrapReleaseStatus(sl); + } + + /// + /// Updates the Lot object with additional info based on Lot data downlaoded from SPN + /// + + //void GetLotInformation(Lot lot) + //{ + // string qryLotInfo = "SELECT WP_LOT_NO, WP_PART_NUMBER, MP_PRODUCT_FAMILY, MP_DESCRIPTION, WP_CURRENT_QTY, WP_CURRENT_LOCATION, DieLotNumber, DiePartNo, DieCount FROM SPNLot WHERE WP_Lot_No = @LotNumber "; + // var lotInfoRow = this.db.Query(qryLotInfo, new { lot.LotNumber }).ToList(); + + // //lot.LotNumber = lotInfoRow.Get("@WP_LOT_NO"); + // //lot.WipPartNo = lotInfoRow.Get("@WP_Part_Number"); + // ////lotInfoRow.WP_LOT_NO; + // //lot.WipPartNo = lotInfoRow.WP_Part_Number; + + // foreach (dynamic lotInfoColumn in lotInfoRow) + // { + + // lot.LotNumber = lotInfoColumn.WP_LOT_NO; + // lot.DieLotNumber = lotInfoColumn.DieLotNumber; + + // if (lotInfoColumn.WP_PART_NUMBER != null) + // lot.WipPartNo = lotInfoColumn.WP_PART_NUMBER.Trim(); + + // if (lotInfoColumn.WP_CURRENT_LOCATION != null) + // { + // lot.Location = lotInfoColumn.WP_CURRENT_LOCATION; + // } + + // if (lotInfoColumn.MP_DESCRIPTION != null) + // { + // lot.Description = lotInfoColumn.MP_DESCRIPTION; + // if (lot.Description.Length > 0) + // { + // string[] temp = lot.Description.Split(new char[] { ',' }); + // if (temp.Length > 0) + // { + // try + // { + // lot.ProductFamily = temp[0]; + // } + // catch { } // ignore the error + + // try + // { + // lot.Gen = double.Parse(temp[2].Substring(1,temp[2].Length - 1)); + // } + // catch { }// ignore the error + // try + // { + // lot.Hexsize = double.Parse(temp[6]); + // } + // catch { }// ignore the error + + // } + // } + // } + + // if (lotInfoColumn.DieCount != null) + // lot.DieCount = int.Parse(lotInfoColumn.DieCount.ToString()); + + // if (lotInfoColumn.DiePartNo != null) + // lot.DiePartNo = lotInfoColumn.DiePartNo.Trim(); + + // if (lotInfoColumn.WP_CURRENT_QTY != null) + // lot.WaferCount = lotInfoColumn.WP_CURRENT_QTY; + + // if (lot.WipPartNo.Length > 0 || lot.DiePartNo.Length > 0) + // { + // qryLotInfo = "SELECT DiePartNo, SourceFAB, Diameter, Silicon, Gen, Layers,HexSize,Voltage,Channel, Type AS ProductFamily, WaferCost, DieCost FROM FabApprovalSystem.dbo.StdCost WHERE WIPWaferNo = @WIPPartNo OR DiePartNo = @DiePartNo "; + // var moreLotInfoRow = this.db.Query(qryLotInfo, new { lot.WipPartNo, lot.DiePartNo }).ToList(); + + // foreach (var moreLotInfoColumn in moreLotInfoRow) + // { + // lot.DieCost = double.Parse(moreLotInfoColumn.DieCost.ToString()); + // lot.WaferCost = double.Parse(moreLotInfoColumn.WaferCost.ToString()); + + // if (moreLotInfoColumn.Channel != null) + // lot.Channel = moreLotInfoColumn.Channel; + + // //if (moreLotInfoColumn.ProductFamily != null) + // // lot.ProductFamily = moreLotInfoColumn.ProductFamily; + + // if (moreLotInfoColumn.Hexsize != null) + // lot.Hexsize = moreLotInfoColumn.Hexsize; + + // if (moreLotInfoColumn.Voltage != null) + // lot.Voltage = moreLotInfoColumn.Voltage; + + // //if (moreLotInfoColumn.Gen != null) + // // lot.Gen = moreLotInfoColumn.Gen; + + // if (lot.DieCount == 0) + // lot.TotalCost = Math.Round(lot.WaferCount * lot.WaferCost,2); + // else + // lot.TotalCost = Math.Round(lot.DieCount * lot.DieCost,2); + // } + + // } + + // } + + // //return lotStatusOption; + + //} + + #endregion + + public IEnumerable GetLotStatusOptions() { + List lotStatusOption = db.Query("SELECT * FROM LotStatusOption").ToList(); + return lotStatusOption; + } + + public IEnumerable GetLotDispositionLots(int issueID) { + // NOTE: Any new fields that needs to be added to select list , needs to be referenced prior to the "LS.LotStatusOptionID , LS.LotStatusOption" fields + + db.Open(); + #region Commented Code + /* + StringBuilder sql = new StringBuilder(); + sql.Append("SELECT DISTINCT SQ.IssueIDs AS MRBsLinkedToLot , DispoType.MRBDispoType, SQP.IssueIDs AS IssueIDWithoutMRB, "); + sql.Append("CASE WHEN L.LotStatusOptionID = 2 THEN 1 "); + sql.Append("WHEN PATINDEX('%B%', DispoType.MRBDispoType) > 0 AND L.LotStatusOptionID <> 2 THEN 0 "); + sql.Append("WHEN PATINDEX('%X%', DispoType.MRBDispoType) > 0 AND PATINDEX('%B%', DispoType.MRBDispoType) = 0 THEN 0 "); + + sql.Append("WHEN (PATINDEX('%D%', DispoType.MRBDispoType) > 0 "); + sql.Append(" AND PATINDEX('%X%', DispoType.MRBDispoType) = 0 "); + sql.Append(" AND PATINDEX('%B%', DispoType.MRBDispoType) = 0 "); + sql.Append(" AND LS.LotStatusOptionID <> 6 ) "); + sql.Append(" AND (LTRIM(RTRIM(Location)) <> 'QDB' AND LTRIM(RTRIM(Location)) <> 'EDB') THEN 0 "); + + sql.Append("ELSE 1 "); + sql.Append("END AS GoodToSubmit, "); + + sql.Append("CASE WHEN L.LotStatusOptionID = 2 THEN 'NA' "); + sql.Append("WHEN (PATINDEX('%B%', DispoType.MRBDispoType) > 0 AND L.LotStatusOptionID <> 2) "); + sql.Append("OR ( "); + sql.Append(" (PATINDEX('%D%', DispoType.MRBDispoType) > 0 "); + sql.Append(" AND PATINDEX('%X%', DispoType.MRBDispoType) = 0 "); + sql.Append(" AND PATINDEX('%B%', DispoType.MRBDispoType) = 0 "); + sql.Append(" AND LS.LotStatusOptionID <> 6 AND (LTRIM(RTRIM(Location)) <> 'QDB' AND LTRIM(RTRIM(Location)) <> 'EDB')) "); + sql.Append(" )"); + sql.Append(" THEN 'MRB Disposition different from Lot Dispostion' "); + + sql.Append("WHEN PATINDEX('%X%', DispoType.MRBDispoType) > 0 AND PATINDEX('%B%', DispoType.MRBDispoType) = 0 THEN 'MRB Dispo missing' "); + sql.Append("ELSE 'NA' "); + sql.Append("END AS SubmitErrorMessage, "); + + sql.Append(" "); + sql.Append("L.LotID, L.LotNumber, L.IssueID ,L.DieLotNumber ,L.Description ,L.NewPartNo ,L.WipPartNo ,L.DiePartNo ,L.ProductFamily, "); + sql.Append("L.Gen ,L.Channel, L.HexSize, L.Voltage, L.WaferCount, L.DieCount, L.Location, L.TotalCost, L.LotStatusOptionID,"); + sql.Append("S.ReleaseCount, S.ScrapCount, L.QualityCode, LS.LotStatusOptionID , LS.LotStatusOption FROM Lot L "); + sql.Append("INNER JOIN LotStatusOption LS ON L.LotStatusOptionID = LS.LotStatusOptionID "); + sql.Append("LEFT JOIN ScrapLot S ON L.LotNumber = S.LotNo AND L.IssueID = S.IssueID "); + + sql.Append("LEFT JOIN "); + sql.Append("(SELECT DISTINCT L.LotID, STUFF "); + // Code changed 12/11/2019 RJK + //sql.Append("((SELECT DISTINCT ',' + CAST(ML.MRBNumber AS varchar(512)) "); + sql.Append("((SELECT DISTINCT ',' + CAST(ML.MRBNumber AS varchar(512)) + '_' + CAST(ISNULL(ML.DispoType,'') AS varchar(512)) "); + sql.Append("FROM vMRBLot ML "); + //sql.Append("WHERE SUBSTRING(LTRIM(RTRIM(L.LotNumber)),1,7) = SUBSTRING(LTRIM(RTRIM(ML.LotNumber)),1,7) "); + sql.Append("WHERE LTRIM(RTRIM(L.LotNumber)) = LTRIM(RTRIM(ML.LotNumber)) "); + sql.Append("FOR XML PATH('')), 1, 1, '') AS IssueIDs "); + sql.Append("FROM Lot L) AS SQ "); + sql.Append("ON L.LotID = SQ.LotID "); + + sql.Append("LEFT JOIN "); + sql.Append("(SELECT DISTINCT L.LotID, STUFF "); + sql.Append("((SELECT DISTINCT ',' + CAST(ML.MRBNumber AS varchar(512)) "); + sql.Append("FROM vMRBLot ML "); + sql.Append("WHERE LTRIM(RTRIM(L.LotNumber)) = LTRIM(RTRIM(ML.LotNumber)) "); + sql.Append("FOR XML PATH('')), 1, 1, '') AS IssueIDs "); + sql.Append("FROM Lot L) AS SQP "); + sql.Append("ON L.LotID = SQP.LotID "); + + sql.Append("LEFT JOIN "); + sql.Append("(SELECT DISTINCT L.LotID, STUFF "); + sql.Append("((SELECT DISTINCT ',' + CAST(ISNULL(ML.DispoType, 'X') AS varchar(512)) "); + sql.Append("FROM vMRBLot ML "); + sql.Append("WHERE LTRIM(RTRIM(L.LotNumber)) = LTRIM(RTRIM(ML.LotNumber)) "); + sql.Append("FOR XML PATH('')), 1, 1, '') AS MRBDispoType "); + sql.Append("FROM Lot L) AS DispoType "); + sql.Append("ON L.LotID = DispoType.LotID "); + + sql.Append("WHERE L.IssueID = " + issueID); + + var data = this.db.Query + (sql.ToString(), (lot, lotstatusoption) => + { + lot.LotStatusOption = lotstatusoption; + return lot; + }, + splitOn: "LotStatusOptionID").ToList(); + + */ + #endregion + + DynamicParameters parameters = new(); + parameters.Add("@IssueID", issueID, DbType.Int32); + List data = db.Query + ("GetLotDispositionLots", (lot, lotstatusoption) => { + lot.LotStatusOption = lotstatusoption; + return lot; + }, + param: parameters, + commandType: CommandType.StoredProcedure, + splitOn: "LotStatusOptionID").ToList(); + + return data; + } + + public IEnumerable GetLotDispoAttachments(int issueID) { + List attachments = db.Query("SELECT A.AttachmentID, A.IssueID, A.FileName, A.UserID, CONVERT(VARCHAR(10), A.UploadDate, 101) AS UploadDate, U.FirstName + ' ' + U.LastName AS FullName FROM Attachment A INNER JOIN Users U ON A.UserID = U.UserID WHERE IssueID = @IssueID ", new { IssueID = issueID }).ToList(); + return attachments; + } + + public void DeleteLotDispoAttachment(int attachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@AttachmentID", attachmentID); + db.Execute("DeleteLotDispositionAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + public void InsertLotDispositionAttachment(Attachment attach) { + DynamicParameters parameters = new(); + parameters.Add("@IssueID", attach.IssueID); + parameters.Add("@UserID", attach.UserID); + parameters.Add("@FileName", attach.FileName); + + db.Execute("InsertLotDispositionAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + public IEnumerable SearchLots(string searchText) { + // string sql = "SELECT WP_LOT_NO AS LotNumber FROM SPNLot WHERE WP_LOT_NO LIKE '%" + searchText + "%' OR DieLotNumber LIKE '%" + searchText + "%'"; + string sql = "SELECT WP_LOT_NO AS LotNumber FROM SPNLot WHERE WP_LOT_NO LIKE '%" + searchText + "%' "; + List lotList = db.Query(sql).ToList(); + return lotList; + } + + public IEnumerable GetUserList() { + StringBuilder sql = new(); + sql.Append("SELECT FirstName + ' ' + LastName AS OriginatorName, U.UserID AS OriginatorID, FirstName "); + sql.Append("FROM Users U "); + sql.Append("ORDER BY FirstName"); + + return db.Query(sql.ToString()).ToList(); + } + + public List GetResponsibilityList() { + List departments = db.Query("SELECT ResponsibilityID, ResponsibilityName FROM Responsibility ORDER BY ResponsibilityName ", null, commandType: CommandType.Text).ToList(); + return departments; + } + + public List GetResponsibilityIssueList(int responsibilityID) { + List respIssue = db.Query("SELECT ResponsibilityIssueID, Issue FROM ResponsibilityIssue WHERE ResponsibilityID = @ResponsibilityID ORDER BY Issue ", new { @ResponsibilityID = responsibilityID }, commandType: CommandType.Text).ToList(); + return respIssue; + } + + public void UpdateLotScrapReleaseStatus(ScrapLot scrap) { + StringBuilder qryInsert = new(); + qryInsert.Append("DELETE FROM ScrapLot WHERE LotNo = @LotNo AND IssueID = @IssueID"); + qryInsert.Append(" INSERT INTO ScrapLot(LotNo,IssueID,ScrapCount,ReleaseCount, Lot1State,Lot2State,Lot3State,Lot4State,Lot5State,Lot6State,Lot7State,Lot8State,Lot9State,Lot10State, "); + qryInsert.Append(" Lot11State,Lot12State,Lot13State,Lot14State,Lot15State,Lot16State,Lot17State,Lot18State,Lot19State,Lot20State, "); + qryInsert.Append(" Lot21State,Lot22State,Lot23State,Lot24State,Lot25State,Lot26State,Lot27State,Lot28State,Lot29State,Lot30State, "); + qryInsert.Append(" Lot31State,Lot32State,Lot33State,Lot34State,Lot35State,Lot36State,Lot37State,Lot38State,Lot39State,Lot40State, "); + qryInsert.Append(" Lot41State,Lot42State,Lot43State,Lot44State,Lot45State,Lot46State,Lot47State,Lot48State,Lot49State,Lot50State) "); + qryInsert.Append(" VALUES(@LotNo,@IssueID,@ScrapCount,@ReleaseCount,@Lot1State,@Lot2State,@Lot3State,@Lot4State,@Lot5State,@Lot6State,@Lot7State,@Lot8State,@Lot9State,@Lot10State,"); + qryInsert.Append(" @Lot11State,@Lot12State,@Lot13State,@Lot14State,@Lot15State,@Lot16State,@Lot17State,@Lot18State,@Lot19State,@Lot20State,"); + qryInsert.Append(" @Lot21State,@Lot22State,@Lot23State,@Lot24State,@Lot25State,@Lot26State,@Lot27State,@Lot28State,@Lot29State,@Lot30State,"); + qryInsert.Append(" @Lot31State,@Lot32State,@Lot33State,@Lot34State,@Lot35State,@Lot36State,@Lot37State,@Lot38State,@Lot39State,@Lot40State,"); + qryInsert.Append(" @Lot41State,@Lot42State,@Lot43State,@Lot44State,@Lot45State,@Lot46State,@Lot47State,@Lot48State,@Lot49State,@Lot50State)"); + + DynamicParameters parameters = new(); + parameters.Add("@LotNo", scrap.LotNo); + parameters.Add("@IssueID", scrap.IssueID); + parameters.Add("@ScrapCount", scrap.ScrapCount); + parameters.Add("@ReleaseCount", scrap.ReleaseCount); + parameters.Add("@Lot1State", scrap.Lot1State); + parameters.Add("@Lot2State", scrap.Lot2State); + parameters.Add("@Lot3State", scrap.Lot3State); + parameters.Add("@Lot4State", scrap.Lot4State); + parameters.Add("@Lot5State", scrap.Lot5State); + parameters.Add("@Lot6State", scrap.Lot6State); + parameters.Add("@Lot7State", scrap.Lot7State); + parameters.Add("@Lot8State", scrap.Lot8State); + parameters.Add("@Lot9State", scrap.Lot9State); + parameters.Add("@Lot10State", scrap.Lot10State); + parameters.Add("@Lot11State", scrap.Lot11State); + parameters.Add("@Lot12State", scrap.Lot12State); + parameters.Add("@Lot13State", scrap.Lot13State); + parameters.Add("@Lot14State", scrap.Lot14State); + parameters.Add("@Lot15State", scrap.Lot15State); + parameters.Add("@Lot16State", scrap.Lot16State); + parameters.Add("@Lot17State", scrap.Lot17State); + parameters.Add("@Lot18State", scrap.Lot18State); + parameters.Add("@Lot19State", scrap.Lot19State); + parameters.Add("@Lot20State", scrap.Lot20State); + parameters.Add("@Lot21State", scrap.Lot21State); + parameters.Add("@Lot22State", scrap.Lot22State); + parameters.Add("@Lot23State", scrap.Lot23State); + parameters.Add("@Lot24State", scrap.Lot24State); + parameters.Add("@Lot25State", scrap.Lot25State); + parameters.Add("@Lot26State", scrap.Lot26State); + parameters.Add("@Lot27State", scrap.Lot27State); + parameters.Add("@Lot28State", scrap.Lot28State); + parameters.Add("@Lot29State", scrap.Lot29State); + parameters.Add("@Lot30State", scrap.Lot30State); + parameters.Add("@Lot31State", scrap.Lot31State); + parameters.Add("@Lot32State", scrap.Lot32State); + parameters.Add("@Lot33State", scrap.Lot33State); + parameters.Add("@Lot34State", scrap.Lot34State); + parameters.Add("@Lot35State", scrap.Lot35State); + parameters.Add("@Lot36State", scrap.Lot36State); + parameters.Add("@Lot37State", scrap.Lot37State); + parameters.Add("@Lot38State", scrap.Lot38State); + parameters.Add("@Lot39State", scrap.Lot39State); + parameters.Add("@Lot40State", scrap.Lot40State); + parameters.Add("@Lot41State", scrap.Lot41State); + parameters.Add("@Lot42State", scrap.Lot42State); + parameters.Add("@Lot43State", scrap.Lot43State); + parameters.Add("@Lot44State", scrap.Lot44State); + parameters.Add("@Lot45State", scrap.Lot45State); + parameters.Add("@Lot46State", scrap.Lot46State); + parameters.Add("@Lot47State", scrap.Lot47State); + parameters.Add("@Lot48State", scrap.Lot48State); + parameters.Add("@Lot49State", scrap.Lot49State); + parameters.Add("@Lot50State", scrap.Lot50State); + + db.Execute(qryInsert.ToString(), parameters, commandType: CommandType.Text); + } + + public void UpdateLotStatus(ScrapLot lotStatus) { + //if all the wafers in a lot is either "RELEASE" or "SCRAP" from the "SELECT WAFERS SCREEN" set the Lot Status Option accodingly for the particula lot + int tempLotStatus; + if ((lotStatus.ReleaseCount == lotStatus.WaferCount || lotStatus.ScrapCount == lotStatus.WaferCount) && (lotStatus.ReleaseCount > 0 || lotStatus.WaferCount > 0)) { + // set the LotStatus appropriately because the entire lot either is set to "RELEASE" or "SCRAP"' + tempLotStatus = lotStatus.ReleaseCount == lotStatus.WaferCount ? (int)GlobalVars.LotStatusOption.Release : (int)GlobalVars.LotStatusOption.Scrap; + + // Close to QDB is count as "Release" + if ((lotStatus.CloseToQDBCount == lotStatus.WaferCount) && (lotStatus.CloseToQDBCount > 0 || lotStatus.WaferCount > 0)) { + tempLotStatus = (int)GlobalVars.LotStatusOption.CloseToQDB; + } + } else if ((lotStatus.SplitOfHoldCount == lotStatus.WaferCount) && (lotStatus.SplitOfHoldCount > 0 || lotStatus.WaferCount > 0)) { + tempLotStatus = (int)GlobalVars.LotStatusOption.SplitOffHold; + } else { + tempLotStatus = (int)GlobalVars.LotStatusOption.Select_Wafers; + } + DynamicParameters parameters = new(); + parameters.Add("@LotNo", lotStatus.LotNo); + parameters.Add("@IssueID", lotStatus.IssueID); + parameters.Add("@LotStatus", tempLotStatus); + db.Execute("UpdateLotStatus", parameters, commandType: CommandType.StoredProcedure); + } + + /// + /// Update the Status of all the lots for a given Lot disposition document + /// + + public void UpdateLotStatusAll(ScrapLot scrap, int lotStatus) { + DynamicParameters parameters = new(); + parameters.Add("@IssueID", scrap.IssueID); + parameters.Add("@LotStatus", lotStatus); + parameters.Add("@ScrapCount", 0); + parameters.Add("@Lot1State", scrap.Lot1State); + parameters.Add("@Lot2State", scrap.Lot2State); + parameters.Add("@Lot3State", scrap.Lot3State); + parameters.Add("@Lot4State", scrap.Lot4State); + parameters.Add("@Lot5State", scrap.Lot5State); + parameters.Add("@Lot6State", scrap.Lot6State); + parameters.Add("@Lot7State", scrap.Lot7State); + parameters.Add("@Lot8State", scrap.Lot8State); + parameters.Add("@Lot9State", scrap.Lot9State); + parameters.Add("@Lot10State", scrap.Lot10State); + parameters.Add("@Lot11State", scrap.Lot11State); + parameters.Add("@Lot12State", scrap.Lot12State); + parameters.Add("@Lot13State", scrap.Lot13State); + parameters.Add("@Lot14State", scrap.Lot14State); + parameters.Add("@Lot15State", scrap.Lot15State); + parameters.Add("@Lot16State", scrap.Lot16State); + parameters.Add("@Lot17State", scrap.Lot17State); + parameters.Add("@Lot18State", scrap.Lot18State); + parameters.Add("@Lot19State", scrap.Lot19State); + parameters.Add("@Lot20State", scrap.Lot20State); + parameters.Add("@Lot21State", scrap.Lot21State); + parameters.Add("@Lot22State", scrap.Lot22State); + parameters.Add("@Lot23State", scrap.Lot23State); + parameters.Add("@Lot24State", scrap.Lot24State); + parameters.Add("@Lot25State", scrap.Lot25State); + parameters.Add("@Lot26State", scrap.Lot26State); + parameters.Add("@Lot27State", scrap.Lot27State); + parameters.Add("@Lot28State", scrap.Lot28State); + parameters.Add("@Lot29State", scrap.Lot29State); + parameters.Add("@Lot30State", scrap.Lot30State); + parameters.Add("@Lot31State", scrap.Lot31State); + parameters.Add("@Lot32State", scrap.Lot32State); + parameters.Add("@Lot33State", scrap.Lot33State); + parameters.Add("@Lot34State", scrap.Lot34State); + parameters.Add("@Lot35State", scrap.Lot35State); + parameters.Add("@Lot36State", scrap.Lot36State); + parameters.Add("@Lot37State", scrap.Lot37State); + parameters.Add("@Lot38State", scrap.Lot38State); + parameters.Add("@Lot39State", scrap.Lot39State); + parameters.Add("@Lot40State", scrap.Lot40State); + parameters.Add("@Lot41State", scrap.Lot41State); + parameters.Add("@Lot42State", scrap.Lot42State); + parameters.Add("@Lot43State", scrap.Lot43State); + parameters.Add("@Lot44State", scrap.Lot44State); + parameters.Add("@Lot45State", scrap.Lot45State); + parameters.Add("@Lot46State", scrap.Lot46State); + parameters.Add("@Lot47State", scrap.Lot47State); + parameters.Add("@Lot48State", scrap.Lot48State); + parameters.Add("@Lot49State", scrap.Lot49State); + parameters.Add("@Lot50State", scrap.Lot50State); + + db.Execute("UpdateScrapLotAll", parameters, commandType: CommandType.StoredProcedure); + } + + public LotDispositionLotSummaryViewModel GetLotDispositionLotSummary(int issueID) { + StringBuilder sql = new(); + sql.Append("SELECT L.WaferCount AS 'TotalWaferCount', L.DieCount AS 'TotalDieCount', L.TotalCost AS 'TotalCost', S.ScrapCount AS 'ScrapWaferCount', S.ReleaseCount AS 'ReleaseWaferCount', L.LotStatusOptionID AS 'LotStatusOption' "); + sql.Append("FROM ScrapLot S INNER JOIN Lot L ON S.IssueID = L.IssueID AND S.LotNo = L.LotNumber "); + sql.Append("WHERE S.IssueID = @issueID"); + + List LotDispositionLotList = db.Query(sql.ToString(), new { issueID = issueID }).ToList(); + int lotCount = 0; + + int totalWaferScrapCount = 0; + int totalDieScrapCount = 0; + double totalScrapCost = 0; + + int totalWaferReleaseCount = 0; + int totalDieReleaseCount = 0; + double totalReleaseCost = 0; + + int releaseWaferCount = 0; + double releaseCost = 0; + int releaseDieCount = 0; + + int scrapWaferCount = 0; + double scrapCost = 0; + int scrapDieCount = 0; + + foreach (LotDispositionLotSummaryViewModel ld in LotDispositionLotList) { + releaseWaferCount = 0; + releaseCost = 0; + releaseDieCount = 0; + + scrapWaferCount = 0; + scrapCost = 0; + scrapDieCount = 0; + + // Wafer=================================================================== + if (ld.ScrapWaferCount > 0 && ld.TotalWaferCount > 0 && ld.TotalCost > 0) { + scrapWaferCount = ld.ScrapWaferCount; + double perWaferCost = ld.TotalCost / ld.TotalWaferCount; + scrapCost = scrapWaferCount * perWaferCost; + } else if (ld.ScrapWaferCount == 0) { + scrapWaferCount = ld.ScrapWaferCount; + scrapCost = 0; + } + + if (ld.ReleaseWaferCount > 0 && ld.TotalWaferCount > 0 && ld.TotalCost > 0) { + releaseWaferCount = ld.ReleaseWaferCount; + double perWaferCost = ld.TotalCost / ld.TotalWaferCount; + releaseCost = releaseWaferCount * perWaferCost; + } else if (ld.ReleaseWaferCount == 0) { + releaseWaferCount = ld.ReleaseWaferCount; + releaseCost = 0; + } + + // Die =================================================================== + if ( + (ld.LotStatusOption == (int)GlobalVars.LotStatusOption.Release + || ld.LotStatusOption == (int)GlobalVars.LotStatusOption.M_Suffix + || ld.LotStatusOption == (int)GlobalVars.LotStatusOption.CloseToQDB) + && ld.TotalDieCount > 0) { + releaseDieCount = ld.TotalDieCount;// + releaseCost = ld.TotalCost; + } + + if (ld.LotStatusOption == (int)GlobalVars.LotStatusOption.Scrap && ld.TotalDieCount > 0) { + scrapDieCount = ld.TotalDieCount;// + scrapCost = ld.TotalCost; + } + + // Summarize + lotCount++; + totalWaferScrapCount += scrapWaferCount; + totalWaferReleaseCount += releaseWaferCount; + + totalDieScrapCount += scrapDieCount; + totalDieReleaseCount += releaseDieCount; + + totalScrapCost += scrapCost; + totalReleaseCost += releaseCost; + } + + //} + + return new LotDispositionLotSummaryViewModel() { + LotCount = lotCount, + ReleaseCost = string.Format("{0:C}", totalReleaseCost), + //Math.Round(totalReleaseCost, 2).ToString(, + ReleaseWaferCount = totalWaferReleaseCount, + ReleaseDieCount = totalDieReleaseCount, + ScrapCost = string.Format("{0:C}", totalScrapCost), + //Math.Round(totalScrapCost, 2), + ScrapWaferCount = totalWaferScrapCount, + ScrapDieCount = totalDieScrapCount + + }; + } + + public int SubmitDocument(int issueID, bool peRequired, bool mrbRequired, int userID) { + string subRoles = wfDMO.GetSubRoleItems(issueID, (int)GlobalVars.DocumentType.LotDisposition); + + // bubble the error + int appoverCount = 0; + DynamicParameters parameters = new(); + parameters.Add("@IssueID", issueID); + parameters.Add("@UserID", userID); + parameters.Add("@PERequired", peRequired); + parameters.Add("@MRBRequired", mrbRequired); + parameters.Add("@DocumentTypeID", 1); // Lot Dispostion + parameters.Add("@SubRoleCategoriesClause", subRoles); + parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); + + db.Execute("SubmitForApproval_LotDisposition", parameters, commandType: CommandType.StoredProcedure); + + appoverCount = parameters.Get("@AppoverCount"); + return appoverCount; + } + + public List GetRejectionOrginatorEmailList(int issueID) { + DynamicParameters parameters = new(); + parameters.Add("@IssueID", issueID); + List emailList = db.Query("GetRejectionOrginatorEmailList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return emailList; + } + + public void UpdateReasonForDisposition(int issueID, string reasonForDisposition) { + DynamicParameters parameters = new(); + + parameters.Add("@IssueID", issueID); + parameters.Add("@ReasonForDisposition", reasonForDisposition); + db.Execute("UpdateReasonForDisposition", parameters, commandType: CommandType.StoredProcedure); + } + + public void InsertComments(int issueID, string comments, int commentedBy) { + DynamicParameters parameters = new(); + + parameters.Add("@IssueID", issueID); + parameters.Add("@Comments", comments); + parameters.Add("@CommentedBy", commentedBy); + db.Execute("InsertComments", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteLotDisposition(int issueID) { + DynamicParameters parameters = new(); + parameters.Add("@IssueID", issueID); + db.Execute("DeleteLotDisposition", parameters, commandType: CommandType.StoredProcedure); + } + + internal IEnumerable GetComments(int issueID) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + return db.Query("GetComments", new { @IssueID = issueID }, commandType: CommandType.StoredProcedure).ToList(); + } + + public void ReleaseLockOnDocument(int userID, int issueID) { + DynamicParameters parameters = new(); + parameters.Add("@IssueID", issueID); + parameters.Add("@UserID", userID); + db.Execute("ReleaseLockOnLotDispoDoc", parameters, commandType: CommandType.StoredProcedure); + } + + public string GetFileName(string attachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@AttachmentID", attachmentID); + var fileName = db.Query("GetFileName", parameters, commandType: CommandType.StoredProcedure).Single(); + return fileName; + } + + public void AttachSave(int issueID, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + var fileName = Path.GetFileName(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + "LotDisposition", fileName); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + Attachment attach = new() { + IssueID = issueID, + FileName = fileName, + UserID = userId, + }; + InsertLotDispositionAttachment(attach); + } + + public string ExcelLotOpen(int issueID, string userIdentityName, string lotTempPipeLine, string fullFileName, Stream stream) { + string physicalPath; + + var fileExtension = Path.GetExtension(fullFileName); + string fName = userIdentityName + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); + + physicalPath = Path.Combine(lotTempPipeLine, fName + "." + fileExtension); + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } +#if !NET8 + ExcelData x = new ExcelData(physicalPath); + var lotNumbers = x.ReadData(); + + foreach (var lotInfo in lotNumbers) { + Lot l = new Lot(); + l.LotNumber = lotInfo.LotNo; + l.IssueID = issueID; + if (l.LotStatusOptionID == 0) + l.LotStatusOption.LotStatusOptionID = (int)GlobalVars.LotStatusOption.Release; + + InsertLot(l, true); + //if (!mrbDMO.DoesMRBLotExist(lotInfo.LotNo)) + //{ + // //get All the MRBs associated to the Parent lot + // //insert the lot into the MRBChildLotNotInMRB table and NOT in the MRB Lot table for each MRB + // InsertChildLot_NotInTheMRB(lotInfo.LotNo); + + //} + } +#endif + + FileInfo f = new(physicalPath); + if (f.Exists) + f.Delete(); + + return physicalPath; + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/LotTravelerDMO.cs b/Fab2ApprovalSystem/DMO/LotTravelerDMO.cs index 53de567..a30f9e2 100644 --- a/Fab2ApprovalSystem/DMO/LotTravelerDMO.cs +++ b/Fab2ApprovalSystem/DMO/LotTravelerDMO.cs @@ -1,1651 +1,1307 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.Data; using System.Data.SqlClient; +using System.IO; using System.Linq; using System.Text; -using System.Web; -using Fab2ApprovalSystem.Models; -using Dapper; using System.Transactions; -using Fab2ApprovalSystem.ViewModels; -using System.Reflection; + +using Dapper; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.ViewModels; -namespace Fab2ApprovalSystem.DMO -{ - public class LotTravelerDMO - { - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - WorkflowDMO wfDMO = new WorkflowDMO(); +namespace Fab2ApprovalSystem.DMO; - /// - /// - /// - /// - /// - /// - internal LTWorkRequest InsertWorkRequest(LTWorkRequest workRequest) - { +public class LotTravelerDMO { - var parameters = new DynamicParameters(); - parameters.Add("@ID", value: workRequest.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@OriginatorID", workRequest.OriginatorID); + private readonly AppSettings _AppSettings; + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + private readonly WorkflowDMO wfDMO = new(); - this.db.Execute("LTInsertWorkRequest", parameters, commandType: CommandType.StoredProcedure); - workRequest.ID = parameters.Get("@ID"); + public LotTravelerDMO(AppSettings appSettings) => + _AppSettings = appSettings; - return workRequest; - } + /// + /// + internal LTWorkRequest InsertWorkRequest(LTWorkRequest workRequest) { + DynamicParameters parameters = new(); + parameters.Add("@ID", value: workRequest.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@OriginatorID", workRequest.OriginatorID); - /// - /// - /// - /// - /// - /// - /// - internal LTWorkRequest GetLTWorkRequestItem(int workRequestID, out int isITAR, int userID) - { + db.Execute("LTInsertWorkRequest", parameters, commandType: CommandType.StoredProcedure); + workRequest.ID = parameters.Get("@ID"); + return workRequest; + } - isITAR = 2; - var workRequestItem = new LTWorkRequest(); - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", value: workRequestID); - parameters.Add("@UserID", userID); - parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - - using (var multipleResultItems = this.db.QueryMultiple("LTGetWorkRequestItem", parameters, commandType: CommandType.StoredProcedure)) - { - workRequestItem = multipleResultItems.Read().SingleOrDefault(); - - var departments = multipleResultItems.Read().ToList(); - if (workRequestItem != null && departments != null) - { - workRequestItem.DepartmentIDs.AddRange(departments); - } - - var modules = multipleResultItems.Read().ToList(); - if (workRequestItem != null && modules != null) - { - if (modules.Count > 0) - workRequestItem.ModuleIDs.AddRange(modules); - } - - //var holdsteps = multipleResultItems.Read().SingleOrDefault(); - //workRequestItem.LTHoldStep = holdsteps; - - isITAR = parameters.Get("@IsITAR"); + internal LTWorkRequest GetLTWorkRequestItem(int workRequestID, out int isITAR, int userID) { + isITAR = 2; + LTWorkRequest workRequestItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", value: workRequestID); + parameters.Add("@UserID", userID); + parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + using (var multipleResultItems = db.QueryMultiple("LTGetWorkRequestItem", parameters, commandType: CommandType.StoredProcedure)) { + workRequestItem = multipleResultItems.Read().SingleOrDefault(); + List departments = multipleResultItems.Read().ToList(); + if (workRequestItem != null && departments != null) { + workRequestItem.DepartmentIDs.AddRange(departments); } - return workRequestItem; - - } - - - internal WorkRequestPdf GetLTWorkRequestItemPDF(int workRequestID) - { - - - var workRequestItem = new WorkRequestPdf(); - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", value: workRequestID); - - - using (var multipleResultItems = this.db.QueryMultiple("LTGetWorkRequestItemPDF", parameters, commandType: CommandType.StoredProcedure)) - { - workRequestItem = multipleResultItems.Read().SingleOrDefault(); - - var departments = multipleResultItems.Read().ToList(); - workRequestItem.AffectedDepartments = String.Join(", ", departments) ; - - var modules = multipleResultItems.Read().ToList(); - workRequestItem.AffectedModules = String.Join(", ", modules); - - var materials = multipleResultItems.Read().ToList(); - if (workRequestItem != null && materials != null) - { - if (materials.Count > 0) - workRequestItem.LTMaterial.AddRange(materials); - } - - var holdsteps = multipleResultItems.Read().ToList(); - if (workRequestItem != null && holdsteps != null) - { - if (holdsteps.Count > 0) - workRequestItem.LTHoldStep.AddRange(holdsteps); - } + List modules = multipleResultItems.Read().ToList(); + if (workRequestItem != null && modules != null) { + if (modules.Count > 0) + workRequestItem.ModuleIDs.AddRange(modules); } - return workRequestItem; + //var holdsteps = multipleResultItems.Read().SingleOrDefault(); + //workRequestItem.LTHoldStep = holdsteps; + + isITAR = parameters.Get("@IsITAR"); } - /// - /// - /// - /// - /// - /// - /// - internal LTWorkRequest GetLTWorkRequestItemForRead(int workRequestID, out int isITAR, int userID) - { + return workRequestItem; + } + internal WorkRequestPdf GetLTWorkRequestItemPDF(int workRequestID) { + WorkRequestPdf workRequestItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", value: workRequestID); - isITAR = 2; - var workRequestItem = new LTWorkRequest(); - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", value: workRequestID); - parameters.Add("@UserID", userID); - parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + using (var multipleResultItems = db.QueryMultiple("LTGetWorkRequestItemPDF", parameters, commandType: CommandType.StoredProcedure)) { + workRequestItem = multipleResultItems.Read().SingleOrDefault(); + List departments = multipleResultItems.Read().ToList(); + workRequestItem.AffectedDepartments = string.Join(", ", departments); - using (var multipleResultItems = this.db.QueryMultiple("LTGetWorkRequestItemForRead", parameters, commandType: CommandType.StoredProcedure)) - { - workRequestItem = multipleResultItems.Read().SingleOrDefault(); - - var departments = multipleResultItems.Read().ToList(); - if (workRequestItem != null && departments != null) - { - workRequestItem.DepartmentIDs.AddRange(departments); - } - - var modules = multipleResultItems.Read().ToList(); - if (workRequestItem != null && modules != null) - { - if (modules.Count > 0) - workRequestItem.ModuleIDs.AddRange(modules); - } - - //var holdsteps = multipleResultItems.Read().SingleOrDefault(); - //workRequestItem.LTHoldStep = holdsteps; - - isITAR = parameters.Get("@IsITAR"); - + List modules = multipleResultItems.Read().ToList(); + workRequestItem.AffectedModules = string.Join(", ", modules); + List materials = multipleResultItems.Read().ToList(); + if (workRequestItem != null && materials != null) { + if (materials.Count > 0) + workRequestItem.LTMaterial.AddRange(materials); } - return workRequestItem; + List holdsteps = multipleResultItems.Read().ToList(); + if (workRequestItem != null && holdsteps != null) { + if (holdsteps.Count > 0) + workRequestItem.LTHoldStep.AddRange(holdsteps); + } + } + + return workRequestItem; + } + + internal LTWorkRequest GetLTWorkRequestItemForRead(int workRequestID, out int isITAR, int userID) { + isITAR = 2; + LTWorkRequest workRequestItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", value: workRequestID); + parameters.Add("@UserID", userID); + parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + using (var multipleResultItems = db.QueryMultiple("LTGetWorkRequestItemForRead", parameters, commandType: CommandType.StoredProcedure)) { + workRequestItem = multipleResultItems.Read().SingleOrDefault(); + + List departments = multipleResultItems.Read().ToList(); + if (workRequestItem != null && departments != null) { + workRequestItem.DepartmentIDs.AddRange(departments); + } + + List modules = multipleResultItems.Read().ToList(); + if (workRequestItem != null && modules != null) { + if (modules.Count > 0) + workRequestItem.ModuleIDs.AddRange(modules); + } + + //var holdsteps = multipleResultItems.Read().SingleOrDefault(); + //workRequestItem.LTHoldStep = holdsteps; + + isITAR = parameters.Get("@IsITAR"); } - /// - /// - /// - /// - internal int UpdateWorkRequest(LTWorkRequest data, int userID) - { - int result = 0; - var parameters = new DynamicParameters(); - using (var transanction = new TransactionScope()) - { - try - { + return workRequestItem; + } + internal int UpdateWorkRequest(LTWorkRequest data, int userID) { + int result = 0; + DynamicParameters parameters = new(); + using (TransactionScope transanction = new()) { + try { + parameters.Add("@LTWorkRequestID", data.ID); + parameters.Add("@Title", data.Title); + parameters.Add("@LotType", data.LotType); + parameters.Add("@EngLotStartRequired", data.EngLotStartRequired); + parameters.Add("@LotTypeConversion", data.LotTypeConversion); + parameters.Add("@QualLot", data.QualLot); + parameters.Add("@PurposeOfRequest", data.PurposeOfRequest); + parameters.Add("@PlannedLotStartDate", data.PlannedLotStartDate); + parameters.Add("@PlannedScheduledCloseDate", data.PlannedScheduledCloseDate); + parameters.Add("@ChargeDepartment", data.ChargeDepartment); + parameters.Add("@AllocationToUse", data.AllocationToUse); + parameters.Add("@PredictedCyleTime", data.PredictedCyleTime); + parameters.Add("@DeptChargedForRawWafers", data.ChargeDepartment); + //parameters.Add("@EstimatedBinCLoseDate", data.EstimatedBinCLoseDate); + parameters.Add("@TotalQty", data.TotalQty); + parameters.Add("@WIPArea", data.WIPArea); + parameters.Add("@LotStartDate", data.LotStartDate); + parameters.Add("@LotNumber", data.LotNumber); + parameters.Add("@WIPPartNumber", data.WIPPartNumber); + parameters.Add("@PartDescription", data.PartDescription); + parameters.Add("@DefaultEPISiliconPartNumber", data.DefaultEPISiliconPartNumber); + parameters.Add("@RecordSiliconLotInSPNTapeTagTotrav", data.RecordSiliconLotInSPNTapeTagTotrav); + parameters.Add("@SiliconLotNoCassette1", data.SiliconLotNoCassette1); + parameters.Add("@ProcessFlow", data.ProcessFlow); + parameters.Add("@EmployeeID", data.EmployeeID); + parameters.Add("@VerbComment", data.VerbComment); + parameters.Add("@SiliconOnHand", data.SiliconOnHand); + parameters.Add("@SiliconExpectedDueDate", data.SiliconExpectedDueDate); + parameters.Add("@SiliconComments", data.SiliconComments); + parameters.Add("@ReticleOnHand", data.ReticleOnHand); + parameters.Add("@ReticleExpectedDueDate", data.ReticleExpectedDueDate); + parameters.Add("@ReticleComments", data.ReticleComments); + parameters.Add("@SPNTransferOnHand", data.SPNTransferOnHand); + parameters.Add("@SPNTransferExpectedDueDate", data.SPNTransferExpectedDueDate); + parameters.Add("@SPNTransferComments", data.SPNTransferComments); + parameters.Add("@ProbeCardOnHand", data.ProbeCardOnHand); + parameters.Add("@ProbeCardExpectedDueDate", data.ProbeCardExpectedDueDate); + parameters.Add("@ProbeCardComments", data.ProbeCardComments); + parameters.Add("@ProbeRecipeOnHand", data.ProbeRecipeOnHand); + parameters.Add("@ProbeRecipeExpectedDueDate", data.ProbeRecipeExpectedDueDate); + parameters.Add("@ProbeRecipeComments", data.ProbeRecipeComments); + parameters.Add("@ProcessChangeDetailsOnHand", data.ProcessChangeDetailsOnHand); + parameters.Add("@ProcessChangeDetailsDueDate", data.ProcessChangeDetailsDueDate); + parameters.Add("@LotStartCheckListComments", data.LotStartCheckListComments); + parameters.Add("@PCRBNumber", data.PCRBNumber); + parameters.Add("@LastUpdateBy", userID); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + db.Execute("LTUpdateWorkRequest", parameters, commandType: CommandType.StoredProcedure); - parameters.Add("@LTWorkRequestID", data.ID); - parameters.Add("@Title", data.Title); - parameters.Add("@LotType", data.LotType); - parameters.Add("@EngLotStartRequired", data.EngLotStartRequired); - parameters.Add("@LotTypeConversion", data.LotTypeConversion); - parameters.Add("@QualLot", data.QualLot); - parameters.Add("@PurposeOfRequest", data.PurposeOfRequest); - parameters.Add("@PlannedLotStartDate", data.PlannedLotStartDate); - parameters.Add("@PlannedScheduledCloseDate", data.PlannedScheduledCloseDate); - parameters.Add("@ChargeDepartment", data.ChargeDepartment); - parameters.Add("@AllocationToUse", data.AllocationToUse); - parameters.Add("@PredictedCyleTime", data.PredictedCyleTime); - parameters.Add("@DeptChargedForRawWafers", data.ChargeDepartment); - //parameters.Add("@EstimatedBinCLoseDate", data.EstimatedBinCLoseDate); - parameters.Add("@TotalQty", data.TotalQty); - parameters.Add("@WIPArea", data.WIPArea); - parameters.Add("@LotStartDate", data.LotStartDate); - parameters.Add("@LotNumber", data.LotNumber); - parameters.Add("@WIPPartNumber", data.WIPPartNumber); - parameters.Add("@PartDescription", data.PartDescription); - parameters.Add("@DefaultEPISiliconPartNumber", data.DefaultEPISiliconPartNumber); - parameters.Add("@RecordSiliconLotInSPNTapeTagTotrav", data.RecordSiliconLotInSPNTapeTagTotrav); - parameters.Add("@SiliconLotNoCassette1", data.SiliconLotNoCassette1); - parameters.Add("@ProcessFlow", data.ProcessFlow); - parameters.Add("@EmployeeID", data.EmployeeID); - parameters.Add("@VerbComment", data.VerbComment); - parameters.Add("@SiliconOnHand", data.SiliconOnHand); - parameters.Add("@SiliconExpectedDueDate", data.SiliconExpectedDueDate); - parameters.Add("@SiliconComments", data.SiliconComments); - parameters.Add("@ReticleOnHand", data.ReticleOnHand); - parameters.Add("@ReticleExpectedDueDate", data.ReticleExpectedDueDate); - parameters.Add("@ReticleComments", data.ReticleComments); - parameters.Add("@SPNTransferOnHand", data.SPNTransferOnHand); - parameters.Add("@SPNTransferExpectedDueDate", data.SPNTransferExpectedDueDate); - parameters.Add("@SPNTransferComments", data.SPNTransferComments); - parameters.Add("@ProbeCardOnHand", data.ProbeCardOnHand); - parameters.Add("@ProbeCardExpectedDueDate", data.ProbeCardExpectedDueDate); - parameters.Add("@ProbeCardComments", data.ProbeCardComments); - parameters.Add("@ProbeRecipeOnHand", data.ProbeRecipeOnHand); - parameters.Add("@ProbeRecipeExpectedDueDate", data.ProbeRecipeExpectedDueDate); - parameters.Add("@ProbeRecipeComments", data.ProbeRecipeComments); - parameters.Add("@ProcessChangeDetailsOnHand", data.ProcessChangeDetailsOnHand); - parameters.Add("@ProcessChangeDetailsDueDate", data.ProcessChangeDetailsDueDate); - parameters.Add("@LotStartCheckListComments", data.LotStartCheckListComments); - parameters.Add("@PCRBNumber", data.PCRBNumber); - parameters.Add("@LastUpdateBy", userID); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - this.db.Execute("LTUpdateWorkRequest", parameters, commandType: CommandType.StoredProcedure); - - result = parameters.Get("@Result"); - - if (result == -1) - { - throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); - } - - parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", data.ID); - this.db.Execute("LTDeleteAffectedDepartments", parameters, commandType: CommandType.StoredProcedure); - List wrDepIDs = data.DepartmentIDs; - if (wrDepIDs != null) - { - foreach (int depId in wrDepIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", data.ID); - parameters.Add("@DepartmentID", depId); - this.db.Execute("LTInsertAffectedDepartments", parameters, commandType: CommandType.StoredProcedure); - } - } - - parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", data.ID); - this.db.Execute("LTDeleteAffectedModules", parameters, commandType: CommandType.StoredProcedure); - - List wrModuleIDs = data.ModuleIDs; - if (wrModuleIDs != null) - { - foreach (int moduleID in wrModuleIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", data.ID); - parameters.Add("@ModuleID", moduleID); - this.db.Execute("LTInsertAffectedModules", parameters, commandType: CommandType.StoredProcedure); - } - } - transanction.Complete(); - } - catch (Exception ex) - { - transanction.Dispose(); - throw new Exception(ex.Message + " " + ex.InnerException); - } + result = parameters.Get("@Result"); + if (result == -1) { + throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); } - // have to do it outside of the Transaction scope because the OPENQUERY to TEMIRWAP019 LINKED server does not work parameters = new DynamicParameters(); parameters.Add("@WorkRequestID", data.ID); - this.db.Execute("LTUpdateIsITAR", parameters, commandType: CommandType.StoredProcedure); - - return result; - - } - - /// - /// - /// - /// - /// - internal LTWorkRequestAttachment GetWorkRequestAttachDetail(int wrAttachmentID) - { - var wrAttach = this.db.Query("SELECT ID, FileName ,DocType, Comments FROM LTWorkRequestAttachment WHERE ID = @wrAttachmentID ", new { wrAttachmentID = wrAttachmentID }, commandType: CommandType.Text).Single(); - return wrAttach; - } - - /// - /// - /// - /// - /// - internal IEnumerable GetMaterialDetails(int workRequestID) - { - var parameters = new DynamicParameters(); - parameters.Add("@workRequestID", value: workRequestID); - - var data = this.db.Query("LTGetMaterialDetails", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - /// - /// Update via the edit screen - /// - /// - internal void UpdateMaterialDetail(LTMaterialViewModel model, int userID) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@LTMaterialID", model.ID); - parameters.Add("@EPISiliconPartNumber", model.@EPISiliconPartNumber); - parameters.Add("@Quantity", model.Quantity); - parameters.Add("@Source", model.Source); - parameters.Add("@Supplier", model.Supplier); - parameters.Add("@UpdatedBy", userID); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - - this.db.Execute("LTUpdateMaterialDetail", parameters, commandType: CommandType.StoredProcedure); - result = parameters.Get("@Result"); - if (result == -1) - { - throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); - } - } - - /// - /// Update via the revision screen - /// - /// - internal void UpdateMaterialDetail(LTMaterial model, int userID) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@LTMaterialID", model.ID); - parameters.Add("@EPISiliconPartNumber", model.@EPISiliconPartNumber); - parameters.Add("@Quantity", model.Quantity); - parameters.Add("@Source", model.Source); - parameters.Add("@Supplier", model.Supplier); - parameters.Add("@UpdatedBy", userID); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - - this.db.Execute("LTUpdateMaterialDetail", parameters, commandType: CommandType.StoredProcedure); - - result = parameters.Get("@Result"); - if (result == -1) - { - throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); - } - } - - /// - /// - /// - /// - /// - /// - internal void UpdateMaterialDetailRevision(LTMaterial model, int previousMaterialID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@LTMaterialID", model.ID); - parameters.Add("@EPISiliconPartNumber", model.EPISiliconPartNumber); - parameters.Add("@Quantity", model.Quantity); - parameters.Add("@Source", model.Source); - parameters.Add("@Supplier", model.Supplier); - parameters.Add("@PreviousMaterialID", previousMaterialID); - - this.db.Execute("LTUpdateMaterialDetailRevision", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - internal void InsertMaterialDetail(LTMaterialViewModel model, int userID) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@LTMaterialID", model.ID, direction: ParameterDirection.InputOutput); - parameters.Add("@EPISiliconPartNumber", model.@EPISiliconPartNumber); - parameters.Add("@Quantity", model.Quantity); - parameters.Add("@Source", model.Source); - parameters.Add("@Supplier", model.Supplier); - parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); - parameters.Add("@UpdatedBy", userID); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - - this.db.Execute("LTInsertMaterialDetail", parameters, commandType: CommandType.StoredProcedure); - - int id = parameters.Get("@LTMaterialID"); - model.ID = id; - - result = parameters.Get("@Result"); - if (result == -1) - { - throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); - } - } - - /// - /// For Revisioing the data - /// - /// - internal void InsertMaterialDetail(LTMaterial model, int userID) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@LTMaterialID", model.ID, direction: ParameterDirection.InputOutput); - parameters.Add("@EPISiliconPartNumber", model.@EPISiliconPartNumber); - parameters.Add("@Quantity", model.Quantity); - parameters.Add("@Source", model.Source); - parameters.Add("@Supplier", model.Supplier); - parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); - parameters.Add("@UpdatedBy", userID); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - - - this.db.Execute("LTInsertMaterialDetail", parameters, commandType: CommandType.StoredProcedure); - - int id = parameters.Get("@LTMaterialID"); - model.ID = id; - - result = parameters.Get("@Result"); - if (result == -1) - { - throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); - } - } - - - - - /// - /// - /// - /// - internal void DeleteMaterialDetail(int LTMaterialID) - { - var parameters = new DynamicParameters(); - parameters.Add("@LTMaterialID", LTMaterialID); - this.db.Execute("LTDeleteMaterial", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - internal void DeleteMaterialDetailRevision(int materialID) - { - var parameters = new DynamicParameters(); - parameters.Add("@MaterialID", materialID); - this.db.Execute("LTDeleteMaterialRevision", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - internal List GetBaseFlowLocations(string processFlow) - { - var baseFlowLocations = this.db.Query("SELECT DISTINCT LOC as Location FROM vSPNPDB_FLOWLOCS WHERE PROCESS = @ProcessFlow ORDER BY LOC ", new { ProcessFlow = processFlow }, commandType: CommandType.Text).ToList(); - return baseFlowLocations; - } - - /// - /// - /// - /// - /// - internal LTMaterial GetMaterialRecord(int materialID) - { - var material = this.db.Query("SELECT * FROM LTMaterial WHERE ID = @materialID ", new { materialID }, commandType: CommandType.Text).Single(); - return material; - } - - /// - /// - /// - /// - /// - /// - internal List GetBaseFlowOperations(string processFlow, string loc) - { - var baseFlowOperations = this.db.Query( - "SELECT DISTINCT " + - " LTRIM(RTRIM(OPER)) + '-' + LTRIM(RTRIM(SEQ)) as Operation, " + - " LTRIM(RTRIM(OPER)) as OperCode, " + - " LTRIM(RTRIM(SEQ)) as SeqCode, " + - " LTRIM(RTRIM([OPDESC])) + ' (' + LTRIM(RTRIM([AREA])) + ')' AS 'OperationDesc' " + - "FROM vSPNPDB_FLOWLOCS " + - "WHERE PROCESS = @ProcessFlow AND LOC = @LOC " + - "ORDER BY Operation ", - new { ProcessFlow = processFlow, LOC = loc }, commandType: CommandType.Text).ToList(); - return baseFlowOperations; - } - - - internal List GetPartNumbers() - { - - var baseFlowOperations = this.db.Query("SELECT DISTINCT TOP 100 [MP_PART_NUMBER] AS PartNumber, MP_DESCRIPTION + ' ~ ' + MP_PART_NUMBER AS SiliconAndDesc FROM vFAB2SPN_MP_RECORD ORDER BY MP_PART_NUMBER ", commandType: CommandType.Text).ToList(); - return baseFlowOperations; - } - - /// - /// - /// - /// - /// - internal IEnumerable GetHoldSteps(int workRequestID) - { - var parameters = new DynamicParameters(); - parameters.Add("@workRequestID", value: workRequestID); - - var data = this.db.Query("LTGetHoldSteps", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - /// - /// - /// - /// - internal void InsertHoldStep(LTHoldStep model) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@LTHoldStepID", model.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@BaseFlow", model.BaseFlow); - parameters.Add("@BaseFlowLocation", model.Location); - parameters.Add("@BaseFlowOperationSeq", model.OperSequence); - parameters.Add("@BaseFlowOperation", model.Operation); - parameters.Add("@OperationDescription", model.OperationDescription); - parameters.Add("@ChangeInstruction", model.ChangeInstructions); - parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); - parameters.Add("@UpdatedBy", model.UpdatedBy); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - this.db.Execute("LTInsertHoldStep", parameters, commandType: CommandType.StoredProcedure); - - int id = parameters.Get("@LTHoldStepID"); - model.ID = id; - - result = parameters.Get("@Result"); - - //if (result == -1) - //{ - // throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); - //} - - - } - - /// - /// - /// - /// - internal void UpdateHoldStep(LTHoldStep model) - { - var parameters = new DynamicParameters(); - parameters.Add("@LTHoldStepID", model.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@BaseFlow", model.BaseFlow); - parameters.Add("@BaseFlowOperationSeq", model.OperSequence); - parameters.Add("@BaseFlowLocation", model.Location); - parameters.Add("@BaseFlowOperation", model.Operation); - parameters.Add("@OperationDescription", model.OperationDescription); - parameters.Add("@ChangeInstruction", model.ChangeInstructions); - parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); - parameters.Add("@UpdatedBy", model.UpdatedBy); - - this.db.Execute("LTUpdateHoldStep", parameters, commandType: CommandType.StoredProcedure); - - //int id = parameters.Get("@LTHoldStepID"); - //model.ID = id; - - - } - - - /// - /// - /// - /// - internal void InsertHoldStepRevision(LTHoldStep model) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@LTHoldStepID", model.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@BaseFlow", model.BaseFlow); - parameters.Add("@BaseFlowLocation", model.Location); - parameters.Add("@BaseFlowOperationSeq", model.OperSequence); - parameters.Add("@BaseFlowOperation", model.Operation); - parameters.Add("@OperationDescription", model.OperationDescription); - parameters.Add("@ChangeInstruction", model.ChangeInstructions); - parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); - parameters.Add("@UpdatedBy", model.UpdatedBy); - - - this.db.Execute("LTInsertHoldStepRevision", parameters, commandType: CommandType.StoredProcedure); - - int id = parameters.Get("@LTHoldStepID"); - model.ID = id; - - - } - - /// - /// - /// - /// - internal void UpdateHoldStepRevision(LTHoldStep model) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@LTHoldStepID", model.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - //parameters.Add("@BaseFlow", model.BaseFlow); - parameters.Add("@BaseFlowLocation", model.Location); - parameters.Add("@BaseFlowOperationSeq", model.OperSequence); - parameters.Add("@BaseFlowOperation", model.Operation); - parameters.Add("@OperationDescription", model.OperationDescription); - parameters.Add("@ChangeInstruction", model.ChangeInstructions); - parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); - parameters.Add("@UpdatedBy", model.UpdatedBy); - //parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - - this.db.Execute("LTUpdateHoldStepRevision", parameters, commandType: CommandType.StoredProcedure); - - //result = parameters.Get("@Result"); - //if (result == -1) - //{ - // throw new Exception("Cannot add the Hold Step as the step has already been passed in the Mfg Process."); - //} - - - } - - /// - /// - /// - /// - internal void DeleteHoldStep(int holdStepID, int userID) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@HoldStepID", holdStepID); - parameters.Add("@UpdatedBy", userID); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - - this.db.Execute("LTDeleteHoldStep", parameters, commandType: CommandType.StoredProcedure); - - result = parameters.Get("@Result"); - if (result == -1) - { - throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); - } - } - - /// - /// - /// - /// - internal void DeleteHoldStepRevision(int holdStepID) - { - var parameters = new DynamicParameters(); - parameters.Add("@HoldStepID", holdStepID); - this.db.Execute("LTDeleteHoldStepRevision", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - internal void DeleteLotTravHoldStep(int lotTravHoldStepID) - { - var parameters = new DynamicParameters(); - parameters.Add("@LotTravHoldStepID", lotTravHoldStepID); - this.db.Execute("LTDeleteLotTravHoldStep", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - internal void DeleteLotTravHoldStepRevision(int lotTravHoldStepID) - { - var parameters = new DynamicParameters(); - parameters.Add("@LotTravHoldStepID", lotTravHoldStepID); - this.db.Execute("LTDeleteLotTravHoldStepRevision", parameters, commandType: CommandType.StoredProcedure); - } - - - - - /// - /// - /// - /// - /// - internal IEnumerable GetHoldStepAttachemnts(int holdStepID) - { - //var holdStepAttachments = this.db.Query("SELECT * FROM LTWorkRequestAttachment WHERE HoldStepID = @HoldStep ORDER BY UploadDateTime", new { holdStep }, commandType: CommandType.Text).ToList(); - var parameters = new DynamicParameters(); - parameters.Add("@HoldStepID", holdStepID); - var data = this.db.Query("LTGetHoldStepAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - /// - /// - /// - /// - /// - internal IEnumerable GetLotTravHoldStepAttachemnts(int ltHoldStepID) - { - //var holdStepAttachments = this.db.Query("SELECT * FROM LTWorkRequestAttachment WHERE HoldStepID = @HoldStep ORDER BY UploadDateTime", new { holdStep }, commandType: CommandType.Text).ToList(); - var parameters = new DynamicParameters(); - parameters.Add("@LTHoldStepID", ltHoldStepID); - var data = this.db.Query("LTGetLotTravHoldStepAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - /// - /// - /// - /// - /// - internal LTHoldStep GetHoldStep(int holdStepID) - { - var parameters = new DynamicParameters(); - parameters.Add("@HoldStepID", value: holdStepID); - - var data = this.db.Query("LTGetHoldStep", parameters, commandType: CommandType.StoredProcedure).SingleOrDefault(); - return data; - } - - /// - /// - /// - /// - /// - internal LTLotTravelerHoldSteps GetLotTravHoldStep(int ltHoldStepID) - { - var parameters = new DynamicParameters(); - parameters.Add("@LotTravHoldStepID", value: ltHoldStepID); - - var data = this.db.Query("LTGetLotTravHoldStep", parameters, commandType: CommandType.StoredProcedure).SingleOrDefault(); - return data; - } - - /// - /// - /// - /// - internal void InsertLotHoldStepAttachment(LTWorkRequestAttachment attachment) - { - var parameters = new DynamicParameters(); - parameters.Add("@HoldStepID", attachment.LTHoldStepID); - parameters.Add("@FileName", attachment.FileName); - parameters.Add("@FileGUID", attachment.FileGUID); - parameters.Add("@DocType", attachment.DocType); - parameters.Add("@UploadedByID", attachment.UploadedByID); - parameters.Add("@Comments", attachment.Comments); - this.db.Execute("LTInsertHoldStepAttachment", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - internal void InsertLotHoldStepAttachmentRevision(LTWorkRequestAttachment attachment) - { - var parameters = new DynamicParameters(); - parameters.Add("@HoldStepID", attachment.LTHoldStepID); - parameters.Add("@FileName", attachment.FileName); - parameters.Add("@FileGUID", attachment.FileGUID); - parameters.Add("@DocType", attachment.DocType); - parameters.Add("@UploadedByID", attachment.UploadedByID); - parameters.Add("@Comments", attachment.Comments); - this.db.Execute("LTInsertHoldStepAttachmentRevision", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - internal void InsertWorkRequestAttachment(LTWorkRequestAttachment attachment) - { - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", attachment.WorkRequestID); - parameters.Add("@FileName", attachment.FileName); - parameters.Add("@FileGUID", attachment.FileGUID); - parameters.Add("@DocType", attachment.DocType); - parameters.Add("@UploadedByID", attachment.UploadedByID); - parameters.Add("@Comments", attachment.Comments); - this.db.Execute("LTInsertWorkRequestAttachment", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - internal void InsertWorkRequestAttachmentRevision(LTWorkRequestAttachment attachment) - { - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", attachment.WorkRequestID); - parameters.Add("@FileName", attachment.FileName); - parameters.Add("@FileGUID", attachment.FileGUID); - parameters.Add("@DocType", attachment.DocType); - parameters.Add("@UploadedByID", attachment.UploadedByID); - parameters.Add("@Comments", attachment.Comments); - this.db.Execute("LTInsertWorkRequestAttachmentRevision", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - /// - internal int GetRevisedWrkReqIDFromHoldStepID(int prevHoldStepID) - { - int workRequestID = this.db.Query("SELECT LTWorkRequestID FROM LTHoldStep WHERE PreviousHoldStepID = @PrevHoldStepID", new { PrevHoldStepID = prevHoldStepID }, commandType: CommandType.Text).Single(); - - return workRequestID; - } - - /// - /// - /// - /// - /// - internal int GetRevisedWrkReqIDFromPreviousWrkReqID(int prevWorkRequestID) - { - int workRequestID = this.db.Query("SELECT ID FROM LTWorkRequest WHERE PreviousWorkRequestID = @prevWorkRequestID", new { prevWorkRequestID = prevWorkRequestID }, commandType: CommandType.Text).Single(); - - return workRequestID; - } - - - - /// - /// - /// - /// - /// - internal IEnumerable GetWorkRequestAttachments(int workRequestID) - { - //var holdStepAttachments = this.db.Query("SELECT * FROM LTWorkRequestAttachment WHERE HoldStepID = @HoldStep ORDER BY UploadDateTime", new { holdStep }, commandType: CommandType.Text).ToList(); - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", workRequestID); - var data = this.db.Query("LTGetWorkRequestAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - /// - /// - /// - /// - internal void UpdateWorkRequestAttachment(LTWorkRequestAttachment attachment) - { - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestAttachmentID", attachment.ID); - parameters.Add("@DocType", attachment.DocType); - parameters.Add("@Comments", attachment.Comments); - - this.db.Execute("LTUpdateWorkRequestAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - internal void UpdateWorkRequestAttachmentRevision(LTWorkRequestAttachment attachment, int previousWorkRequestAttachmentID) - { - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestAttachmentID", attachment.ID); - parameters.Add("@FileName", attachment.FileName); - parameters.Add("@DocType", attachment.DocType); - parameters.Add("@Comments", attachment.Comments); - parameters.Add("@PreviousWorkRequestAttachmentID", previousWorkRequestAttachmentID); - - this.db.Execute("LTUpdateWorkRequestAttachmentRevision", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - internal void DeleteWorkRequestAttachment(int workRequestAttachmentID) - { - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestAttachmentID", workRequestAttachmentID); - this.db.Execute("LTDeleteWorkRequestAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - - internal void DeleteWorkRequestAttachmentRevision(int workRequestAttachmentID) - { - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestAttachmentID", workRequestAttachmentID); - this.db.Execute("LTDeleteWorkRequestAttachmentRevision", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - /// - /// - /// - public int SubmitDocument(int workRequestID, int userID, int documentType, out int allowedITAR) - { - allowedITAR = 1; - string subRoles = ""; - subRoles = wfDMO.GetSubRoleItems(workRequestID, documentType); - - // bubble the error - int appoverCount = 0; - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", workRequestID); - parameters.Add("@UserID", userID); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@SubRoleCategoriesClause", subRoles); - parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - parameters.Add("@AllowedITAR", allowedITAR, dbType: DbType.Int32, direction: ParameterDirection.Output); - this.db.Execute("LTSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); - - appoverCount = parameters.Get("@AppoverCount"); - allowedITAR = parameters.Get("@AllowedITAR"); - - return appoverCount; - - } - - /// - /// Release lock on all the documents locked by the current user - /// - /// - public void ReleaseLockOnDocument(int userID, int workRequestID) - { - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", workRequestID); - parameters.Add("@UserID", userID); - this.db.Execute("LTReleaseLockOnDocuments", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - public void ReleaseLockOnLotTravelerUpdateDoc(int userID, int ltLotID) - { - var parameters = new DynamicParameters(); - parameters.Add("@LTLotID", ltLotID); - parameters.Add("@UserID", userID); - this.db.Execute("LTReleaseLockOnLTUpdateDoc", parameters, commandType: CommandType.StoredProcedure); - } - - - - - /// - /// - /// - /// - /// - public List GetRejectionOrginatorEmailList(int workRequestID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", workRequestID); - var emailList = this.db.Query("LTGetRejectionOrginatorEmailList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return emailList; - - } - - /// - /// - /// - /// - /// - /// - public int CreateWorkRequestRevision(LTWorkRequest data, int userID) - { - int newWorkRequestID = -1; - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - parameters.Add("@ChangeComments", data.RevisionComments); - parameters.Add("@CurrentStep", data.CurrentStep); - parameters.Add("@LTWorkRequestID", data.ID); - parameters.Add("@Title", data.Title); - parameters.Add("@LotType", data.LotType); - parameters.Add("@EngLotStartRequired", data.EngLotStartRequired); - parameters.Add("@LotTypeConversion", data.LotTypeConversion); - parameters.Add("@QualLot", data.QualLot); - parameters.Add("@PurposeOfRequest", data.PurposeOfRequest); - parameters.Add("@PlannedLotStartDate", data.PlannedLotStartDate); - parameters.Add("@PlannedScheduledCloseDate", data.PlannedScheduledCloseDate); - parameters.Add("@ChargeDepartment", data.ChargeDepartment); - parameters.Add("@AllocationToUse", data.AllocationToUse); - parameters.Add("@PredictedCyleTime", data.PredictedCyleTime); - parameters.Add("@DeptChargedForRawWafers", data.ChargeDepartment); - parameters.Add("@StartQty", data.StartQty); - parameters.Add("@TotalQty", data.TotalQty); - parameters.Add("@WIPArea", data.WIPArea); - parameters.Add("@LotStartDate", data.LotStartDate); - parameters.Add("@LotNumber", data.LotNumber); - parameters.Add("@WIPPartNumber", data.WIPPartNumber); - parameters.Add("@PartDescription", data.PartDescription); - parameters.Add("@DefaultEPISiliconPartNumber", data.DefaultEPISiliconPartNumber); - parameters.Add("@ProcessFlow", data.ProcessFlow); - parameters.Add("@EmployeeID", data.EmployeeID); - parameters.Add("@VerbComment", data.VerbComment); - parameters.Add("@RecordSiliconLotInSPNTapeTagTotrav", data.RecordSiliconLotInSPNTapeTagTotrav); - parameters.Add("@SiliconLotNoCassette1", data.SiliconLotNoCassette1); - parameters.Add("@SiliconOnHand", data.SiliconOnHand); - parameters.Add("@SiliconExpectedDueDate", data.SiliconExpectedDueDate); - parameters.Add("@SiliconComments", data.SiliconComments); - parameters.Add("@ReticleOnHand", data.ReticleOnHand); - parameters.Add("@ReticleExpectedDueDate", data.ReticleExpectedDueDate); - parameters.Add("@ReticleComments", data.ReticleComments); - parameters.Add("@SPNTransferOnHand", data.SPNTransferOnHand); - parameters.Add("@SPNTransferExpectedDueDate", data.SPNTransferExpectedDueDate); - parameters.Add("@SPNTransferComments", data.SPNTransferComments); - parameters.Add("@ProbeCardOnHand", data.ProbeCardOnHand); - parameters.Add("@ProbeCardExpectedDueDate", data.ProbeCardExpectedDueDate); - parameters.Add("@ProbeCardComments", data.ProbeCardComments); - parameters.Add("@ProbeRecipeOnHand", data.ProbeRecipeOnHand); - parameters.Add("@ProbeRecipeExpectedDueDate", data.ProbeRecipeExpectedDueDate); - parameters.Add("@ProbeRecipeComments", data.ProbeRecipeComments); - parameters.Add("@LotStartCheckListComments", data.LotStartCheckListComments); - parameters.Add("@ProcessChangeDetailsOnHand", data.ProcessChangeDetailsOnHand); - parameters.Add("@ProcessChangeDetailsDueDate", data.ProcessChangeDetailsDueDate); - parameters.Add("@PCRBNumber", data.PCRBNumber); - parameters.Add("@LotStartCheckListComments", data.LotStartCheckListComments); - parameters.Add("@NewWorkRequestID", data.ID, direction: ParameterDirection.InputOutput); - this.db.Execute("LTCreateWorkRequestRevision", parameters, commandType: CommandType.StoredProcedure); - newWorkRequestID = parameters.Get("@NewWorkRequestID"); - - return newWorkRequestID; - } - - /// - /// - /// - /// - /// - public List GetWorkReqRevisions(int swrNumber) - { - var revisions = this.db.Query("SELECT ID, Revision AS RevisionNumber FROM LTWorkRequest WHERE SWRNumber = @SWRNUmber ORDER BY Revision ", new { SWRNUmber = swrNumber }, commandType: CommandType.Text).ToList(); - return revisions; - } - - /// - /// - /// - /// - /// - public List GetLotTravRevisions(int ltLotID) - { - var revisions = this.db.Query("SELECT ID, RevisionNumber FROM LTLotTravelerRevisionAttrib WHERE LTLotID = @ltLotID ORDER BY RevisionNumber ", new { ltLotID = ltLotID }, commandType: CommandType.Text).ToList(); - return revisions; - } - - - /// - /// - /// - /// - /// - /// - public void InsertLot(LTLot lot) - { - MiscDMO.GetLTLotInformation(lot); - - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", lot.WorkRequestID); - parameters.Add("@LotNumber", lot.LotNumber); - parameters.Add("@WIPPartNumber", lot.WIPPartNumber); - parameters.Add("@WaferQty", lot.WaferQty); - parameters.Add("@PartDescription", lot.PartDescription); - parameters.Add("@Process", lot.Process); - parameters.Add("@Location", lot.Location); - parameters.Add("@Operation", lot.Operation); - parameters.Add("@LotStatus", lot.LotStatus); - parameters.Add("@UploadedBy", lot.LotUploadedBy); - - parameters.Add("@WRWithExistingLot", dbType: DbType.Int32, direction: ParameterDirection.Output); - - - this.db.Execute("LTInsertLTLot", parameters, commandType: CommandType.StoredProcedure); - - - //int lotID = parameters.Get("@LotID"); - if (parameters.Get("@WRWithExistingLot") != 0) - { - - lot.WRWithExistingLot = parameters.Get("@WRWithExistingLot"); - } - - //return lotID; - - } - - /// - /// - /// - /// - /// - public IEnumerable GetLotList(int workRequestID) - { - StringBuilder sql = new StringBuilder(); - sql.Append("SELECT L.*, U.FirstName + ' ' + U.LastName AS UploadedByName,CASE WHEN TravelerClosed = 0 THEN 'Open' ELSE 'Closed' END AS TravelerStatus "); - sql.Append("FROM LTLot L LEFT JOIN Users U ON L.LotUploadedBy = U.UserID "); - sql.Append("WHERE WorkRequestID = @workRequestID ORDER BY LotNumber "); - var lots = this.db.Query(sql.ToString(), new { @workRequestID = workRequestID }, commandType: CommandType.Text).ToList(); - return lots; - } - - /// - /// - /// - /// - /// - public IEnumerable GetLotListBasedOnSWRNumber(int swrNumber) - { - StringBuilder sql = new StringBuilder(); - sql.Append("SELECT L.*, U.FirstName + ' ' + U.LastName AS UploadedByName,CASE WHEN TravelerClosed = 0 THEN 'Open' ELSE 'Closed' END AS TravelerStatus "); - sql.Append("FROM LTWorkRequest WR INNER JOIN LTLot L ON WR.ID = L.WorkRequestID AND WR.IsCurrentRevision = 1 "); - sql.Append("LEFT JOIN Users U ON L.LotUploadedBy = U.UserID "); - sql.Append("WHERE WR.SWRNumber = @SWRNumber ORDER BY LotNumber "); - var lots = this.db.Query(sql.ToString(), new { @SWRNumber = swrNumber }, commandType: CommandType.Text).ToList(); - //var lots = this.db.Query("SELECT L.*, U.FirstName + ' ' + U.LastName AS UploadedByName FROM LTWorkRequest WR INNER JOIN LTLot L ON WR.ID = L.WorkRequestID AND WR.IsCurrentRevision = 1 LEFT JOIN Users U ON L.LotUploadedBy = U.UserID WHERE WR.SWRNumber = @SWRNumber ORDER BY LotNumber ", new { swrNumber }, commandType: CommandType.Text).ToList(); - return lots; - } - - /// - /// - /// - /// - /// - public IEnumerable GetLotsWithTraveler(int workRequestID) - { - var lotList = this.db.Query("SELECT ID AS LotID, LotNumber FROM LTLot WHERE WorkRequestID = @workRequestID AND IsTravelerGenerated = 1 ORDER BY LotNumber ", new { workRequestID = workRequestID }, commandType: CommandType.Text).ToList(); - return lotList; - } - - /// - /// - /// - /// - /// - /// - public void CreateTraveler(int ltLotID, int workRequestID , int UserID) - { - var parameters = new DynamicParameters(); - parameters.Add("@LTLotID", ltLotID); - parameters.Add("@WorkRequestID", workRequestID); - parameters.Add("@UserID", UserID); - this.db.Execute("LTCreateLotTraveler", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - public LTLotTravelerHeaderViewModel GetLotTravelerHeaderForUpdate(int ltLotID, int UserID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@LTLotID", ltLotID); - parameters.Add("@UserID", UserID); - var data = this.db.Query("LTGetLotTravelerHeaderForUpdate", parameters, commandType: CommandType.StoredProcedure).Single(); - return data; - - } - - /// - /// - /// - /// - /// - /// - public LTLotTravelerHeaderViewModel GetLotTravelerHeaderForReadOnly(int ltLotID, int revisionNumber) - { - - var parameters = new DynamicParameters(); - parameters.Add("@LTLotID", ltLotID); - parameters.Add("@RevisionNumber", revisionNumber); - var data = this.db.Query("LTGetLotTravelerHeaderForReadOnly", parameters, commandType: CommandType.StoredProcedure).Single(); - return data; - - } - - - /// - public IEnumerable GetLotTravHoldSteps(int ltLotID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@LTLotID", ltLotID); - var data = this.db.Query("LTGetLotTravelerHoldSteps", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - - } - - - - /// - /// - /// - /// - /// - public IEnumerable GetLotTravHoldStepsPending(int ltLotID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@LTLotID", ltLotID); - var data = this.db.Query("LTGetLotTravelerHoldStepsPending", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - - } - - - /// - /// - /// - /// - /// - public IEnumerable GetLotTravHoldStepsCompleted(int ltLotID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@LTLotID", ltLotID); - var data = this.db.Query("LTGetLotTravelerHoldStepsCompleted", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - - } - - /// - /// - /// - /// - /// - /// - public IEnumerable GetLotTravelerHolStepsByRevision(int ltLotID, int revisionNumber) - { - - var parameters = new DynamicParameters(); - parameters.Add("@LTLotID", ltLotID); - parameters.Add("@RevisionNumber", revisionNumber); - var data = this.db.Query("LTGetLotTravelerHoldStepsByRevision", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - - } - - - - - - /// - /// - /// - /// - /// - public int CreateLotTravelerRevision(LTLotTravelerHoldSteps model, int userID) - { - - var parameters = new DynamicParameters(); - parameters.Add("@CurrLotTravelerRevisionID", model.LotTravelerRevisionID); - parameters.Add("@LTLotID", model.LTLotID); - parameters.Add("@NewUpdatedBy", userID); - parameters.Add("@ChangeComments", model.RevisionComments); - parameters.Add("@NewLotTravelerRevisionID", model.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - this.db.Execute("LTCreateLotTravHoldStepsRevision", parameters, commandType: CommandType.StoredProcedure); - - int newLotTravRevisionID = parameters.Get("@NewLotTravelerRevisionID"); - // model.ID = id; - - return newLotTravRevisionID; - - } - - - /// - /// - /// - /// - /// - /// - public int CanAddLocationOperation(LTLotTravelerHoldSteps model) - { - int result = 0; - - var parameters = new DynamicParameters(); - parameters.Add("@LTLotID", model.LTLotID); - parameters.Add("@Location", model.Location); - parameters.Add("@OperSequence", model.OperSequence); - parameters.Add("@Operation", model.Operation); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - - this.db.Execute("LTCanAddLocationOperation", parameters, commandType: CommandType.StoredProcedure); - result = parameters.Get("@Result"); - return result; - - } - - - /// - /// - /// - /// - /// - /// - public void RestoreLotTravToPrevRevision(int prevLotTravRevID, int newLotTravRevID) - { - var parameters = new DynamicParameters(); - parameters.Add("@PrevLotTravelerRevisionID", prevLotTravRevID); - parameters.Add("@NewLotTravelerRevisionID", newLotTravRevID); - - this.db.Execute("LTRestoreLotTravToPrevRevision", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - /// - public int UpdateRevisedLotTravelerHoldStep(LTLotTravelerHoldSteps model, int userID) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@LotTravHoldStepID", model.ID); - parameters.Add("@NewLocation", model.Location); - parameters.Add("@NewOperSequence", model.OperSequence); - parameters.Add("@NewOperation", model.Operation); - parameters.Add("@NewOperationDescription", model.OperationDescription); - parameters.Add("@NewChangeInstructions", model.ChangeInstructions); - parameters.Add("@NewUpdatedBy", userID); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - - this.db.Execute("LTUpdateRevisedLotTravelerHoldStep", parameters, commandType: CommandType.StoredProcedure); - result = parameters.Get("@Result"); - return result; - } - - /// - /// - /// - /// - public int UpdateLotTravelerHoldStep(LTLotTravelerHoldSteps model, int userID) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@LotTravHoldStepID", model.ID); - parameters.Add("@NewLocation", model.Location); - parameters.Add("@NewOperSequence", model.OperSequence); - parameters.Add("@NewOperation", model.Operation); - parameters.Add("@NewOperationDescription", model.OperationDescription); - parameters.Add("@NewChangeInstructions", model.ChangeInstructions); - parameters.Add("@NewUpdatedBy", userID); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - - this.db.Execute("LTUpdateLotTravelerHoldStep", parameters, commandType: CommandType.StoredProcedure); - - result = parameters.Get("@Result"); - return result; - } - - - /// - /// - /// - /// - //public void InsertLotTravelerRevision(LTLotTravelerHoldSteps model) - //{ - - // var parameters = new DynamicParameters(); - // parameters.Add("@LotTravelerRevisionID", model.ID); - // parameters.Add("@NewLocation", model.Location); - // parameters.Add("@NewOperation", model.Operation); - // parameters.Add("@NewOperationDescription", model.OperationDescription); - // parameters.Add("@NewChangeInstruction", model.ChangeInstructions); - - // this.db.Execute("LTInsertLotTravelerRevision", parameters, commandType: CommandType.StoredProcedure); - //} - - /// - /// - /// - /// - public int InsertLotTravelerHoldStep(LTLotTravelerHoldSteps model, int userID) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@LTLotTravHoldStepID", model.ID); - parameters.Add("@LTLotID", model.LTLotID); - parameters.Add("@Location", model.Location); - parameters.Add("@OperSequence", model.OperSequence); - parameters.Add("@Operation", model.Operation); - parameters.Add("@OperationDescription", model.OperationDescription); - parameters.Add("@ChangeInstructions", model.ChangeInstructions); - parameters.Add("@UpdatedBy", userID); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - - this.db.Execute("LTInsertLotTravelerHoldStep", parameters, commandType: CommandType.StoredProcedure); - result = parameters.Get("@Result"); - - return result; - } - - /// - /// - /// - /// - public void DeleteLot(int ltLotID) - { - var parameters = new DynamicParameters(); - parameters.Add("@LTLotID", ltLotID); - this.db.Execute("LTDeleteLot", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - /// - /// - /// - public void UpdateLotTravlerExecution(int lotTravHoldStepID, string taskComments, bool CompletedFlag, int userID) - { - var parameters = new DynamicParameters(); - parameters.Add("@LotTravHoldStepID", lotTravHoldStepID); - parameters.Add("@TaskComments", taskComments); - parameters.Add("@CompletedFlag", CompletedFlag); - parameters.Add("@UserID", userID); - - this.db.Execute("LTUpdateLotTravlerExecution", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - /// - /// - public LotTravelerPdf GetLotTravlerPdf(int ltLotID, int revisionNumber) - { - var data = new LotTravelerPdf(); - - var parameters = new DynamicParameters(); - parameters.Add("@LTLotID", ltLotID); - parameters.Add("@RevisionNumber", revisionNumber); - - using (var multipleResultItems = this.db.QueryMultiple("LTGetLotTravelerForPDF", parameters, commandType: CommandType.StoredProcedure)) - { - data = multipleResultItems.Read().SingleOrDefault(); - - var ltTaskList = multipleResultItems.Read().ToList(); - if (data != null && ltTaskList != null) - { - if (ltTaskList.Count > 0) - data.Tasklist.AddRange(ltTaskList); + db.Execute("LTDeleteAffectedDepartments", parameters, commandType: CommandType.StoredProcedure); + List wrDepIDs = data.DepartmentIDs; + if (wrDepIDs != null) { + foreach (int depId in wrDepIDs) { + parameters = new DynamicParameters(); + parameters.Add("@WorkRequestID", data.ID); + parameters.Add("@DepartmentID", depId); + db.Execute("LTInsertAffectedDepartments", parameters, commandType: CommandType.StoredProcedure); + } } + parameters = new DynamicParameters(); + parameters.Add("@WorkRequestID", data.ID); + db.Execute("LTDeleteAffectedModules", parameters, commandType: CommandType.StoredProcedure); + List wrModuleIDs = data.ModuleIDs; + if (wrModuleIDs != null) { + foreach (int moduleID in wrModuleIDs) { + parameters = new DynamicParameters(); + parameters.Add("@WorkRequestID", data.ID); + parameters.Add("@ModuleID", moduleID); + db.Execute("LTInsertAffectedModules", parameters, commandType: CommandType.StoredProcedure); + } + } + transanction.Complete(); + } catch (Exception ex) { + transanction.Dispose(); + throw new Exception(ex.Message + " " + ex.InnerException); } - - - //var data = this.db.Query("LTGetLotTravelerForPDF", parameters, commandType: CommandType.StoredProcedure).Single(); - return data; - } + // have to do it outside of the Transaction scope because the OPENQUERY to TEMIRWAP019 LINKED server does not work + parameters = new DynamicParameters(); + parameters.Add("@WorkRequestID", data.ID); + db.Execute("LTUpdateIsITAR", parameters, commandType: CommandType.StoredProcedure); - /// - /// - /// - /// - /// - public IEnumerable GetWorkReqApprovalLogHistory(int swrNumber) - { + return result; + } - var parameters = new DynamicParameters(); - parameters.Add("@SWRNumber", swrNumber); - var data = this.db.Query("LTGetWorkRequestApprovalLogHistory", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } + internal LTWorkRequestAttachment GetWorkRequestAttachDetail(int wrAttachmentID) { + var wrAttach = db.Query("SELECT ID, FileName ,DocType, Comments FROM LTWorkRequestAttachment WHERE ID = @wrAttachmentID ", new { wrAttachmentID = wrAttachmentID }, commandType: CommandType.Text).Single(); + return wrAttach; + } - /// - /// - /// - /// - /// - public IEnumerable GetWorkReqRevisionHistory(int swrNumber) - { + internal IEnumerable GetMaterialDetails(int workRequestID) { + DynamicParameters parameters = new(); + parameters.Add("@workRequestID", value: workRequestID); - var parameters = new DynamicParameters(); - parameters.Add("@SWRNumber", swrNumber); - var data = this.db.Query("LTGetWorkRequestRevHistory", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } + List data = db.Query("LTGetMaterialDetails", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + /// + /// Update via the edit screen + /// - /// - /// - /// - /// - /// - public IEnumerable GetLotTravelerRevisionHistory(int lotID) - { + internal void UpdateMaterialDetail(LTMaterialViewModel model, int userID) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@LTMaterialID", model.ID); + parameters.Add("@EPISiliconPartNumber", model.@EPISiliconPartNumber); + parameters.Add("@Quantity", model.Quantity); + parameters.Add("@Source", model.Source); + parameters.Add("@Supplier", model.Supplier); + parameters.Add("@UpdatedBy", userID); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - var parameters = new DynamicParameters(); - parameters.Add("@LotID", lotID); - var data = this.db.Query("LTGetLotTravelerRevHistory", parameters, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - - /// - /// - /// - /// - internal void InsertLotTravLotHoldStepAttachment(LTLotTravAttachment attachment) - { - var parameters = new DynamicParameters(); - parameters.Add("@LTHoldStepID", attachment.LTLotTravHoldStepID); - parameters.Add("@FileName", attachment.FileName); - parameters.Add("@FileGUID", attachment.FileGUID); - parameters.Add("@DocType", attachment.DocType); - parameters.Add("@UploadedByID", attachment.UploadedByID); - parameters.Add("@LotTravelerRevisionID", attachment.LotTravelerRevisionID); - this.db.Execute("LTInsertLotTravHoldStepAttachment", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - internal void InsertLotTravLotHoldStepAttachmentRevision(LTLotTravAttachment attachment) - { - var parameters = new DynamicParameters(); - parameters.Add("@LTHoldStepID", attachment.LTLotTravHoldStepID); - parameters.Add("@FileName", attachment.FileName); - parameters.Add("@FileGUID", attachment.FileGUID); - parameters.Add("@DocType", attachment.DocType); - parameters.Add("@UploadedByID", attachment.UploadedByID); - parameters.Add("@LotTravelerRevisionID", attachment.LotTravelerRevisionID); - this.db.Execute("LTInsertLotTravHoldStepAttachmentRevision", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - /// - internal int IsWorkRequestDocLockedByUser(int workRequestID, int userID) - { - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", workRequestID); - parameters.Add("@UserID", userID); - var data = this.db.Query("LTIsWorkRequestDocLockedByUser", parameters, commandType: CommandType.StoredProcedure).Single(); - - return data; - - } - - - /// - /// - /// - /// - /// - internal int CloseTraveler(int ltLotID, int userID, string reason) - { - int result = 0; - var parameters = new DynamicParameters(); - parameters.Add("@LtLotID", ltLotID); - parameters.Add("@UserID", userID); - parameters.Add("@Reason", reason); - parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); - - this.db.Execute("LTCloseTraveler", parameters, commandType: CommandType.StoredProcedure); - - result = parameters.Get("@Result"); - - return result; - - - - - } - - /// - /// - /// - /// - /// - internal string GetFileName(string fileGUID, int typeOfDoc) - { - var parameters = new DynamicParameters(); - parameters.Add("@FileGUID", fileGUID); - parameters.Add("@TypeOfDoc", typeOfDoc); - var fileName = this.db.Query("LTGetFileName", parameters, commandType: CommandType.StoredProcedure).Single(); - return fileName; - } - - public void ReassignOriginator(int workRequestID, int newOriginatorID, string comments, int userID) - { - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", workRequestID); - parameters.Add("@NewOriginatorID", newOriginatorID); - parameters.Add("@Comments", comments); - parameters.Add("@UserID", userID); - - this.db.Execute("LTReassignOriginator", parameters, commandType: CommandType.StoredProcedure); + db.Execute("LTUpdateMaterialDetail", parameters, commandType: CommandType.StoredProcedure); + result = parameters.Get("@Result"); + if (result == -1) { + throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); } } -} + + /// + /// Update via the revision screen + /// + + internal void UpdateMaterialDetail(LTMaterial model, int userID) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@LTMaterialID", model.ID); + parameters.Add("@EPISiliconPartNumber", model.@EPISiliconPartNumber); + parameters.Add("@Quantity", model.Quantity); + parameters.Add("@Source", model.Source); + parameters.Add("@Supplier", model.Supplier); + parameters.Add("@UpdatedBy", userID); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + + db.Execute("LTUpdateMaterialDetail", parameters, commandType: CommandType.StoredProcedure); + + result = parameters.Get("@Result"); + if (result == -1) { + throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); + } + } + + internal void UpdateMaterialDetailRevision(LTMaterial model, int previousMaterialID) { + DynamicParameters parameters = new(); + parameters.Add("@LTMaterialID", model.ID); + parameters.Add("@EPISiliconPartNumber", model.EPISiliconPartNumber); + parameters.Add("@Quantity", model.Quantity); + parameters.Add("@Source", model.Source); + parameters.Add("@Supplier", model.Supplier); + parameters.Add("@PreviousMaterialID", previousMaterialID); + + db.Execute("LTUpdateMaterialDetailRevision", parameters, commandType: CommandType.StoredProcedure); + } + + internal void InsertMaterialDetail(LTMaterialViewModel model, int userID) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@LTMaterialID", model.ID, direction: ParameterDirection.InputOutput); + parameters.Add("@EPISiliconPartNumber", model.@EPISiliconPartNumber); + parameters.Add("@Quantity", model.Quantity); + parameters.Add("@Source", model.Source); + parameters.Add("@Supplier", model.Supplier); + parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); + parameters.Add("@UpdatedBy", userID); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + + db.Execute("LTInsertMaterialDetail", parameters, commandType: CommandType.StoredProcedure); + + int id = parameters.Get("@LTMaterialID"); + model.ID = id; + + result = parameters.Get("@Result"); + if (result == -1) { + throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); + } + } + + /// + /// For Revisioing the data + /// + + internal void InsertMaterialDetail(LTMaterial model, int userID) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@LTMaterialID", model.ID, direction: ParameterDirection.InputOutput); + parameters.Add("@EPISiliconPartNumber", model.@EPISiliconPartNumber); + parameters.Add("@Quantity", model.Quantity); + parameters.Add("@Source", model.Source); + parameters.Add("@Supplier", model.Supplier); + parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); + parameters.Add("@UpdatedBy", userID); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + + db.Execute("LTInsertMaterialDetail", parameters, commandType: CommandType.StoredProcedure); + + int id = parameters.Get("@LTMaterialID"); + model.ID = id; + + result = parameters.Get("@Result"); + if (result == -1) { + throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); + } + } + + internal void DeleteMaterialDetail(int LTMaterialID) { + DynamicParameters parameters = new(); + parameters.Add("@LTMaterialID", LTMaterialID); + db.Execute("LTDeleteMaterial", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteMaterialDetailRevision(int materialID) { + DynamicParameters parameters = new(); + parameters.Add("@MaterialID", materialID); + db.Execute("LTDeleteMaterialRevision", parameters, commandType: CommandType.StoredProcedure); + } + + internal List GetBaseFlowLocations(string processFlow) { + List baseFlowLocations = db.Query("SELECT DISTINCT LOC as Location FROM vSPNPDB_FLOWLOCS WHERE PROCESS = @ProcessFlow ORDER BY LOC ", new { ProcessFlow = processFlow }, commandType: CommandType.Text).ToList(); + return baseFlowLocations; + } + + internal LTMaterial GetMaterialRecord(int materialID) { + var material = db.Query("SELECT * FROM LTMaterial WHERE ID = @materialID ", new { materialID }, commandType: CommandType.Text).Single(); + return material; + } + + internal List GetBaseFlowOperations(string processFlow, string loc) { + List baseFlowOperations = db.Query( + "SELECT DISTINCT " + + " LTRIM(RTRIM(OPER)) + '-' + LTRIM(RTRIM(SEQ)) as Operation, " + + " LTRIM(RTRIM(OPER)) as OperCode, " + + " LTRIM(RTRIM(SEQ)) as SeqCode, " + + " LTRIM(RTRIM([OPDESC])) + ' (' + LTRIM(RTRIM([AREA])) + ')' AS 'OperationDesc' " + + "FROM vSPNPDB_FLOWLOCS " + + "WHERE PROCESS = @ProcessFlow AND LOC = @LOC " + + "ORDER BY Operation ", + new { ProcessFlow = processFlow, LOC = loc }, commandType: CommandType.Text).ToList(); + return baseFlowOperations; + } + + internal List GetPartNumbers() { + List baseFlowOperations = db.Query("SELECT DISTINCT TOP 100 [MP_PART_NUMBER] AS PartNumber, MP_DESCRIPTION + ' ~ ' + MP_PART_NUMBER AS SiliconAndDesc FROM vFAB2SPN_MP_RECORD ORDER BY MP_PART_NUMBER ", commandType: CommandType.Text).ToList(); + return baseFlowOperations; + } + + internal IEnumerable GetHoldSteps(int workRequestID) { + DynamicParameters parameters = new(); + parameters.Add("@workRequestID", value: workRequestID); + + List data = db.Query("LTGetHoldSteps", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + internal void InsertHoldStep(LTHoldStep model) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@LTHoldStepID", model.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@BaseFlow", model.BaseFlow); + parameters.Add("@BaseFlowLocation", model.Location); + parameters.Add("@BaseFlowOperationSeq", model.OperSequence); + parameters.Add("@BaseFlowOperation", model.Operation); + parameters.Add("@OperationDescription", model.OperationDescription); + parameters.Add("@ChangeInstruction", model.ChangeInstructions); + parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); + parameters.Add("@UpdatedBy", model.UpdatedBy); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + db.Execute("LTInsertHoldStep", parameters, commandType: CommandType.StoredProcedure); + + int id = parameters.Get("@LTHoldStepID"); + model.ID = id; + + result = parameters.Get("@Result"); + + //if (result == -1) + //{ + // throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); + //} + + } + + internal void UpdateHoldStep(LTHoldStep model) { + DynamicParameters parameters = new(); + parameters.Add("@LTHoldStepID", model.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@BaseFlow", model.BaseFlow); + parameters.Add("@BaseFlowOperationSeq", model.OperSequence); + parameters.Add("@BaseFlowLocation", model.Location); + parameters.Add("@BaseFlowOperation", model.Operation); + parameters.Add("@OperationDescription", model.OperationDescription); + parameters.Add("@ChangeInstruction", model.ChangeInstructions); + parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); + parameters.Add("@UpdatedBy", model.UpdatedBy); + + db.Execute("LTUpdateHoldStep", parameters, commandType: CommandType.StoredProcedure); + + //int id = parameters.Get("@LTHoldStepID"); + //model.ID = id; + } + + internal void InsertHoldStepRevision(LTHoldStep model) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@LTHoldStepID", model.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@BaseFlow", model.BaseFlow); + parameters.Add("@BaseFlowLocation", model.Location); + parameters.Add("@BaseFlowOperationSeq", model.OperSequence); + parameters.Add("@BaseFlowOperation", model.Operation); + parameters.Add("@OperationDescription", model.OperationDescription); + parameters.Add("@ChangeInstruction", model.ChangeInstructions); + parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); + parameters.Add("@UpdatedBy", model.UpdatedBy); + + db.Execute("LTInsertHoldStepRevision", parameters, commandType: CommandType.StoredProcedure); + + int id = parameters.Get("@LTHoldStepID"); + model.ID = id; + } + + internal void UpdateHoldStepRevision(LTHoldStep model) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@LTHoldStepID", model.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + //parameters.Add("@BaseFlow", model.BaseFlow); + parameters.Add("@BaseFlowLocation", model.Location); + parameters.Add("@BaseFlowOperationSeq", model.OperSequence); + parameters.Add("@BaseFlowOperation", model.Operation); + parameters.Add("@OperationDescription", model.OperationDescription); + parameters.Add("@ChangeInstruction", model.ChangeInstructions); + parameters.Add("@LTWorkRequestID", model.LTWorkRequestID); + parameters.Add("@UpdatedBy", model.UpdatedBy); + //parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + + db.Execute("LTUpdateHoldStepRevision", parameters, commandType: CommandType.StoredProcedure); + + //result = parameters.Get("@Result"); + //if (result == -1) + //{ + // throw new Exception("Cannot add the Hold Step as the step has already been passed in the Mfg Process."); + //} + + } + + internal void DeleteHoldStep(int holdStepID, int userID) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@HoldStepID", holdStepID); + parameters.Add("@UpdatedBy", userID); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + + db.Execute("LTDeleteHoldStep", parameters, commandType: CommandType.StoredProcedure); + + result = parameters.Get("@Result"); + if (result == -1) { + throw new Exception("In order to do the UPDATE or SUBMIT operation the record needs to exclusively locked by you.\nThe record was unlocked by the system due to inactivity for more than 30 minutes, hence the update was not successful"); + } + } + + internal void DeleteHoldStepRevision(int holdStepID) { + DynamicParameters parameters = new(); + parameters.Add("@HoldStepID", holdStepID); + db.Execute("LTDeleteHoldStepRevision", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteLotTravHoldStep(int lotTravHoldStepID) { + DynamicParameters parameters = new(); + parameters.Add("@LotTravHoldStepID", lotTravHoldStepID); + db.Execute("LTDeleteLotTravHoldStep", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteLotTravHoldStepRevision(int lotTravHoldStepID) { + DynamicParameters parameters = new(); + parameters.Add("@LotTravHoldStepID", lotTravHoldStepID); + db.Execute("LTDeleteLotTravHoldStepRevision", parameters, commandType: CommandType.StoredProcedure); + } + + internal IEnumerable GetHoldStepAttachemnts(int holdStepID) { + //var holdStepAttachments = this.db.Query("SELECT * FROM LTWorkRequestAttachment WHERE HoldStepID = @HoldStep ORDER BY UploadDateTime", new { holdStep }, commandType: CommandType.Text).ToList(); + DynamicParameters parameters = new(); + parameters.Add("@HoldStepID", holdStepID); + List data = db.Query("LTGetHoldStepAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + internal IEnumerable GetLotTravHoldStepAttachemnts(int ltHoldStepID) { + //var holdStepAttachments = this.db.Query("SELECT * FROM LTWorkRequestAttachment WHERE HoldStepID = @HoldStep ORDER BY UploadDateTime", new { holdStep }, commandType: CommandType.Text).ToList(); + DynamicParameters parameters = new(); + parameters.Add("@LTHoldStepID", ltHoldStepID); + List data = db.Query("LTGetLotTravHoldStepAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + internal LTHoldStep GetHoldStep(int holdStepID) { + DynamicParameters parameters = new(); + parameters.Add("@HoldStepID", value: holdStepID); + + var data = db.Query("LTGetHoldStep", parameters, commandType: CommandType.StoredProcedure).SingleOrDefault(); + return data; + } + + internal LTLotTravelerHoldSteps GetLotTravHoldStep(int ltHoldStepID) { + DynamicParameters parameters = new(); + parameters.Add("@LotTravHoldStepID", value: ltHoldStepID); + + var data = db.Query("LTGetLotTravHoldStep", parameters, commandType: CommandType.StoredProcedure).SingleOrDefault(); + return data; + } + + internal void InsertLotHoldStepAttachment(LTWorkRequestAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@HoldStepID", attachment.LTHoldStepID); + parameters.Add("@FileName", attachment.FileName); + parameters.Add("@FileGUID", attachment.FileGUID); + parameters.Add("@DocType", attachment.DocType); + parameters.Add("@UploadedByID", attachment.UploadedByID); + parameters.Add("@Comments", attachment.Comments); + db.Execute("LTInsertHoldStepAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal void InsertLotHoldStepAttachmentRevision(LTWorkRequestAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@HoldStepID", attachment.LTHoldStepID); + parameters.Add("@FileName", attachment.FileName); + parameters.Add("@FileGUID", attachment.FileGUID); + parameters.Add("@DocType", attachment.DocType); + parameters.Add("@UploadedByID", attachment.UploadedByID); + parameters.Add("@Comments", attachment.Comments); + db.Execute("LTInsertHoldStepAttachmentRevision", parameters, commandType: CommandType.StoredProcedure); + } + + internal void InsertWorkRequestAttachment(LTWorkRequestAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", attachment.WorkRequestID); + parameters.Add("@FileName", attachment.FileName); + parameters.Add("@FileGUID", attachment.FileGUID); + parameters.Add("@DocType", attachment.DocType); + parameters.Add("@UploadedByID", attachment.UploadedByID); + parameters.Add("@Comments", attachment.Comments); + db.Execute("LTInsertWorkRequestAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal void InsertWorkRequestAttachmentRevision(LTWorkRequestAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", attachment.WorkRequestID); + parameters.Add("@FileName", attachment.FileName); + parameters.Add("@FileGUID", attachment.FileGUID); + parameters.Add("@DocType", attachment.DocType); + parameters.Add("@UploadedByID", attachment.UploadedByID); + parameters.Add("@Comments", attachment.Comments); + db.Execute("LTInsertWorkRequestAttachmentRevision", parameters, commandType: CommandType.StoredProcedure); + } + + internal int GetRevisedWrkReqIDFromHoldStepID(int prevHoldStepID) { + int workRequestID = db.Query("SELECT LTWorkRequestID FROM LTHoldStep WHERE PreviousHoldStepID = @PrevHoldStepID", new { PrevHoldStepID = prevHoldStepID }, commandType: CommandType.Text).Single(); + + return workRequestID; + } + + internal int GetRevisedWrkReqIDFromPreviousWrkReqID(int prevWorkRequestID) { + int workRequestID = db.Query("SELECT ID FROM LTWorkRequest WHERE PreviousWorkRequestID = @prevWorkRequestID", new { prevWorkRequestID = prevWorkRequestID }, commandType: CommandType.Text).Single(); + + return workRequestID; + } + + internal IEnumerable GetWorkRequestAttachments(int workRequestID) { + //var holdStepAttachments = this.db.Query("SELECT * FROM LTWorkRequestAttachment WHERE HoldStepID = @HoldStep ORDER BY UploadDateTime", new { holdStep }, commandType: CommandType.Text).ToList(); + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", workRequestID); + List data = db.Query("LTGetWorkRequestAttachments", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + internal void UpdateWorkRequestAttachment(LTWorkRequestAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestAttachmentID", attachment.ID); + parameters.Add("@DocType", attachment.DocType); + parameters.Add("@Comments", attachment.Comments); + + db.Execute("LTUpdateWorkRequestAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal void UpdateWorkRequestAttachmentRevision(LTWorkRequestAttachment attachment, int previousWorkRequestAttachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestAttachmentID", attachment.ID); + parameters.Add("@FileName", attachment.FileName); + parameters.Add("@DocType", attachment.DocType); + parameters.Add("@Comments", attachment.Comments); + parameters.Add("@PreviousWorkRequestAttachmentID", previousWorkRequestAttachmentID); + + db.Execute("LTUpdateWorkRequestAttachmentRevision", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteWorkRequestAttachment(int workRequestAttachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestAttachmentID", workRequestAttachmentID); + db.Execute("LTDeleteWorkRequestAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteWorkRequestAttachmentRevision(int workRequestAttachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestAttachmentID", workRequestAttachmentID); + db.Execute("LTDeleteWorkRequestAttachmentRevision", parameters, commandType: CommandType.StoredProcedure); + } + + public int SubmitDocument(int workRequestID, int userID, int documentType, out int allowedITAR) { + allowedITAR = 1; + string subRoles = ""; + subRoles = wfDMO.GetSubRoleItems(workRequestID, documentType); + + // bubble the error + int appoverCount = 0; + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", workRequestID); + parameters.Add("@UserID", userID); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@SubRoleCategoriesClause", subRoles); + parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); + parameters.Add("@AllowedITAR", allowedITAR, dbType: DbType.Int32, direction: ParameterDirection.Output); + db.Execute("LTSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); + + appoverCount = parameters.Get("@AppoverCount"); + allowedITAR = parameters.Get("@AllowedITAR"); + + return appoverCount; + } + + /// + /// Release lock on all the documents locked by the current user + /// + + public void ReleaseLockOnDocument(int userID, int workRequestID) { + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", workRequestID); + parameters.Add("@UserID", userID); + db.Execute("LTReleaseLockOnDocuments", parameters, commandType: CommandType.StoredProcedure); + } + + public void ReleaseLockOnLotTravelerUpdateDoc(int userID, int ltLotID) { + DynamicParameters parameters = new(); + parameters.Add("@LTLotID", ltLotID); + parameters.Add("@UserID", userID); + db.Execute("LTReleaseLockOnLTUpdateDoc", parameters, commandType: CommandType.StoredProcedure); + } + + public List GetRejectionOrginatorEmailList(int workRequestID) { + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", workRequestID); + List emailList = db.Query("LTGetRejectionOrginatorEmailList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return emailList; + } + + public int CreateWorkRequestRevision(LTWorkRequest data, int userID) { + int newWorkRequestID = -1; + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + parameters.Add("@ChangeComments", data.RevisionComments); + parameters.Add("@CurrentStep", data.CurrentStep); + parameters.Add("@LTWorkRequestID", data.ID); + parameters.Add("@Title", data.Title); + parameters.Add("@LotType", data.LotType); + parameters.Add("@EngLotStartRequired", data.EngLotStartRequired); + parameters.Add("@LotTypeConversion", data.LotTypeConversion); + parameters.Add("@QualLot", data.QualLot); + parameters.Add("@PurposeOfRequest", data.PurposeOfRequest); + parameters.Add("@PlannedLotStartDate", data.PlannedLotStartDate); + parameters.Add("@PlannedScheduledCloseDate", data.PlannedScheduledCloseDate); + parameters.Add("@ChargeDepartment", data.ChargeDepartment); + parameters.Add("@AllocationToUse", data.AllocationToUse); + parameters.Add("@PredictedCyleTime", data.PredictedCyleTime); + parameters.Add("@DeptChargedForRawWafers", data.ChargeDepartment); + parameters.Add("@StartQty", data.StartQty); + parameters.Add("@TotalQty", data.TotalQty); + parameters.Add("@WIPArea", data.WIPArea); + parameters.Add("@LotStartDate", data.LotStartDate); + parameters.Add("@LotNumber", data.LotNumber); + parameters.Add("@WIPPartNumber", data.WIPPartNumber); + parameters.Add("@PartDescription", data.PartDescription); + parameters.Add("@DefaultEPISiliconPartNumber", data.DefaultEPISiliconPartNumber); + parameters.Add("@ProcessFlow", data.ProcessFlow); + parameters.Add("@EmployeeID", data.EmployeeID); + parameters.Add("@VerbComment", data.VerbComment); + parameters.Add("@RecordSiliconLotInSPNTapeTagTotrav", data.RecordSiliconLotInSPNTapeTagTotrav); + parameters.Add("@SiliconLotNoCassette1", data.SiliconLotNoCassette1); + parameters.Add("@SiliconOnHand", data.SiliconOnHand); + parameters.Add("@SiliconExpectedDueDate", data.SiliconExpectedDueDate); + parameters.Add("@SiliconComments", data.SiliconComments); + parameters.Add("@ReticleOnHand", data.ReticleOnHand); + parameters.Add("@ReticleExpectedDueDate", data.ReticleExpectedDueDate); + parameters.Add("@ReticleComments", data.ReticleComments); + parameters.Add("@SPNTransferOnHand", data.SPNTransferOnHand); + parameters.Add("@SPNTransferExpectedDueDate", data.SPNTransferExpectedDueDate); + parameters.Add("@SPNTransferComments", data.SPNTransferComments); + parameters.Add("@ProbeCardOnHand", data.ProbeCardOnHand); + parameters.Add("@ProbeCardExpectedDueDate", data.ProbeCardExpectedDueDate); + parameters.Add("@ProbeCardComments", data.ProbeCardComments); + parameters.Add("@ProbeRecipeOnHand", data.ProbeRecipeOnHand); + parameters.Add("@ProbeRecipeExpectedDueDate", data.ProbeRecipeExpectedDueDate); + parameters.Add("@ProbeRecipeComments", data.ProbeRecipeComments); + parameters.Add("@LotStartCheckListComments", data.LotStartCheckListComments); + parameters.Add("@ProcessChangeDetailsOnHand", data.ProcessChangeDetailsOnHand); + parameters.Add("@ProcessChangeDetailsDueDate", data.ProcessChangeDetailsDueDate); + parameters.Add("@PCRBNumber", data.PCRBNumber); + parameters.Add("@LotStartCheckListComments", data.LotStartCheckListComments); + parameters.Add("@NewWorkRequestID", data.ID, direction: ParameterDirection.InputOutput); + db.Execute("LTCreateWorkRequestRevision", parameters, commandType: CommandType.StoredProcedure); + newWorkRequestID = parameters.Get("@NewWorkRequestID"); + + return newWorkRequestID; + } + + public List GetWorkReqRevisions(int swrNumber) { + List revisions = db.Query("SELECT ID, Revision AS RevisionNumber FROM LTWorkRequest WHERE SWRNumber = @SWRNUmber ORDER BY Revision ", new { SWRNUmber = swrNumber }, commandType: CommandType.Text).ToList(); + return revisions; + } + + public List GetLotTravRevisions(int ltLotID) { + List revisions = db.Query("SELECT ID, RevisionNumber FROM LTLotTravelerRevisionAttrib WHERE LTLotID = @ltLotID ORDER BY RevisionNumber ", new { ltLotID = ltLotID }, commandType: CommandType.Text).ToList(); + return revisions; + } + + public void InsertLot(LTLot lot) { + MiscDMO.GetLTLotInformation(lot); + + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", lot.WorkRequestID); + parameters.Add("@LotNumber", lot.LotNumber); + parameters.Add("@WIPPartNumber", lot.WIPPartNumber); + parameters.Add("@WaferQty", lot.WaferQty); + parameters.Add("@PartDescription", lot.PartDescription); + parameters.Add("@Process", lot.Process); + parameters.Add("@Location", lot.Location); + parameters.Add("@Operation", lot.Operation); + parameters.Add("@LotStatus", lot.LotStatus); + parameters.Add("@UploadedBy", lot.LotUploadedBy); + + parameters.Add("@WRWithExistingLot", dbType: DbType.Int32, direction: ParameterDirection.Output); + + db.Execute("LTInsertLTLot", parameters, commandType: CommandType.StoredProcedure); + + //int lotID = parameters.Get("@LotID"); + if (parameters.Get("@WRWithExistingLot") != 0) { + lot.WRWithExistingLot = parameters.Get("@WRWithExistingLot"); + } + + //return lotID; + } + + public IEnumerable GetLotList(int workRequestID) { + StringBuilder sql = new(); + sql.Append("SELECT L.*, U.FirstName + ' ' + U.LastName AS UploadedByName,CASE WHEN TravelerClosed = 0 THEN 'Open' ELSE 'Closed' END AS TravelerStatus "); + sql.Append("FROM LTLot L LEFT JOIN Users U ON L.LotUploadedBy = U.UserID "); + sql.Append("WHERE WorkRequestID = @workRequestID ORDER BY LotNumber "); + List lots = db.Query(sql.ToString(), new { @workRequestID = workRequestID }, commandType: CommandType.Text).ToList(); + return lots; + } + + public IEnumerable GetLotListBasedOnSWRNumber(int swrNumber) { + StringBuilder sql = new(); + sql.Append("SELECT L.*, U.FirstName + ' ' + U.LastName AS UploadedByName,CASE WHEN TravelerClosed = 0 THEN 'Open' ELSE 'Closed' END AS TravelerStatus "); + sql.Append("FROM LTWorkRequest WR INNER JOIN LTLot L ON WR.ID = L.WorkRequestID AND WR.IsCurrentRevision = 1 "); + sql.Append("LEFT JOIN Users U ON L.LotUploadedBy = U.UserID "); + sql.Append("WHERE WR.SWRNumber = @SWRNumber ORDER BY LotNumber "); + List lots = db.Query(sql.ToString(), new { @SWRNumber = swrNumber }, commandType: CommandType.Text).ToList(); + //var lots = this.db.Query("SELECT L.*, U.FirstName + ' ' + U.LastName AS UploadedByName FROM LTWorkRequest WR INNER JOIN LTLot L ON WR.ID = L.WorkRequestID AND WR.IsCurrentRevision = 1 LEFT JOIN Users U ON L.LotUploadedBy = U.UserID WHERE WR.SWRNumber = @SWRNumber ORDER BY LotNumber ", new { swrNumber }, commandType: CommandType.Text).ToList(); + return lots; + } + + public IEnumerable GetLotsWithTraveler(int workRequestID) { + List lotList = db.Query("SELECT ID AS LotID, LotNumber FROM LTLot WHERE WorkRequestID = @workRequestID AND IsTravelerGenerated = 1 ORDER BY LotNumber ", new { workRequestID = workRequestID }, commandType: CommandType.Text).ToList(); + return lotList; + } + + public void CreateTraveler(int ltLotID, int workRequestID, int UserID) { + DynamicParameters parameters = new(); + parameters.Add("@LTLotID", ltLotID); + parameters.Add("@WorkRequestID", workRequestID); + parameters.Add("@UserID", UserID); + db.Execute("LTCreateLotTraveler", parameters, commandType: CommandType.StoredProcedure); + } + + public LTLotTravelerHeaderViewModel GetLotTravelerHeaderForUpdate(int ltLotID, int UserID) { + DynamicParameters parameters = new(); + parameters.Add("@LTLotID", ltLotID); + parameters.Add("@UserID", UserID); + var data = db.Query("LTGetLotTravelerHeaderForUpdate", parameters, commandType: CommandType.StoredProcedure).Single(); + return data; + } + + public LTLotTravelerHeaderViewModel GetLotTravelerHeaderForReadOnly(int ltLotID, int revisionNumber) { + DynamicParameters parameters = new(); + parameters.Add("@LTLotID", ltLotID); + parameters.Add("@RevisionNumber", revisionNumber); + var data = db.Query("LTGetLotTravelerHeaderForReadOnly", parameters, commandType: CommandType.StoredProcedure).Single(); + return data; + } + + public IEnumerable GetLotTravHoldSteps(int ltLotID) { + DynamicParameters parameters = new(); + parameters.Add("@LTLotID", ltLotID); + List data = db.Query("LTGetLotTravelerHoldSteps", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetLotTravHoldStepsPending(int ltLotID) { + DynamicParameters parameters = new(); + parameters.Add("@LTLotID", ltLotID); + List data = db.Query("LTGetLotTravelerHoldStepsPending", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetLotTravHoldStepsCompleted(int ltLotID) { + DynamicParameters parameters = new(); + parameters.Add("@LTLotID", ltLotID); + List data = db.Query("LTGetLotTravelerHoldStepsCompleted", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetLotTravelerHolStepsByRevision(int ltLotID, int revisionNumber) { + DynamicParameters parameters = new(); + parameters.Add("@LTLotID", ltLotID); + parameters.Add("@RevisionNumber", revisionNumber); + List data = db.Query("LTGetLotTravelerHoldStepsByRevision", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public int CreateLotTravelerRevision(LTLotTravelerHoldSteps model, int userID) { + DynamicParameters parameters = new(); + parameters.Add("@CurrLotTravelerRevisionID", model.LotTravelerRevisionID); + parameters.Add("@LTLotID", model.LTLotID); + parameters.Add("@NewUpdatedBy", userID); + parameters.Add("@ChangeComments", model.RevisionComments); + parameters.Add("@NewLotTravelerRevisionID", model.ID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + db.Execute("LTCreateLotTravHoldStepsRevision", parameters, commandType: CommandType.StoredProcedure); + + int newLotTravRevisionID = parameters.Get("@NewLotTravelerRevisionID"); + // model.ID = id; + + return newLotTravRevisionID; + } + + public int CanAddLocationOperation(LTLotTravelerHoldSteps model) { + int result = 0; + + DynamicParameters parameters = new(); + parameters.Add("@LTLotID", model.LTLotID); + parameters.Add("@Location", model.Location); + parameters.Add("@OperSequence", model.OperSequence); + parameters.Add("@Operation", model.Operation); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + + db.Execute("LTCanAddLocationOperation", parameters, commandType: CommandType.StoredProcedure); + result = parameters.Get("@Result"); + return result; + } + + public void RestoreLotTravToPrevRevision(int prevLotTravRevID, int newLotTravRevID) { + DynamicParameters parameters = new(); + parameters.Add("@PrevLotTravelerRevisionID", prevLotTravRevID); + parameters.Add("@NewLotTravelerRevisionID", newLotTravRevID); + + db.Execute("LTRestoreLotTravToPrevRevision", parameters, commandType: CommandType.StoredProcedure); + } + + public int UpdateRevisedLotTravelerHoldStep(LTLotTravelerHoldSteps model, int userID) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@LotTravHoldStepID", model.ID); + parameters.Add("@NewLocation", model.Location); + parameters.Add("@NewOperSequence", model.OperSequence); + parameters.Add("@NewOperation", model.Operation); + parameters.Add("@NewOperationDescription", model.OperationDescription); + parameters.Add("@NewChangeInstructions", model.ChangeInstructions); + parameters.Add("@NewUpdatedBy", userID); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + + db.Execute("LTUpdateRevisedLotTravelerHoldStep", parameters, commandType: CommandType.StoredProcedure); + result = parameters.Get("@Result"); + return result; + } + + public int UpdateLotTravelerHoldStep(LTLotTravelerHoldSteps model, int userID) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@LotTravHoldStepID", model.ID); + parameters.Add("@NewLocation", model.Location); + parameters.Add("@NewOperSequence", model.OperSequence); + parameters.Add("@NewOperation", model.Operation); + parameters.Add("@NewOperationDescription", model.OperationDescription); + parameters.Add("@NewChangeInstructions", model.ChangeInstructions); + parameters.Add("@NewUpdatedBy", userID); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + + db.Execute("LTUpdateLotTravelerHoldStep", parameters, commandType: CommandType.StoredProcedure); + + result = parameters.Get("@Result"); + return result; + } + + public int InsertLotTravelerHoldStep(LTLotTravelerHoldSteps model, int userID) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@LTLotTravHoldStepID", model.ID); + parameters.Add("@LTLotID", model.LTLotID); + parameters.Add("@Location", model.Location); + parameters.Add("@OperSequence", model.OperSequence); + parameters.Add("@Operation", model.Operation); + parameters.Add("@OperationDescription", model.OperationDescription); + parameters.Add("@ChangeInstructions", model.ChangeInstructions); + parameters.Add("@UpdatedBy", userID); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + + db.Execute("LTInsertLotTravelerHoldStep", parameters, commandType: CommandType.StoredProcedure); + result = parameters.Get("@Result"); + + return result; + } + + public void DeleteLot(int ltLotID) { + DynamicParameters parameters = new(); + parameters.Add("@LTLotID", ltLotID); + db.Execute("LTDeleteLot", parameters, commandType: CommandType.StoredProcedure); + } + + public void UpdateLotTravlerExecution(int lotTravHoldStepID, string taskComments, bool CompletedFlag, int userID) { + DynamicParameters parameters = new(); + parameters.Add("@LotTravHoldStepID", lotTravHoldStepID); + parameters.Add("@TaskComments", taskComments); + parameters.Add("@CompletedFlag", CompletedFlag); + parameters.Add("@UserID", userID); + + db.Execute("LTUpdateLotTravlerExecution", parameters, commandType: CommandType.StoredProcedure); + } + + public LotTravelerPdf GetLotTravlerPdf(int ltLotID, int revisionNumber) { + LotTravelerPdf data = new(); + + DynamicParameters parameters = new(); + parameters.Add("@LTLotID", ltLotID); + parameters.Add("@RevisionNumber", revisionNumber); + + using (var multipleResultItems = db.QueryMultiple("LTGetLotTravelerForPDF", parameters, commandType: CommandType.StoredProcedure)) { + data = multipleResultItems.Read().SingleOrDefault(); + + List ltTaskList = multipleResultItems.Read().ToList(); + if (data != null && ltTaskList != null) { + if (ltTaskList.Count > 0) + data.Tasklist.AddRange(ltTaskList); + } + + } + + //var data = this.db.Query("LTGetLotTravelerForPDF", parameters, commandType: CommandType.StoredProcedure).Single(); + return data; + } + + public IEnumerable GetWorkReqApprovalLogHistory(int swrNumber) { + DynamicParameters parameters = new(); + parameters.Add("@SWRNumber", swrNumber); + List data = db.Query("LTGetWorkRequestApprovalLogHistory", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetWorkReqRevisionHistory(int swrNumber) { + DynamicParameters parameters = new(); + parameters.Add("@SWRNumber", swrNumber); + List data = db.Query("LTGetWorkRequestRevHistory", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + public IEnumerable GetLotTravelerRevisionHistory(int lotID) { + DynamicParameters parameters = new(); + parameters.Add("@LotID", lotID); + List data = db.Query("LTGetLotTravelerRevHistory", parameters, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + internal void InsertLotTravLotHoldStepAttachment(LTLotTravAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@LTHoldStepID", attachment.LTLotTravHoldStepID); + parameters.Add("@FileName", attachment.FileName); + parameters.Add("@FileGUID", attachment.FileGUID); + parameters.Add("@DocType", attachment.DocType); + parameters.Add("@UploadedByID", attachment.UploadedByID); + parameters.Add("@LotTravelerRevisionID", attachment.LotTravelerRevisionID); + db.Execute("LTInsertLotTravHoldStepAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal void InsertLotTravLotHoldStepAttachmentRevision(LTLotTravAttachment attachment) { + DynamicParameters parameters = new(); + parameters.Add("@LTHoldStepID", attachment.LTLotTravHoldStepID); + parameters.Add("@FileName", attachment.FileName); + parameters.Add("@FileGUID", attachment.FileGUID); + parameters.Add("@DocType", attachment.DocType); + parameters.Add("@UploadedByID", attachment.UploadedByID); + parameters.Add("@LotTravelerRevisionID", attachment.LotTravelerRevisionID); + db.Execute("LTInsertLotTravHoldStepAttachmentRevision", parameters, commandType: CommandType.StoredProcedure); + } + + internal int IsWorkRequestDocLockedByUser(int workRequestID, int userID) { + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", workRequestID); + parameters.Add("@UserID", userID); + var data = db.Query("LTIsWorkRequestDocLockedByUser", parameters, commandType: CommandType.StoredProcedure).Single(); + + return data; + } + + internal int CloseTraveler(int ltLotID, int userID, string reason) { + int result = 0; + DynamicParameters parameters = new(); + parameters.Add("@LtLotID", ltLotID); + parameters.Add("@UserID", userID); + parameters.Add("@Reason", reason); + parameters.Add("@Result", result, direction: ParameterDirection.InputOutput); + + db.Execute("LTCloseTraveler", parameters, commandType: CommandType.StoredProcedure); + + result = parameters.Get("@Result"); + + return result; + } + + internal string GetFileName(string fileGUID, int typeOfDoc) { + DynamicParameters parameters = new(); + parameters.Add("@FileGUID", fileGUID); + parameters.Add("@TypeOfDoc", typeOfDoc); + var fileName = db.Query("LTGetFileName", parameters, commandType: CommandType.StoredProcedure).Single(); + return fileName; + } + + public void ReassignOriginator(int workRequestID, int newOriginatorID, string comments, int userID) { + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", workRequestID); + parameters.Add("@NewOriginatorID", newOriginatorID); + parameters.Add("@Comments", comments); + parameters.Add("@UserID", userID); + + db.Execute("LTReassignOriginator", parameters, commandType: CommandType.StoredProcedure); + } + + public void HoldStepAttachSave(int holdStepID, int swrNo, string docType, string comments, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + // TODO + //int currentRevision = 1; + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var SWRPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo; + di = new DirectoryInfo(SWRPhysicalPath); + if (!di.Exists) + di.Create(); + + //var SWR_RevPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision; + var SWR_RevPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo; + di = new DirectoryInfo(SWR_RevPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + //var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision + @"\", guid + fileExtension); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + LTWorkRequestAttachment attach = new() { + FileGUID = guid, + LTHoldStepID = holdStepID, + FileName = fileName, + UploadedByID = userId, + DocType = docType, + Comments = comments + }; + + InsertLotHoldStepAttachment(attach); + } + + public void HoldStepAttachSaveRev(int holdStepID, int swrNo, string docType, string comments, bool newRevision, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + // TODO + //int currentRevision = 1; + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var SWRPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo; + di = new DirectoryInfo(SWRPhysicalPath); + if (!di.Exists) + di.Create(); + + //var SWR_RevPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision; + var SWR_RevPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo; + di = new DirectoryInfo(SWR_RevPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + //var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision + @"\", guid + fileExtension); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + LTWorkRequestAttachment attach = new() { + FileGUID = guid, + LTHoldStepID = holdStepID, + FileName = fileName, + UploadedByID = userId, + DocType = docType, + Comments = comments + }; + if (newRevision) + InsertLotHoldStepAttachmentRevision(attach); + else + InsertLotHoldStepAttachment(attach); + } + + public void AttachSaveWorkRequestRevision(int workRequestID, int swrNo, string docType, string attachComments, bool newRevision, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + // TODO + //int currentRevision = 1; + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var SWRPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo; + di = new DirectoryInfo(SWRPhysicalPath); + if (!di.Exists) + di.Create(); + + //var SWR_RevPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision; + var SWR_RevPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo; + di = new DirectoryInfo(SWR_RevPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + LTWorkRequestAttachment attach = new() { + WorkRequestID = workRequestID, + FileGUID = guid, + LTHoldStepID = -1, + FileName = fileName, + UploadedByID = userId, + DocType = docType, + Comments = attachComments + }; + + // InsertWorkRequestAttachment(attach); + if (newRevision) + InsertWorkRequestAttachmentRevision(attach); + else + InsertWorkRequestAttachment(attach); + } + + public void AttachSaveWorkRequest(int workRequestID, int swrNo, string comments, string docType, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + // TODO + //int currentRevision = 1; + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var SWRPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo; + di = new DirectoryInfo(SWRPhysicalPath); + if (!di.Exists) + di.Create(); + + //var SWR_RevPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision; + var SWR_RevPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo; + di = new DirectoryInfo(SWR_RevPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + LTWorkRequestAttachment attach = new() { + WorkRequestID = workRequestID, + FileGUID = guid, + LTHoldStepID = -1, + FileName = fileName, + UploadedByID = userId, + DocType = docType, + Comments = comments + + }; + + InsertWorkRequestAttachment(attach); + } + + public void LotTravHoldStepAttachSaveRev(int ltHoldStepID, int swrNo, string docType, int prevLotTravRevID, int newLotTravRevID, bool newRevision, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + + // TODO + //int currentRevision = 1; + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName); + DirectoryInfo di; + var SWRPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo; + di = new DirectoryInfo(SWRPhysicalPath); + if (!di.Exists) + di.Create(); + + //var SWR_RevPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision; + var SWR_RevPhysicalPath = _AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo; + di = new DirectoryInfo(SWR_RevPhysicalPath); + if (!di.Exists) + di.Create(); + + var guid = Guid.NewGuid().ToString(); + //var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\Rev" + currentRevision + @"\", guid + fileExtension); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"LotTraveler\" + swrNo + @"\", guid + fileExtension); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + LTLotTravAttachment attach = new() { + FileGUID = guid, + LTLotTravHoldStepID = ltHoldStepID, + LotTravelerRevisionID = newLotTravRevID, + FileName = fileName, + UploadedByID = userId, + DocType = docType + }; + if (newRevision) { + try { + InsertLotTravLotHoldStepAttachmentRevision(attach); + } catch { + //roll back the revision creation + RestoreLotTravToPrevRevision(prevLotTravRevID, newLotTravRevID); + throw new Exception("There was a problem while creating the revision, Please logout and log back and then retry. \n If the problem persist please contact the Site Administrator"); + } + + } else + InsertLotTravLotHoldStepAttachment(attach); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/MRB_DMO.cs b/Fab2ApprovalSystem/DMO/MRB_DMO.cs index b6f8ab1..7648955 100644 --- a/Fab2ApprovalSystem/DMO/MRB_DMO.cs +++ b/Fab2ApprovalSystem/DMO/MRB_DMO.cs @@ -1,886 +1,730 @@ -using Fab2ApprovalSystem.Models; using System; using System.Collections.Generic; -using System.Configuration; using System.Data; using System.Data.SqlClient; +using System.Diagnostics; +using System.IO; using System.Linq; -using System.Web; -using Dapper; -using System.Transactions; using System.Text; +using System.Threading; +using System.Transactions; + +using Dapper; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.ViewModels; -namespace Fab2ApprovalSystem.DMO -{ - public class MRB_DMO - { +namespace Fab2ApprovalSystem.DMO; - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - WorkflowDMO wfDMO = new WorkflowDMO(); - /// - /// - /// - /// - /// - internal MRB InsertMRB(MRB mrb) - { - var parameters = new DynamicParameters(); +public class MRB_DMO { + private readonly AppSettings _AppSettings; + private readonly WorkflowDMO wfDMO = new(); + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + + public MRB_DMO(AppSettings appSettings) => + _AppSettings = appSettings; + + internal MRB InsertMRB(MRB mrb) { + DynamicParameters parameters = new(); + + parameters = new DynamicParameters(); + parameters.Add("@MRBNumber", value: mrb.MRBNumber, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@OriginatorID", mrb.OriginatorID); + + db.Execute("MRBInsertItem", parameters, commandType: CommandType.StoredProcedure); + mrb.MRBNumber = parameters.Get("@MRBNumber"); + + return mrb; + } + + internal void UpdateMRB(MRB mrb) { + DynamicParameters parameters = new(); + using (TransactionScope transanction = new()) { + // Lot Disposition parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", value: mrb.MRBNumber, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@OriginatorID", mrb.OriginatorID); + parameters.Add("@MRBNumber", mrb.MRBNumber); + parameters.Add("@Title", mrb.Title); + parameters.Add("@MRBRaisedAreaID", mrb.MRBRaisedAreaID); + parameters.Add("@Owner", mrb.Owner); + parameters.Add("@Tool", mrb.Tool); + parameters.Add("@ToolCSV", mrb.ToolCSV); + parameters.Add("@NumberOfLotsAffected", mrb.NumberOfLotsAffected); + parameters.Add("@Process", mrb.Process); + parameters.Add("@CANo", mrb.CANo); + parameters.Add("@NumberOfWafersAffected", mrb.NumberOfWafersAffected); + parameters.Add("@NumberOfDiesAffected", mrb.NumberOfDiesAffected); + parameters.Add("@IssueDescription", mrb.IssueDescription); + parameters.Add("@Notes", mrb.Notes); + parameters.Add("@IssueDetectedDate", mrb.IssueDetectedDate); + parameters.Add("@IssueStartDate", mrb.IssueStartDate); + parameters.Add("@IssueEndDate", mrb.IssueEndDate); - this.db.Execute("MRBInsertItem", parameters, commandType: CommandType.StoredProcedure); - mrb.MRBNumber = parameters.Get("@MRBNumber"); + parameters.Add("@OwnerApprover", mrb.OwnerApprover); + parameters.Add("@PEApprover", mrb.PEApprover); + parameters.Add("@MFGEngineeringAppover", mrb.MfgEngineeringAppover); + parameters.Add("@OtherApprovers", mrb.OtherApprovers); + parameters.Add("@YEApprover", mrb.YEApprover); + parameters.Add("@QualityApprovers", mrb.QualityApprovers); + parameters.Add("@DetailsFolder", mrb.DetailsFolder); + parameters.Add("@CustomerImpacted", mrb.CustomerImpacted); - return mrb; + db.Execute("MRBUpdateItem", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - internal void UpdateMRB(MRB mrb) - { - var parameters = new DynamicParameters(); - using (var transanction = new TransactionScope()) - { - // Lot Disposition + List moduleIDs = mrb.ModuleIDs; + if (moduleIDs != null) { parameters = new DynamicParameters(); parameters.Add("@MRBNumber", mrb.MRBNumber); - parameters.Add("@Title", mrb.Title); - parameters.Add("@MRBRaisedAreaID", mrb.MRBRaisedAreaID); - parameters.Add("@Owner", mrb.Owner); - parameters.Add("@Tool", mrb.Tool); - parameters.Add("@ToolCSV", mrb.ToolCSV); - parameters.Add("@NumberOfLotsAffected", mrb.NumberOfLotsAffected); - parameters.Add("@Process", mrb.Process); - parameters.Add("@CANo", mrb.CANo); - parameters.Add("@NumberOfWafersAffected", mrb.NumberOfWafersAffected); - parameters.Add("@NumberOfDiesAffected", mrb.NumberOfDiesAffected); - parameters.Add("@IssueDescription", mrb.IssueDescription); - parameters.Add("@Notes", mrb.Notes); - parameters.Add("@IssueDetectedDate", mrb.IssueDetectedDate); - parameters.Add("@IssueStartDate", mrb.IssueStartDate); - parameters.Add("@IssueEndDate", mrb.IssueEndDate); + db.Execute("MRBDeleteModulesByMRB", parameters, commandType: CommandType.StoredProcedure); - parameters.Add("@OwnerApprover", mrb.OwnerApprover); - parameters.Add("@PEApprover", mrb.PEApprover); - parameters.Add("@MFGEngineeringAppover", mrb.MfgEngineeringAppover); - parameters.Add("@OtherApprovers", mrb.OtherApprovers); - parameters.Add("@YEApprover", mrb.YEApprover); - parameters.Add("@QualityApprovers", mrb.QualityApprovers); - parameters.Add("@DetailsFolder", mrb.DetailsFolder); - parameters.Add("@CustomerImpacted", mrb.CustomerImpacted); - - this.db.Execute("MRBUpdateItem", parameters, commandType: CommandType.StoredProcedure); - - List moduleIDs = mrb.ModuleIDs; - if (moduleIDs != null) - { + foreach (int moduleID in moduleIDs) { parameters = new DynamicParameters(); parameters.Add("@MRBNumber", mrb.MRBNumber); - this.db.Execute("MRBDeleteModulesByMRB", parameters, commandType: CommandType.StoredProcedure); - - foreach (int moduleID in moduleIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", mrb.MRBNumber); - parameters.Add("@ModuleID", moduleID); - this.db.Execute("MRBInsertModulesByMRB", parameters, commandType: CommandType.StoredProcedure); - } + parameters.Add("@ModuleID", moduleID); + db.Execute("MRBInsertModulesByMRB", parameters, commandType: CommandType.StoredProcedure); } + } + List partGroupIDs = mrb.PartGroupIDs; + if (partGroupIDs != null) { + parameters = new DynamicParameters(); + parameters.Add("@MRBNumber", mrb.MRBNumber); + db.Execute("MRBDeletePartGroupsAffected", parameters, commandType: CommandType.StoredProcedure); - List partGroupIDs = mrb.PartGroupIDs; - if (partGroupIDs != null) - { + foreach (int partGroupID in partGroupIDs) { parameters = new DynamicParameters(); parameters.Add("@MRBNumber", mrb.MRBNumber); - this.db.Execute("MRBDeletePartGroupsAffected", parameters, commandType: CommandType.StoredProcedure); - - foreach (int partGroupID in partGroupIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", mrb.MRBNumber); - parameters.Add("@PartGroupID", partGroupID); - this.db.Execute("MRBInsertPartGroupsAffected", parameters, commandType: CommandType.StoredProcedure); - } - + parameters.Add("@PartGroupID", partGroupID); + db.Execute("MRBInsertPartGroupsAffected", parameters, commandType: CommandType.StoredProcedure); } - List riskAssessmentIDs = mrb.RiskAssessmentIDs; - if (riskAssessmentIDs != null) - { + } + + List riskAssessmentIDs = mrb.RiskAssessmentIDs; + if (riskAssessmentIDs != null) { + parameters = new DynamicParameters(); + parameters.Add("@MRBNumber", mrb.MRBNumber); + db.Execute("MRBDeleteRiskAssessmentsByMRB", parameters, commandType: CommandType.StoredProcedure); + + foreach (int riskAssessmentID in riskAssessmentIDs) { parameters = new DynamicParameters(); parameters.Add("@MRBNumber", mrb.MRBNumber); - this.db.Execute("MRBDeleteRiskAssessmentsByMRB", parameters, commandType: CommandType.StoredProcedure); - - foreach (int riskAssessmentID in riskAssessmentIDs) - { - parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", mrb.MRBNumber); - parameters.Add("@RiskAssessmentID", riskAssessmentID); - this.db.Execute("MRBInsertRiskAssessmentsByMRB", parameters, commandType: CommandType.StoredProcedure); - } - + parameters.Add("@RiskAssessmentID", riskAssessmentID); + db.Execute("MRBInsertRiskAssessmentsByMRB", parameters, commandType: CommandType.StoredProcedure); } - - - //List dispositionIDs = mrb.DispositionIDs; - //if (dispositionIDs != null) - //{ - // parameters = new DynamicParameters(); - // parameters.Add("@MRBNumber", mrb.MRBNumber); - // this.db.Execute("MRBDeleteDispositionsByMRB", parameters, commandType: CommandType.StoredProcedure); - - // foreach (int dispositionID in dispositionIDs) - // { - // parameters = new DynamicParameters(); - // parameters.Add("@MRBNumber", mrb.MRBNumber); - // parameters.Add("@DispositionID", dispositionID); - // this.db.Execute("MRBInsertDispositionsByMRB", parameters, commandType: CommandType.StoredProcedure); - // } - - //} - transanction.Complete(); - } - } - - /// - /// - /// - /// - /// - /// - /// - internal MRB GetMRBItem(int mrbNumber, out int isITAR, int userID) - { - - //IsITAR - // 0 = false - // 1 = true - // 2 = not required - isITAR = 2; - var mrbItem = new MRB(); - var parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", value: mrbNumber); - parameters.Add("@UserID", userID); - parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - - using (var multipleResultItems = this.db.QueryMultiple("MRBGetItem", parameters, commandType: CommandType.StoredProcedure)) - { - mrbItem = multipleResultItems.Read().SingleOrDefault(); - - var partGroupIDs = multipleResultItems.Read().ToList(); - if (mrbItem != null && partGroupIDs != null) - { - mrbItem.PartGroupIDs.AddRange(partGroupIDs); - } - - var moduleIDs = multipleResultItems.Read().ToList(); - if (mrbItem != null && moduleIDs != null) - { - mrbItem.ModuleIDs.AddRange(moduleIDs); - } - - var dispositionIDs = multipleResultItems.Read().ToList(); - if (mrbItem != null && dispositionIDs != null) - { - mrbItem.DispositionIDs.AddRange(dispositionIDs); - } - - var riskAssessmentIDs = multipleResultItems.Read().ToList(); - if (mrbItem != null && riskAssessmentIDs != null) - { - mrbItem.RiskAssessmentIDs.AddRange(riskAssessmentIDs); - } - - isITAR = parameters.Get("@IsITAR"); } - return mrbItem; + //List dispositionIDs = mrb.DispositionIDs; + //if (dispositionIDs != null) + //{ + // parameters = new DynamicParameters(); + // parameters.Add("@MRBNumber", mrb.MRBNumber); + // this.db.Execute("MRBDeleteDispositionsByMRB", parameters, commandType: CommandType.StoredProcedure); + + // foreach (int dispositionID in dispositionIDs) + // { + // parameters = new DynamicParameters(); + // parameters.Add("@MRBNumber", mrb.MRBNumber); + // parameters.Add("@DispositionID", dispositionID); + // this.db.Execute("MRBInsertDispositionsByMRB", parameters, commandType: CommandType.StoredProcedure); + // } + + //} + transanction.Complete(); } + } + internal MRB GetMRBItem(int mrbNumber, out int isITAR, int userID) { + //IsITAR + // 0 = false + // 1 = true + // 2 = not required + isITAR = 2; + MRB mrbItem = new(); + DynamicParameters parameters = new(); + parameters.Add("@MRBNumber", value: mrbNumber); + parameters.Add("@UserID", userID); + parameters.Add("@IsITAR", value: isITAR, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + using (var multipleResultItems = db.QueryMultiple("MRBGetItem", parameters, commandType: CommandType.StoredProcedure)) { + mrbItem = multipleResultItems.Read().SingleOrDefault(); - /// - /// - /// - /// - internal List GetModules() - { - - var modules = this.db.Query("MRBGetModules", null, commandType: CommandType.StoredProcedure).ToList(); - return modules; - - } - - /// - /// - /// - /// - internal List GetPartGroups() - { - - var partGroup = this.db.Query("MRBGetPartGroups", null, commandType: CommandType.StoredProcedure).ToList(); - return partGroup; - - } - - /// - /// - /// - /// - internal List GetRiskAssessments() - { - - var riskAssessment = this.db.Query("MRBGetRiskAssessments", null, commandType: CommandType.StoredProcedure).ToList(); - return riskAssessment; - - } - - /// - /// - /// - /// - internal void InsertDisposition(Disposition model) - { - var parameters = new DynamicParameters(); - parameters.Add("@DispositionID", model.DispositionID, DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@MRBNumber", model.MRBNumber); - parameters.Add("@DispositionType", model.DispositionType); - parameters.Add("@DispositionName", model.DispositionName); - parameters.Add("@DispositionNotes", model.DispositionNotes); - parameters.Add("@CloseToQDBOptionID", (model.CloseToQDBOption == null ? 0 : model.CloseToQDBOption.CloseToQDBOptionID)); - - this.db.Execute("MRBInsertDispositionBYMRB", parameters, commandType: CommandType.StoredProcedure); - - int id = parameters.Get("@DispositionID"); - model.DispositionID = id; - } - - /// - /// - /// - /// - internal IEnumerable GetDispositions(int mrbNumber) - { - - //var disposition = this.db.Query("MRBGetDispositionsByMRB", new { @MRBNumber = mrbNumber }, commandType: CommandType.StoredProcedure).ToList(); - - // StringBuilder sql = new StringBuilder(); - - db.Open(); - var disposition = this.db.Query - ( - "MRBGetDispositionsByMRB", - (dispo, closeToQDBOption) => - { - dispo.CloseToQDBOption = closeToQDBOption; - return dispo; - }, - new { @MRBNumber = mrbNumber }, - commandType: CommandType.StoredProcedure, - splitOn: "CloseToQDBOptionID" - ).OrderBy(d => d.DispositionType).ToList(); - - - - return disposition; - - } - - /// - /// - /// - /// - /// - internal void UpdateDisposition(Disposition model) - { - var parameters = new DynamicParameters(); - parameters.Add("@DispositionID", model.DispositionID); - parameters.Add("@DispositionType", model.DispositionType); - parameters.Add("@DispositionName", model.DispositionName); - parameters.Add("@DispositionNotes", model.DispositionNotes); - parameters.Add("@CloseToQDBOptionID", model.CloseToQDBOption.CloseToQDBOptionID); - - this.db.Execute("MRBUpdateDispositionByMRB", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - /// - /// - internal void UpdateLotDispoType(int mrbNumber, string lotNumber, char? dispoType) - { - var parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", mrbNumber); - parameters.Add("@LotNumber", lotNumber); - parameters.Add("@DispoType", dispoType); - - this.db.Execute("MRBUpdateLotDispoType", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - internal void DeleteDisposition(Disposition model) - { - var parameters = new DynamicParameters(); - parameters.Add("@DispositionID", model.DispositionID); - this.db.Execute("MRBDeleteDisposition", parameters, commandType: CommandType.StoredProcedure); - } - - - - /// - /// - /// - /// - /// - internal IEnumerable GetMRBLots(int mrbNumber) - { - //db.Open(); - - //string sql = "SELECT L.* FROM MRBLot L WHERE L.MRBNumber = " + mrbNumber; - //var data = this.db.Query(sql).ToList(); - - var parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", value: mrbNumber); - - var data = this.db.Query("MRBGetLots", parameters, commandType: CommandType.StoredProcedure).ToList(); - - - return data; - } - - - internal IEnumerable GetMRBHoldFlagReport(int mrbNumber) - { - //db.Open(); - - string sql = "SELECT * FROM MRBHoldFlagReport WHERE MRBNumber = @MRBNumber ORDER BY LotNo"; - var data = db.Query(sql, new {MRBNumber = mrbNumber}).ToList(); - - - return data; - } - - internal IEnumerable GetMRHoldFlagSentHistory(int mrbNumber) - { - //db.Open(); - - string sql = "SELECT * FROM MRBLotsToBeSentToSPN WHERE MRBNumber = @MRBNumber ORDER BY LotNumber"; - var data = db.Query(sql, new { MRBNumber = mrbNumber}).ToList(); - - return data; - } - - internal IEnumerable GetTools() - { - //return db.Query("SELECT DISTINCT RTRIM(WO_STATION_ID) AS ToolID from vFAB2SPN_WO_RECORD ORDER BY 1").ToList(); - return db.Query("SELECT 'NA', '1' UNION SELECT DISTINCT LTRIM(RTRIM(ToolID)),LTRIM(RTRIM(ToolID)) FROM [TEMIRWAP019].[SPNPDB].[dbo].[tblToolGroups2] ORDER BY 2").ToList(); - } - - internal MRB GetToolIssueStartEndDateData(int mrbNumber, IDbTransaction dbTrans = null) - { - var tempMRBInfo = db.Query( - "SELECT ToolCSV, IssueStartDate, IssueEndDate FROM MRB WHERE MRBNumber = @mrbNo", - new { mrbNo = mrbNumber } ).First(); - - var tools = ((string)tempMRBInfo.ToolCSV).Split(','); - DateTime? issueStartDate = tempMRBInfo.IssueStartDate; - DateTime? issueEndDate = tempMRBInfo.IssueEndDate; - - if (issueStartDate.HasValue == false) throw new Exception("MRB Issue Start Date cannot be blank"); - if (issueEndDate.HasValue == false) throw new Exception("MRB Issue End Date cannot be blank"); - - MRB mrbData = new MRB { MRBNumber = mrbNumber, ToolCSV = tempMRBInfo.ToolCSV, IssueStartDate = tempMRBInfo.IssueStartDate, IssueEndDate = tempMRBInfo.IssueEndDate }; - return mrbData; - } - - /// - /// Update the first time the LotSplit Analysis was executed - /// This will be used while running the Lot Split Analysis again in order to get the child lots - /// that were not found during the first lot split analysis - /// - /// - /// - /// - internal void UpdateLastLotSplitAnalysisTime(int mrbNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", mrbNumber); - - this.db.Execute("MRBUpdateLastLotSplitAnalysisTime", parameters, commandType: CommandType.StoredProcedure); - - } - - internal bool InsertLotSplitsAffectedByIncident(int mrbNumber, string incidentLotNo, string toolCSV, DateTime? issueStartDate, DateTime? issueEndDate) - { - var analysisTime = DateTime.Now; - - // get mrb info - //var mrbInfo = db.Query( - // "SELECT ToolCSV, IssueStartDate, IssueEndDate FROM MRB WHERE MRBNumber = @mrbNo", - // new { mrbNo = mrbNumber }).First(); - - //var tools = ((string)mrbInfo.ToolCSV).Split(','); - //DateTime? issueStartDate = mrbInfo.IssueStartDate; - //DateTime? issueEndDate = mrbInfo.IssueEndDate; - - //if (issueStartDate.HasValue == false) throw new Exception("MRB Issue Start Date cannot be blank"); - //if (issueEndDate.HasValue == false) throw new Exception("MRB Issue End Date cannot be blank"); - - // search WO for MRB tools between incident start+end to find the earliest WO record for this lot and use the Out time - - DateTime? incidentTime = null; - var tools = ((string)toolCSV).Split(','); - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") - { - incidentTime = db.Query( - "SELECT MIN(OutTime) FROM WO_RECORD_MJ " + - //"SELECT MIN(OutTime) FROM vFAB2SPN_WO_RECORD " + - "WHERE WO_LOT_NO = @LotNo " + - "AND WO_STATION_ID IN @Tools " + - "AND (InTime BETWEEN @StartDate AND @EndDate " + - "OR OutTime BETWEEN @StartDate AND @EndDate)", - new - { - LotNo = incidentLotNo, - Tools = tools, - StartDate = issueStartDate.Value, - EndDate = issueEndDate.Value - }).FirstOrDefault(); - - if (incidentTime == null) - return false; - } - else - { - incidentTime = db.Query( - "SELECT MIN(OutTime) FROM vFAB2SPN_WO_RECORD " + - "WHERE WO_LOT_NO = @LotNo " + - "AND WO_STATION_ID IN @Tools " + - "AND (InTime BETWEEN @StartDate AND @EndDate " + - "OR OutTime BETWEEN @StartDate AND @EndDate)", - new - { - LotNo = incidentLotNo, - Tools = tools, - StartDate = issueStartDate.Value, - EndDate = issueEndDate.Value - }).FirstOrDefault(); - - if (incidentTime == null) - return false; - } - - - // run proc - - String parmsXML = - new System.Xml.Linq.XElement("IssueStartDate", issueStartDate).ToString() + - new System.Xml.Linq.XElement("IssueEndDate", issueEndDate).ToString() + - //new System.Xml.Linq.XElement("ToolCSV", (string)mrbInfo.ToolCSV).ToString(); - new System.Xml.Linq.XElement("ToolCSV", (string)toolCSV).ToString(); - IEnumerable analysisResults = null; - - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") - { - analysisResults = db.Query( - "AnalyzeLotAncestry_TEST", - //"AnalyzeLotAncestry", - new - { - LotNo = incidentLotNo, - IncidentTime = incidentTime, - LogIssueID = mrbNumber, - LogDocumentType = (int)GlobalVars.DocumentType.MRB, - LogParms = parmsXML, - AnalysisType = "A" - }, - commandType: CommandType.StoredProcedure); - } - else - { - analysisResults = db.Query( - "AnalyzeLotAncestry", - new - { - LotNo = incidentLotNo, - IncidentTime = incidentTime, - LogIssueID = mrbNumber, - LogDocumentType = (int)GlobalVars.DocumentType.MRB, - LogParms = parmsXML, - AnalysisType = "A" - }, - commandType: CommandType.StoredProcedure); + List partGroupIDs = multipleResultItems.Read().ToList(); + if (mrbItem != null && partGroupIDs != null) { + mrbItem.PartGroupIDs.AddRange(partGroupIDs); } - - - var dbTrans = db.BeginTransaction(); - try - { - // insert lots - foreach (var result in analysisResults) - { - if ((result.IsAffected.HasValue) && (result.IsAffected.Value == true)) - { - if (db.Query( - "SELECT COUNT(*) FROM MRBLot WHERE LotNumber = @LotNo AND MRBNumber = @MRBNumber", - new { LotNo = result.LotNo, MRBNumber = mrbNumber }, - dbTrans).Single() == 0) - { - bool existingRowUpdated; - var lot = new Lot(); - lot.MRBNumber = mrbNumber; - lot.LotNumber = result.LotNo; - lot.SourceLot = result.ParentLotNo; - lot.SourceAction = result.ActionType; - lot.SourceActionTime = result.ActionTime; - - MiscDMO.GetLotInformation(lot); - - if (String.Equals(lot.Status?.TrimEnd(), "Z", StringComparison.OrdinalIgnoreCase)) - continue; // skip lots with Z status - - InsertLot(lot, false, out existingRowUpdated, dbTrans); - - // set special fields to show lot's source - db.Execute( - "UPDATE MRBLot " + - "SET LotSplitAnalysisTime = @AnalysisTime, " + - " SourceLot = @SourceLot, SourceAction = @SourceAction, SourceActionTime = @SourceActionTime " + - "WHERE LotNumber = @LotNo AND MRBNumber = @MRBNumber", - new - { - LotNo = result.LotNo, - MRBNumber = mrbNumber, - AnalysisTime = analysisTime, - SourceLot = result.ParentLotNo, - SourceAction = result.ActionType, - SourceActionTime = result.ActionTime - }, - dbTrans); - } - - } - } - - // update source lot with analysis timestamp - db.Execute( - "UPDATE MRBLot SET LotSplitAnalysisTime = @AnalysisTime WHERE LotNumber = @LotNo AND MRBNumber = @MRBNumber", - new { AnalysisTime = analysisTime, LotNo = incidentLotNo, MRBNumber = mrbNumber }, - dbTrans); - - // Update the Parent Lot Numbers in table which stores the records to be sent to SPN - db.Execute( - "UPDATE MS SET ParentLotNumber = M.SourceLot " + - "FROM MRBLotsToBeSentToSPN MS INNER JOIN MRBLot M " + - "ON MS.MRBNumber = M.MRBNumber AND MS.LotNumber = M.LotNumber " + - "WHERE MS.MRBNumber = @MRBNumber", - new { MRBNumber = mrbNumber }, - dbTrans); - - dbTrans.Commit(); - return true; + List moduleIDs = multipleResultItems.Read().ToList(); + if (mrbItem != null && moduleIDs != null) { + mrbItem.ModuleIDs.AddRange(moduleIDs); } - catch - { - dbTrans.Rollback(); - throw; + + List dispositionIDs = multipleResultItems.Read().ToList(); + if (mrbItem != null && dispositionIDs != null) { + mrbItem.DispositionIDs.AddRange(dispositionIDs); } + + List riskAssessmentIDs = multipleResultItems.Read().ToList(); + if (mrbItem != null && riskAssessmentIDs != null) { + mrbItem.RiskAssessmentIDs.AddRange(riskAssessmentIDs); + } + + isITAR = parameters.Get("@IsITAR"); } - /// - /// - /// - /// - /// - /// + return mrbItem; + } - internal bool IsLotSentToSPN(string lotNumber, int mrbNumber, IDbTransaction dbTrans) - { + internal List GetModules() { + List modules = db.Query("MRBGetModules", null, commandType: CommandType.StoredProcedure).ToList(); + return modules; + } - var parameters = new DynamicParameters(); - - parameters.Add("@LotNumber", lotNumber); - - parameters.Add("@MRBNumber", mrbNumber); - parameters.Add("@LotSentToSPN", dbType: DbType.Boolean, direction: ParameterDirection.Output); + internal List GetPartGroups() { + List partGroup = db.Query("MRBGetPartGroups", null, commandType: CommandType.StoredProcedure).ToList(); + return partGroup; + } - this.db.Execute("MRBIsLotSentToSPN", parameters, commandType: CommandType.StoredProcedure, transaction: dbTrans); - bool lotSentToSPN = parameters.Get("@LotSentToSPN"); + internal List GetRiskAssessments() { + List riskAssessment = db.Query("MRBGetRiskAssessments", null, commandType: CommandType.StoredProcedure).ToList(); + return riskAssessment; + } - return lotSentToSPN; - } - /// - /// Get all Lots that are added to the MRB, to find any new splits - /// since the last Lot Analysis or since the last time the lot was added to MRB - /// - /// - /// - internal IEnumerable GetLotsToFindNewChildLots(int mrbNumber) - { + internal void InsertDisposition(Disposition model) { + DynamicParameters parameters = new(); + parameters.Add("@DispositionID", model.DispositionID, DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@MRBNumber", model.MRBNumber); + parameters.Add("@DispositionType", model.DispositionType); + parameters.Add("@DispositionName", model.DispositionName); + parameters.Add("@DispositionNotes", model.DispositionNotes); + parameters.Add("@CloseToQDBOptionID", (model.CloseToQDBOption == null ? 0 : model.CloseToQDBOption.CloseToQDBOptionID)); - - - var parameters = new DynamicParameters(); + db.Execute("MRBInsertDispositionBYMRB", parameters, commandType: CommandType.StoredProcedure); - parameters.Add("@MRBNumber", mrbNumber); + int id = parameters.Get("@DispositionID"); + model.DispositionID = id; + } - IEnumerable mrbLot = db.Query( - "SELECT MRBNumber, LotNumber, DispoType, IsDirty FROM MRBLotsToBeSentToSPN " + - "WHERE MRBNumber = @MRBNumber ORDER BY LotNumber", - //"WHERE IsDirty = 1 AND MRBNumber = @MRBNumber ORDER BY LotNumber", - //"WHERE MRBNumber = @MRBNumber AND LotNumber LIKE 'A400612%' ORDER BY LotNumber", - - new - { - MRBNumber = mrbNumber - }); + internal IEnumerable GetDispositions(int mrbNumber) { + //var disposition = this.db.Query("MRBGetDispositionsByMRB", new { @MRBNumber = mrbNumber }, commandType: CommandType.StoredProcedure).ToList(); - return mrbLot; - } + // StringBuilder sql = new StringBuilder(); - /// - /// This routine will get all the child lots that are not in the MRB system - /// ====================================================================================== - /// VERY IMPORTANT NOTE IN THE NEXT LINE - /// This routine will get the lots that were SPLIT in SPN after the "First time the lot was Analysis time" - /// ====================================================================================== - /// This routine will then set the new Dispo Type for all these child Lots before sending it to SPN - /// NOTE: the child lots will not be uploaded into the MRBLot table - /// - /// - /// - /// - /// - /// - /// - internal bool ChildLotsUpdateInSPNWithNewDispoType(Lot parentLot, MRB mrb ) - { - - //db.Open(); - - //var dbTrans = db.BeginTransaction(); - var analysisTime = DateTime.Now; - DateTime? incidentTime = null; - //var tools = ((string)mrb.ToolCSV).Split(','); + db.Open(); + List disposition = db.Query + ( + "MRBGetDispositionsByMRB", + (dispo, closeToQDBOption) => { + dispo.CloseToQDBOption = closeToQDBOption; + return dispo; + }, + new { @MRBNumber = mrbNumber }, + commandType: CommandType.StoredProcedure, + splitOn: "CloseToQDBOptionID" + ).OrderBy(d => d.DispositionType).ToList(); - //This is the "time", when the lot was first uploaded into the system - //Get the child lots that were split after this datetime + return disposition; + } + /// + + internal void UpdateDisposition(Disposition model) { + DynamicParameters parameters = new(); + parameters.Add("@DispositionID", model.DispositionID); + parameters.Add("@DispositionType", model.DispositionType); + parameters.Add("@DispositionName", model.DispositionName); + parameters.Add("@DispositionNotes", model.DispositionNotes); + parameters.Add("@CloseToQDBOptionID", model.CloseToQDBOption.CloseToQDBOptionID); + + db.Execute("MRBUpdateDispositionByMRB", parameters, commandType: CommandType.StoredProcedure); + } + + internal void UpdateLotDispoType(int mrbNumber, string lotNumber, char? dispoType) { + DynamicParameters parameters = new(); + parameters.Add("@MRBNumber", mrbNumber); + parameters.Add("@LotNumber", lotNumber); + parameters.Add("@DispoType", dispoType); + + db.Execute("MRBUpdateLotDispoType", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteDisposition(Disposition model) { + DynamicParameters parameters = new(); + parameters.Add("@DispositionID", model.DispositionID); + db.Execute("MRBDeleteDisposition", parameters, commandType: CommandType.StoredProcedure); + } + + internal IEnumerable GetMRBLots(int mrbNumber) { + DynamicParameters parameters = new(); + parameters.Add("@MRBNumber", value: mrbNumber); + + List data = db.Query("MRBGetLots", parameters, commandType: CommandType.StoredProcedure).ToList(); + + return data; + } + + internal IEnumerable GetMRBHoldFlagReport(int mrbNumber) { + //db.Open(); + + string sql = "SELECT * FROM MRBHoldFlagReport WHERE MRBNumber = @MRBNumber ORDER BY LotNo"; + List data = db.Query(sql, new { MRBNumber = mrbNumber }).ToList(); + + return data; + } + + internal IEnumerable GetMRHoldFlagSentHistory(int mrbNumber) { + //db.Open(); + + string sql = "SELECT * FROM MRBLotsToBeSentToSPN WHERE MRBNumber = @MRBNumber ORDER BY LotNumber"; + List data = db.Query(sql, new { MRBNumber = mrbNumber }).ToList(); + + return data; + } + + internal IEnumerable GetTools() => + //return db.Query("SELECT DISTINCT RTRIM(WO_STATION_ID) AS ToolID from vFAB2SPN_WO_RECORD ORDER BY 1").ToList(); + db.Query("SELECT 'NA', '1' UNION SELECT DISTINCT LTRIM(RTRIM(ToolID)),LTRIM(RTRIM(ToolID)) FROM [TEMIRWAP019].[SPNPDB].[dbo].[tblToolGroups2] ORDER BY 2").ToList(); + + internal MRB GetToolIssueStartEndDateData(int mrbNumber, IDbTransaction dbTrans = null) { + var tempMRBInfo = db.Query( + "SELECT ToolCSV, IssueStartDate, IssueEndDate FROM MRB WHERE MRBNumber = @mrbNo", + new { mrbNo = mrbNumber }).First(); + + var tools = ((string)tempMRBInfo.ToolCSV).Split(','); + DateTime? issueStartDate = tempMRBInfo.IssueStartDate; + DateTime? issueEndDate = tempMRBInfo.IssueEndDate; + + if (issueStartDate.HasValue == false) + throw new Exception("MRB Issue Start Date cannot be blank"); + if (issueEndDate.HasValue == false) + throw new Exception("MRB Issue End Date cannot be blank"); + + MRB mrbData = new() { MRBNumber = mrbNumber, ToolCSV = tempMRBInfo.ToolCSV, IssueStartDate = tempMRBInfo.IssueStartDate, IssueEndDate = tempMRBInfo.IssueEndDate }; + return mrbData; + } + + /// + /// Update the first time the LotSplit Analysis was executed + /// This will be used while running the Lot Split Analysis again in order to get the child lots + /// that were not found during the first lot split analysis + /// + + internal void UpdateLastLotSplitAnalysisTime(int mrbNumber) { + DynamicParameters parameters = new(); + parameters.Add("@MRBNumber", mrbNumber); + + db.Execute("MRBUpdateLastLotSplitAnalysisTime", parameters, commandType: CommandType.StoredProcedure); + } + + internal bool InsertLotSplitsAffectedByIncident(int mrbNumber, string incidentLotNo, string toolCSV, DateTime? issueStartDate, DateTime? issueEndDate) { + var analysisTime = DateTime.Now; + + // get mrb info + //var mrbInfo = db.Query( + // "SELECT ToolCSV, IssueStartDate, IssueEndDate FROM MRB WHERE MRBNumber = @mrbNo", + // new { mrbNo = mrbNumber }).First(); + + //var tools = ((string)mrbInfo.ToolCSV).Split(','); + //DateTime? issueStartDate = mrbInfo.IssueStartDate; + //DateTime? issueEndDate = mrbInfo.IssueEndDate; + + //if (issueStartDate.HasValue == false) throw new Exception("MRB Issue Start Date cannot be blank"); + //if (issueEndDate.HasValue == false) throw new Exception("MRB Issue End Date cannot be blank"); + + // search WO for MRB tools between incident start+end to find the earliest WO record for this lot and use the Out time + + DateTime? incidentTime = null; + var tools = toolCSV.Split(','); + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { incidentTime = db.Query( - "SELECT InsertDateTimeStamp FROM MRBLot " + - "WHERE MRBNumber = @MRBNumber AND LotNumber = @LotNumber", - new - { - MRBNumber = parentLot.MRBNumber, - LotNumber = parentLot.LotNumber + "SELECT MIN(OutTime) FROM WO_RECORD_MJ " + + //"SELECT MIN(OutTime) FROM vFAB2SPN_WO_RECORD " + + "WHERE WO_LOT_NO = @LotNo " + + "AND WO_STATION_ID IN @Tools " + + "AND (InTime BETWEEN @StartDate AND @EndDate " + + "OR OutTime BETWEEN @StartDate AND @EndDate)", + new { + LotNo = incidentLotNo, + Tools = tools, + StartDate = issueStartDate.Value, + EndDate = issueEndDate.Value }).FirstOrDefault(); - - - - - if (incidentTime == null) return false; + } else { + incidentTime = db.Query( + "SELECT MIN(OutTime) FROM vFAB2SPN_WO_RECORD " + + "WHERE WO_LOT_NO = @LotNo " + + "AND WO_STATION_ID IN @Tools " + + "AND (InTime BETWEEN @StartDate AND @EndDate " + + "OR OutTime BETWEEN @StartDate AND @EndDate)", + new { + LotNo = incidentLotNo, + Tools = tools, + StartDate = issueStartDate.Value, + EndDate = issueEndDate.Value + }).FirstOrDefault(); + if (incidentTime == null) + return false; + } - // run proc + // run proc - String parmsXML = - new System.Xml.Linq.XElement("IssueStartDate", mrb.IssueStartDate).ToString() + - new System.Xml.Linq.XElement("IssueEndDate", mrb.IssueEndDate).ToString() + - new System.Xml.Linq.XElement("ToolCSV", (string)mrb.ToolCSV).ToString(); + string parmsXML = + new System.Xml.Linq.XElement("IssueStartDate", issueStartDate).ToString() + + new System.Xml.Linq.XElement("IssueEndDate", issueEndDate).ToString() + + //new System.Xml.Linq.XElement("ToolCSV", (string)mrbInfo.ToolCSV).ToString(); + new System.Xml.Linq.XElement("ToolCSV", toolCSV).ToString(); + IEnumerable analysisResults = null; - List analysisResults ; - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") - { - analysisResults = db.Query( - "AnalyzeLotAncestry_TEST", - //"AnalyzeLotAncestry", - new - { - LotNo = parentLot.LotNumber, - IncidentTime = incidentTime, - LogIssueID = parentLot.MRBNumber, - LogDocumentType = (int)GlobalVars.DocumentType.MRB, - LogParms = parmsXML, - AnalysisType = "S" - }, - commandType: CommandType.StoredProcedure).ToList(); - } - else - { - analysisResults = db.Query( - "AnalyzeLotAncestry", - new - { - LotNo = parentLot.LotNumber, - IncidentTime = incidentTime, - LogIssueID = parentLot.MRBNumber, - LogDocumentType = (int)GlobalVars.DocumentType.MRB, - LogParms = parmsXML, - AnalysisType = "S" - }, - commandType: CommandType.StoredProcedure).ToList(); - } - if (db.State == ConnectionState.Closed) - db.Open(); - var dbTrans = db.BeginTransaction(); + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { + analysisResults = db.Query( + "AnalyzeLotAncestry_TEST", + //"AnalyzeLotAncestry", + new { + LotNo = incidentLotNo, + IncidentTime = incidentTime, + LogIssueID = mrbNumber, + LogDocumentType = (int)GlobalVars.DocumentType.MRB, + LogParms = parmsXML, + AnalysisType = "A" + }, + commandType: CommandType.StoredProcedure); + } else { + analysisResults = db.Query( + "AnalyzeLotAncestry", + new { + LotNo = incidentLotNo, + IncidentTime = incidentTime, + LogIssueID = mrbNumber, + LogDocumentType = (int)GlobalVars.DocumentType.MRB, + LogParms = parmsXML, + AnalysisType = "A" + }, + commandType: CommandType.StoredProcedure); + } - //var newAnalysisResults = from r in analysisResults - // where r.IsAffected.HasValue && r.IsAffected == true - // select r; + var dbTrans = db.BeginTransaction(); + try { + // insert lots + foreach (var result in analysisResults) { + if ((result.IsAffected.HasValue) && (result.IsAffected.Value)) { + if (db.Query( + "SELECT COUNT(*) FROM MRBLot WHERE LotNumber = @LotNo AND MRBNumber = @MRBNumber", + new { LotNo = result.LotNo, MRBNumber = mrbNumber }, + dbTrans).Single() == 0) { + bool existingRowUpdated; + Lot lot = new(); + lot.MRBNumber = mrbNumber; + lot.LotNumber = result.LotNo; + lot.SourceLot = result.ParentLotNo; + lot.SourceAction = result.ActionType; + lot.SourceActionTime = result.ActionTime; - IEnumerable < LotSplitAnalysisResult > newAnalysisResults = analysisResults.Where(r => r.IsAffected.HasValue && r.IsAffected == true).ToList(); - try - { - // insert lots - foreach (var result in newAnalysisResults) - { - if ((result.IsAffected.HasValue) && (result.IsAffected.Value == true)) - { - // do not include the lots that are present in the MRB System - if ( - (db.Query( - "SELECT COUNT(*) FROM MRBLot WHERE LotNumber = @LotNo AND MRBNumber = @MRBNumber", - new { LotNo = result.LotNo, MRBNumber = parentLot.MRBNumber }, - dbTrans).Single() == 0) - && - // check for the lots in the MRBLotsToBeSentToSPN table, - // that were record from the MRBLot record table - (db.Query( - "SELECT COUNT(*) FROM MRBLotsToBeSentToSPN WHERE LotNumber = @LotNo AND MRBNumber = @MRBNumber AND AddRemoveChangeMRBFlag = @AddRemoveChangeMRBFlag", - new { LotNo = result.LotNo, MRBNumber = parentLot.MRBNumber, AddRemoveChangeMRBFlag = 'R' }, - dbTrans).Single() == 0) - ) + MiscDMO.GetLotInformation(lot); - { - result.ParentLotNo = result.ParentLotNo == "" ? result.LotNo : result.ParentLotNo; + if (string.Equals(lot.Status?.TrimEnd(), "Z", StringComparison.OrdinalIgnoreCase)) + continue; // skip lots with Z status - bool existingRowUpdated; - var lot = new Lot(); - lot.MRBNumber = parentLot.MRBNumber; - lot.LotNumber = result.LotNo; - lot.SourceLot = result.ParentLotNo ; - lot.SourceAction = result.ActionType; - lot.SourceActionTime = result.ActionTime; - - MiscDMO.GetLotInformation(lot); - - if (String.Equals(lot.Status?.TrimEnd(), "Z", StringComparison.OrdinalIgnoreCase)) - continue; // skip lots with Z status - - // check if - - // Insert INTo TABLE MRBLotsToBeSentToSPN - // Do NOT Insert into the Lot table - // Only insert into the MRBLotsToBeSentToSPN, which is the table that consist of Lot that needs to have an MRB Flag - // Lot Dispo will pick up the MRB to associate the Lot Dispo with an MRB from this table and the MRBLot table - - InsertChildLot_NotInTheMRB(result.ParentLotNo, result.LotNo, parentLot.MRBNumber, parentLot.DispoType, parentLot.IsDirty, dbTrans); - } + InsertLot(lot, false, out existingRowUpdated, dbTrans); + // set special fields to show lot's source + db.Execute( + "UPDATE MRBLot " + + "SET LotSplitAnalysisTime = @AnalysisTime, " + + " SourceLot = @SourceLot, SourceAction = @SourceAction, SourceActionTime = @SourceActionTime " + + "WHERE LotNumber = @LotNo AND MRBNumber = @MRBNumber", + new { + LotNo = result.LotNo, + MRBNumber = mrbNumber, + AnalysisTime = analysisTime, + SourceLot = result.ParentLotNo, + SourceAction = result.ActionType, + SourceActionTime = result.ActionTime + }, + dbTrans); } - } - dbTrans.Commit(); - return true; - } - catch - { - dbTrans.Rollback(); - throw; - } - } - - /// - /// - /// - /// - /// - /// - /// - /// - internal void InsertChildLot_NotInTheMRB(string parentLotNumber, string lotNumber, int mrbNumber, char? dispoType, bool parentIsDirty, IDbTransaction dbTransaction = null) - { - var parameters = new DynamicParameters(); - parameters.Add("@LotNumber", lotNumber); - parameters.Add("@MRBNumber",mrbNumber); - parameters.Add("@DispoType", dispoType); - parameters.Add("@ParentIsDirty", parentIsDirty); - parameters.Add("@ParentLotNumber", parentLotNumber); - - this.db.Execute("MRBInsertChildLot_NotInTheMRB", parameters, commandType: CommandType.StoredProcedure, transaction: dbTransaction); - } - - - /// - /// - /// - /// - /// - internal bool DoesMRBLotExist(string lotNumber) - { - string tempLotNumber; - if (lotNumber.IndexOf('/') >= 0) - { - tempLotNumber = lotNumber.Substring(0, lotNumber.IndexOf('/')); - } - else - tempLotNumber = lotNumber; - - var parameters = new DynamicParameters(); - parameters.Add("@LotNumber", tempLotNumber); - parameters.Add("@MRBLotCount", dbType: DbType.Int32, direction: ParameterDirection.Output); - - this.db.Execute("MRBLotExists", parameters, commandType: CommandType.StoredProcedure); - int mrbLotCount = parameters.Get("@MRBLotCount"); - - return mrbLotCount > 0; - } - - /// - /// - /// - /// - /// - /// - internal int InsertLot(Lot lot, bool getLotInfo, out bool existingRowUpdated, IDbTransaction dbTransaction = null) - { - if (getLotInfo) - { - char? dispoType = lot.DispoType; - MiscDMO.GetLotInformation(lot); - if (dispoType.HasValue) - { - lot.DispoType = dispoType; } } - var parameters = new DynamicParameters(); - parameters.Add("@LotID", value: lot.LotID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + // update source lot with analysis timestamp + db.Execute( + "UPDATE MRBLot SET LotSplitAnalysisTime = @AnalysisTime WHERE LotNumber = @LotNo AND MRBNumber = @MRBNumber", + new { AnalysisTime = analysisTime, LotNo = incidentLotNo, MRBNumber = mrbNumber }, + dbTrans); + + // Update the Parent Lot Numbers in table which stores the records to be sent to SPN + db.Execute( + "UPDATE MS SET ParentLotNumber = M.SourceLot " + + "FROM MRBLotsToBeSentToSPN MS INNER JOIN MRBLot M " + + "ON MS.MRBNumber = M.MRBNumber AND MS.LotNumber = M.LotNumber " + + "WHERE MS.MRBNumber = @MRBNumber", + new { MRBNumber = mrbNumber }, + dbTrans); + + dbTrans.Commit(); + return true; + } catch { + dbTrans.Rollback(); + throw; + } + } + + /// + + internal bool IsLotSentToSPN(string lotNumber, int mrbNumber, IDbTransaction dbTrans) { + DynamicParameters parameters = new(); + + parameters.Add("@LotNumber", lotNumber); + + parameters.Add("@MRBNumber", mrbNumber); + parameters.Add("@LotSentToSPN", dbType: DbType.Boolean, direction: ParameterDirection.Output); + + db.Execute("MRBIsLotSentToSPN", parameters, commandType: CommandType.StoredProcedure, transaction: dbTrans); + bool lotSentToSPN = parameters.Get("@LotSentToSPN"); + + return lotSentToSPN; + } + /// + /// Get all Lots that are added to the MRB, to find any new splits + /// since the last Lot Analysis or since the last time the lot was added to MRB + /// + + internal IEnumerable GetLotsToFindNewChildLots(int mrbNumber) { + DynamicParameters parameters = new(); + + parameters.Add("@MRBNumber", mrbNumber); + + IEnumerable mrbLot = db.Query( + "SELECT MRBNumber, LotNumber, DispoType, IsDirty FROM MRBLotsToBeSentToSPN " + + "WHERE MRBNumber = @MRBNumber ORDER BY LotNumber", + //"WHERE IsDirty = 1 AND MRBNumber = @MRBNumber ORDER BY LotNumber", + //"WHERE MRBNumber = @MRBNumber AND LotNumber LIKE 'A400612%' ORDER BY LotNumber", + + new { + MRBNumber = mrbNumber + }); + + return mrbLot; + } + + /// + /// This routine will get all the child lots that are not in the MRB system + /// ====================================================================================== + /// VERY IMPORTANT NOTE IN THE NEXT LINE + /// This routine will get the lots that were SPLIT in SPN after the "First time the lot was Analysis time" + /// ====================================================================================== + /// This routine will then set the new Dispo Type for all these child Lots before sending it to SPN + /// NOTE: the child lots will not be uploaded into the MRBLot table + /// + + internal bool ChildLotsUpdateInSPNWithNewDispoType(Lot parentLot, MRB mrb) { + //db.Open(); + + //var dbTrans = db.BeginTransaction(); + var analysisTime = DateTime.Now; + DateTime? incidentTime = null; + //var tools = ((string)mrb.ToolCSV).Split(','); + + //This is the "time", when the lot was first uploaded into the system + //Get the child lots that were split after this datetime + + incidentTime = db.Query( + "SELECT InsertDateTimeStamp FROM MRBLot " + + "WHERE MRBNumber = @MRBNumber AND LotNumber = @LotNumber", + new { + MRBNumber = parentLot.MRBNumber, + LotNumber = parentLot.LotNumber + }).FirstOrDefault(); + + if (incidentTime == null) + return false; + + // run proc + + string parmsXML = + new System.Xml.Linq.XElement("IssueStartDate", mrb.IssueStartDate).ToString() + + new System.Xml.Linq.XElement("IssueEndDate", mrb.IssueEndDate).ToString() + + new System.Xml.Linq.XElement("ToolCSV", mrb.ToolCSV).ToString(); + + List analysisResults; + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { + analysisResults = db.Query( + "AnalyzeLotAncestry_TEST", + //"AnalyzeLotAncestry", + new { + LotNo = parentLot.LotNumber, + IncidentTime = incidentTime, + LogIssueID = parentLot.MRBNumber, + LogDocumentType = (int)GlobalVars.DocumentType.MRB, + LogParms = parmsXML, + AnalysisType = "S" + }, + commandType: CommandType.StoredProcedure).ToList(); + } else { + analysisResults = db.Query( + "AnalyzeLotAncestry", + new { + LotNo = parentLot.LotNumber, + IncidentTime = incidentTime, + LogIssueID = parentLot.MRBNumber, + LogDocumentType = (int)GlobalVars.DocumentType.MRB, + LogParms = parmsXML, + AnalysisType = "S" + }, + commandType: CommandType.StoredProcedure).ToList(); + } + if (db.State == ConnectionState.Closed) + db.Open(); + var dbTrans = db.BeginTransaction(); + + //var newAnalysisResults = from r in analysisResults + // where r.IsAffected.HasValue && r.IsAffected == true + // select r; + + IEnumerable newAnalysisResults = analysisResults.Where(r => r.IsAffected.HasValue && r.IsAffected == true).ToList(); + try { + // insert lots + foreach (var result in newAnalysisResults) { + if ((result.IsAffected.HasValue) && (result.IsAffected.Value)) { + // do not include the lots that are present in the MRB System + if ( + (db.Query( + "SELECT COUNT(*) FROM MRBLot WHERE LotNumber = @LotNo AND MRBNumber = @MRBNumber", + new { LotNo = result.LotNo, MRBNumber = parentLot.MRBNumber }, + dbTrans).Single() == 0) + && + // check for the lots in the MRBLotsToBeSentToSPN table, + // that were record from the MRBLot record table + (db.Query( + "SELECT COUNT(*) FROM MRBLotsToBeSentToSPN WHERE LotNumber = @LotNo AND MRBNumber = @MRBNumber AND AddRemoveChangeMRBFlag = @AddRemoveChangeMRBFlag", + new { LotNo = result.LotNo, MRBNumber = parentLot.MRBNumber, AddRemoveChangeMRBFlag = 'R' }, + dbTrans).Single() == 0) + ) { + result.ParentLotNo = result.ParentLotNo == "" ? result.LotNo : result.ParentLotNo; + + bool existingRowUpdated; + Lot lot = new(); + lot.MRBNumber = parentLot.MRBNumber; + lot.LotNumber = result.LotNo; + lot.SourceLot = result.ParentLotNo; + lot.SourceAction = result.ActionType; + lot.SourceActionTime = result.ActionTime; + + MiscDMO.GetLotInformation(lot); + + if (string.Equals(lot.Status?.TrimEnd(), "Z", StringComparison.OrdinalIgnoreCase)) + continue; // skip lots with Z status + + // check if + + // Insert INTo TABLE MRBLotsToBeSentToSPN + // Do NOT Insert into the Lot table + // Only insert into the MRBLotsToBeSentToSPN, which is the table that consist of Lot that needs to have an MRB Flag + // Lot Dispo will pick up the MRB to associate the Lot Dispo with an MRB from this table and the MRBLot table + + InsertChildLot_NotInTheMRB(result.ParentLotNo, result.LotNo, parentLot.MRBNumber, parentLot.DispoType, parentLot.IsDirty, dbTrans); + } + + } + } + + dbTrans.Commit(); + return true; + } catch { + dbTrans.Rollback(); + throw; + } + } + + internal void InsertChildLot_NotInTheMRB(string parentLotNumber, string lotNumber, int mrbNumber, char? dispoType, bool parentIsDirty, IDbTransaction dbTransaction = null) { + DynamicParameters parameters = new(); + parameters.Add("@LotNumber", lotNumber); + parameters.Add("@MRBNumber", mrbNumber); + parameters.Add("@DispoType", dispoType); + parameters.Add("@ParentIsDirty", parentIsDirty); + parameters.Add("@ParentLotNumber", parentLotNumber); + + db.Execute("MRBInsertChildLot_NotInTheMRB", parameters, commandType: CommandType.StoredProcedure, transaction: dbTransaction); + } + + internal bool DoesMRBLotExist(string lotNumber) { + string tempLotNumber; + if (lotNumber.IndexOf('/') >= 0) { + tempLotNumber = lotNumber.Substring(0, lotNumber.IndexOf('/')); + } else + tempLotNumber = lotNumber; + + DynamicParameters parameters = new(); + parameters.Add("@LotNumber", tempLotNumber); + parameters.Add("@MRBLotCount", dbType: DbType.Int32, direction: ParameterDirection.Output); + + db.Execute("MRBLotExists", parameters, commandType: CommandType.StoredProcedure); + int mrbLotCount = parameters.Get("@MRBLotCount"); + + return mrbLotCount > 0; + } + + internal int InsertLot(Lot lot, bool getLotInfo, out bool existingRowUpdated, IDbTransaction dbTransaction = null) { + if (getLotInfo) { + char? dispoType = lot.DispoType; + MiscDMO.GetLotInformation(lot); + if (dispoType.HasValue) { + lot.DispoType = dispoType; + } + } + + DynamicParameters parameters = new(); + parameters.Add("@LotID", value: lot.LotID, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@LotNumber", lot.LotNumber); + parameters.Add("@Status", lot.Status); + parameters.Add("@DispoType", lot.DispoType); + parameters.Add("@DieLotNumber", lot.DieLotNumber); + parameters.Add("@MRBNumber", lot.MRBNumber); + parameters.Add("@Description", lot.Description); + parameters.Add("@NewPartNo", lot.NewPartNo); + parameters.Add("@WipPartNo", lot.WipPartNo); + parameters.Add("@DiePartNo", lot.DiePartNo); + parameters.Add("@ProductFamily", lot.ProductFamily); + parameters.Add("@Gen", lot.Gen); + + parameters.Add("@Channel", lot.Channel); + parameters.Add("@Hexsize", lot.Hexsize); + + parameters.Add("@Voltage", lot.Voltage); + parameters.Add("@WaferCount", lot.WaferCount); + parameters.Add("@DieCount", lot.DieCount); + + parameters.Add("@Location", lot.Location); + parameters.Add("@TotalCost", lot.TotalCost); + parameters.Add("@QualityCode", lot.QualityCode); + + parameters.Add("@ExistingRowUpdated", dbType: DbType.Boolean, direction: ParameterDirection.Output); + + db.Execute("MRBInsertLot", parameters, commandType: CommandType.StoredProcedure, transaction: dbTransaction); + + int lotID = parameters.Get("@LotID"); + existingRowUpdated = parameters.Get("@ExistingRowUpdated"); + + return lotID; + } + + internal void UpdateMRBLot(Lot lot) { + db.Open(); + var dbTrans = db.BeginTransaction(); + try { + DynamicParameters parameters = new(); + parameters.Add("@LotID", lot.LotID); parameters.Add("@LotNumber", lot.LotNumber); - parameters.Add("@Status", lot.Status); - parameters.Add("@DispoType", lot.DispoType); parameters.Add("@DieLotNumber", lot.DieLotNumber); - parameters.Add("@MRBNumber", lot.MRBNumber); + parameters.Add("@DispoType", lot.DispoType); + + parameters.Add("@IssueID", lot.MRBNumber); parameters.Add("@Description", lot.Description); parameters.Add("@NewPartNo", lot.NewPartNo); parameters.Add("@WipPartNo", lot.WipPartNo); @@ -897,453 +741,591 @@ namespace Fab2ApprovalSystem.DMO parameters.Add("@Location", lot.Location); parameters.Add("@TotalCost", lot.TotalCost); - parameters.Add("@QualityCode", lot.QualityCode); - parameters.Add("@ExistingRowUpdated", dbType: DbType.Boolean, direction: ParameterDirection.Output); - - this.db.Execute("MRBInsertLot", parameters, commandType: CommandType.StoredProcedure, transaction: dbTransaction); - - int lotID = parameters.Get("@LotID"); - existingRowUpdated = parameters.Get("@ExistingRowUpdated"); - - return lotID; - - } - - /// - /// - /// - /// - internal void UpdateMRBLot(Lot lot) - { - db.Open(); - var dbTrans = db.BeginTransaction(); - try - { - var parameters = new DynamicParameters(); - parameters.Add("@LotID", lot.LotID); - parameters.Add("@LotNumber", lot.LotNumber); - parameters.Add("@DieLotNumber", lot.DieLotNumber); - parameters.Add("@DispoType", lot.DispoType); - - parameters.Add("@IssueID", lot.MRBNumber); - parameters.Add("@Description", lot.Description); - parameters.Add("@NewPartNo", lot.NewPartNo); - parameters.Add("@WipPartNo", lot.WipPartNo); - parameters.Add("@DiePartNo", lot.DiePartNo); - parameters.Add("@ProductFamily", lot.ProductFamily); - parameters.Add("@Gen", lot.Gen); - - parameters.Add("@Channel", lot.Channel); - parameters.Add("@Hexsize", lot.Hexsize); - - parameters.Add("@Voltage", lot.Voltage); - parameters.Add("@WaferCount", lot.WaferCount); - parameters.Add("@DieCount", lot.DieCount); - - parameters.Add("@Location", lot.Location); - parameters.Add("@TotalCost", lot.TotalCost); - - this.db.Execute("MRBUpdateLot", parameters, commandType: CommandType.StoredProcedure, transaction: dbTrans); - - ////routine to cascade the "dispo type" to all the child lots in SPN (Lot that are not present in FAb App Sys,) - //MRB mrbInfo = GetToolIssueStartEndDateData(lot.MRBNumber, dbTrans); - - //if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) - //{ - // bool existingLotUpdated; - // Lot l = new Lot(); - // l.LotNumber = lot.LotNumber; - // if (lot.DispoType.ToString().Trim().Length == 1) - // { - // l.DispoType = lot.DispoType; - // } - // l.MRBNumber = lot.MRBNumber; - // // check if the lot was sent to SPN - // bool lotSentToSPN = IsLotSentToSPN(l.LotNumber, l.MRBNumber, dbTrans); - // //only get the child lots if it has been sent to SPN to set the MRB Flag - // if (lotSentToSPN) - // { - // if (!GetChildLotsFromSPNForDispoTypeUpdate(lot.MRBNumber, lot.LotNumber, mrbInfo.ToolCSV, mrbInfo.IssueStartDate, mrbInfo.IssueEndDate, lot.DispoType, dbTrans)) - // { - // //warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n", l.LotNumber); - // } - // } - - //} - dbTrans.Commit(); - - } - catch - { - dbTrans.Rollback(); - throw; - } - - } - - - - - - /// - /// - /// - /// - internal void DeleteMRBLot(int lotID) - { - var parameters = new DynamicParameters(); - parameters.Add("@LotID", lotID); - this.db.Execute("MRBDeleteLot", parameters, commandType: CommandType.StoredProcedure); - } - - internal void DeleteAllMRBLot(int mrbNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", mrbNumber); - this.db.Execute("MRBDeleteAllLots", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - internal void DeleteMRB(int mrbNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", mrbNumber); - this.db.Execute("MRBDelete", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - internal IEnumerable GetMRBAttachments(int mrbNumber) - { - StringBuilder sql = new StringBuilder(); - sql.Append("SELECT A.AttachmentID, A.MRBNumber, A.FileName, A.UserID, CONVERT(VARCHAR(10), A.UploadDate, 101) AS UploadDate, "); - sql.Append("U.FirstName + ' ' + U.LastName AS FullName, A.Path "); - sql.Append("FROM MRBAttachment A INNER JOIN Users U ON A.UserID = U.UserID "); - sql.Append("WHERE MRBNumber = @MRBNumber "); - - var attachments = this.db.Query(sql.ToString(), new { MRBNumber = mrbNumber }).ToList(); - return attachments; - } - - /// - /// - /// - /// - /// - public MRBAttachment GetMRBAttachment(int attachmentID) - { - StringBuilder sql = new StringBuilder(); - sql.Append("SELECT A.AttachmentID, A.MRBNumber, A.FileName, A.UserID, CONVERT(VARCHAR(10), A.UploadDate, 101) AS UploadDate, "); - sql.Append("U.FirstName + ' ' + U.LastName AS FullName, A.Path "); - sql.Append("FROM MRBAttachment A INNER JOIN Users U ON A.UserID = U.UserID "); - sql.Append("WHERE A.AttachmentID = @AttachmentID "); - - return this.db.Query(sql.ToString(), new { AttachmentID = attachmentID }).SingleOrDefault(); - } - - - //internal IEnumerable GetMRBAttachmentsByFilename(string fileName) - //{ - // StringBuilder sql = new StringBuilder(); - // sql.Append("SELECT A.AttachmentID, A.MRBNumber, A.FileName, A.UserID, CONVERT(VARCHAR(10), A.UploadDate, 101) AS UploadDate, "); - // sql.Append("U.FirstName + ' ' + U.LastName AS FullName "); - // sql.Append("FROM MRBAttachment A INNER JOIN Users U ON A.UserID = U.UserID "); - // sql.Append("WHERE A.Filename = @filename"); - - // var attachments = this.db.Query(sql.ToString(), new { filename = fileName }).ToList(); - // return attachments; - //} - - /// - /// - /// - /// - internal void DeleteMRBAttachment(int attachmentID) - { - var parameters = new DynamicParameters(); - parameters.Add("@AttachmentID", attachmentID); - this.db.Execute("MRBDeleteAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - internal void InsertMRBAttachment(MRBAttachment attach) - { - var parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", attach.MRBNumber); - parameters.Add("@UserID", attach.UserID); - parameters.Add("@FileName", attach.FileName); - parameters.Add("@Path", attach.Path); - - this.db.Execute("MRBInsertAttachment", parameters, commandType: CommandType.StoredProcedure); - - - } - - /// - /// - /// - /// - /// - internal IEnumerable GetContainmentActions(int mrbNumber) - { - //db.Open(); - - //string sql = "SELECT * FROM MRBContainmentAction WHERE MRBNumber = " + mrbNumber; - //var data = this.db.Query(sql).ToList(); - - var parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", mrbNumber); - - var data = this.db.Query("MRBGetContainmentActions", parameters, commandType: CommandType.StoredProcedure).ToList(); - - - return data; - - } - - /// - /// - /// - /// - internal void InsertContainmentAction(ContainmentActionObj model) - { - var parameters = new DynamicParameters(); - parameters.Add("@ContainmentActionID", model.ContainmentActionID, DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@MRBNumber", model.MRBNumber); - parameters.Add("@ContainmentAction", model.ContainmentAction); - //parameters.Add("@ResponsibilityOwner", model.ResponsibilityOwner); - parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); - parameters.Add("@ECD", model.ECD); - parameters.Add("@ImplementedDate", model.ImplementedDate); - - this.db.Execute("MRBInsertContainmentAction", parameters, commandType: CommandType.StoredProcedure); - - - int id = parameters.Get("@ContainmentActionID"); - model.ContainmentActionID = id; - } - - - /// - /// - /// - /// - public void UpdateContainmentAction(ContainmentActionObj model) - { - var parameters = new DynamicParameters(); - parameters.Add("@ContainmentActionID", model.ContainmentActionID); - parameters.Add("@ContainmentAction", model.ContainmentAction); - parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); - //parameters.Add("@ResponsibilityOwner", model.ResponsibilityOwner); - parameters.Add("@ECD", model.ECD); - parameters.Add("@ImplementedDate", model.ImplementedDate); - - this.db.Execute("MRBUpdateContainmentAction", parameters, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - internal void DeleteContainmentAction(ContainmentActionObj model) - { - var parameters = new DynamicParameters(); - parameters.Add("@ContainmentActionID", model.ContainmentActionID); - this.db.Execute("MRBDeleteContainmentAction", parameters, commandType: CommandType.StoredProcedure); - } - - - /// - /// - /// - /// - /// - /// - internal void SubmitDocument(int mrbNumber, int userID) - { - string subRoles = wfDMO.GetSubRoleItems(mrbNumber, (int)GlobalVars.DocumentType.MRB); - - // bubble the error - int appoverCount = 0; - var parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", mrbNumber); - parameters.Add("@UserID", userID); - parameters.Add("@DocumentTypeID", (int)GlobalVars.DocumentType.MRB); - parameters.Add("@SubRoleCategoriesClause", subRoles); - parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - - this.db.Execute("MRBSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); - - parameters.Get("@AppoverCount"); - - } - - /// - /// - /// - /// - internal void CloseDocument(int mrbNumber) - { - this.db.Execute("UPDATE MRB SET ApprovalStatus = " + (int)GlobalVars.ApprovalOption.Closed + ", CloseDate = GETDATE() WHERE MRBNumber = " + mrbNumber, commandType: CommandType.Text); - - } - - - /// - /// - /// - /// - /// - internal void SetDispositionTypeForAllLots(int mrbNumber, string dispoType) - { - //var sql = "UPDATE MRBLot SET DispoType = '" + dispoType + "' WHERE MRBNumber = " + mrbNumber; - //this.db.Execute(sql, commandType: CommandType.Text); - - this.db.Execute("MRBSetDispositionTypeForAllLots", new { @MRBNumber = mrbNumber, @DispoType = dispoType }, commandType: CommandType.StoredProcedure); - } - - /// - /// - /// - /// - /// - /// - internal void GetLotWaferDieCount(int mrbNumber, out int lotCount, out int waferCount, out int dieCount) - { - lotCount = 0; - waferCount = 0; - dieCount = 0; - - var parameters = new DynamicParameters(); - parameters.Add("@MRBNumber", mrbNumber); - parameters.Add("@LotCount", lotCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - parameters.Add("@WaferCount", waferCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - parameters.Add("@DieCount", dieCount, dbType: DbType.Int32, direction: ParameterDirection.Output); - - this.db.Execute("MRBGetLotWaferDieCount", parameters, commandType: CommandType.StoredProcedure); - - lotCount = parameters.Get("@LotCount"); - waferCount = parameters.Get("@WaferCount"); - dieCount = parameters.Get("@DieCount"); - } - - /// - /// - /// - /// - /// - internal IEnumerable GetMRBHoldLots(int mrbNumber) - { - var data = this.db.Query("MRBGetMRBHoldLots", new { @MRBNumber = mrbNumber }, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - /// - /// - /// - /// - internal void LogHoldFlagSentToSPNHistory(int mrbNumber) - { - this.db.Execute("MRBLogHoldFlagSentToSPNHistory", new { @MRBNumber = mrbNumber }, commandType: CommandType.StoredProcedure); - - } - - - - /// - /// - /// - /// - //internal IEnumerable GetSPN_MRB_HoldFlagLots(int mrbNumber) - //{ - // var disposition = this.db.Query("MRBGet_SPN_HoldLots", new { @MRBNumber = mrbNumber }, commandType: CommandType.StoredProcedure).ToList(); - // return disposition; - //} - - - /// - /// - /// - /// - //internal void InsertSPN_MRB_HoldFlagLots(int mrbNumber) - //{ - // var disposition = this.db.Query("MRBInsertSPN_HoldFlagLots", new { @MRBNumber = mrbNumber }, commandType: CommandType.StoredProcedure).ToList(); - // //return disposition; - //} - - - /// - /// - /// - /// - /// - internal void InsertMRB_QDB_HoldFlag(string guid, string data, string operation) - { - string[] tempData = data.Split(new char[] { '~' }); - - var parameters = new DynamicParameters(); - parameters.Add("@GUID", guid); - parameters.Add("@LotNumber", tempData[0].ToString()); - parameters.Add("@MRBNumber", tempData[1].ToString()); - parameters.Add("@IncludeChildLots", tempData[2].ToUpper() == "YES" ? 1 : 0); - parameters.Add("@Operation", operation); - this.db.Execute("MRBInsertQDB_HoldFlag", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - /// - internal IEnumerable GetMRB_QDB_HoldFlags(string guid) - { - var data = this.db.Query("MRBGetMRB_QDB_HoldFlags", new { @Guid = guid }, commandType: CommandType.StoredProcedure).ToList(); - return data; - } - - - - /// - /// - /// - /// - internal void UpdateMRB_QDB_HoldFlag(string guid, bool successResult) - { - var parameters = new DynamicParameters(); - parameters.Add("@GUID", guid); - parameters.Add("@SuccessResult", successResult); - this.db.Execute("MRBUpdateQDB_HoldProcessedFlag", parameters, commandType: CommandType.StoredProcedure); - - } - - //internal IEnumerable GetLotsForMRBHoldFlags(string guid) - //{ - // var data = this.db.Query("MRBGetMRB_QDB_HoldFlags", new { @Guid = guid }, commandType: CommandType.StoredProcedure).ToList(); - // return data; - //} - - /// - /// - /// - /// - public IEnumerable GetUserList() - { - var parameters = new DynamicParameters(); - var userList = this.db.Query("_8DGetUserList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return userList; + db.Execute("MRBUpdateLot", parameters, commandType: CommandType.StoredProcedure, transaction: dbTrans); + + ////routine to cascade the "dispo type" to all the child lots in SPN (Lot that are not present in FAb App Sys,) + //MRB mrbInfo = GetToolIssueStartEndDateData(lot.MRBNumber, dbTrans); + + //if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) + //{ + // bool existingLotUpdated; + // Lot l = new Lot(); + // l.LotNumber = lot.LotNumber; + // if (lot.DispoType.ToString().Trim().Length == 1) + // { + // l.DispoType = lot.DispoType; + // } + // l.MRBNumber = lot.MRBNumber; + // // check if the lot was sent to SPN + // bool lotSentToSPN = IsLotSentToSPN(l.LotNumber, l.MRBNumber, dbTrans); + // //only get the child lots if it has been sent to SPN to set the MRB Flag + // if (lotSentToSPN) + // { + // if (!GetChildLotsFromSPNForDispoTypeUpdate(lot.MRBNumber, lot.LotNumber, mrbInfo.ToolCSV, mrbInfo.IssueStartDate, mrbInfo.IssueEndDate, lot.DispoType, dbTrans)) + // { + // //warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n", l.LotNumber); + // } + // } + + //} + dbTrans.Commit(); + + } catch { + dbTrans.Rollback(); + throw; } } -} + + internal void DeleteMRBLot(int lotID) { + DynamicParameters parameters = new(); + parameters.Add("@LotID", lotID); + db.Execute("MRBDeleteLot", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteAllMRBLot(int mrbNumber) { + DynamicParameters parameters = new(); + parameters.Add("@MRBNumber", mrbNumber); + db.Execute("MRBDeleteAllLots", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteMRB(int mrbNumber) { + DynamicParameters parameters = new(); + parameters.Add("@MRBNumber", mrbNumber); + db.Execute("MRBDelete", parameters, commandType: CommandType.StoredProcedure); + } + + internal IEnumerable GetMRBAttachments(int mrbNumber) { + StringBuilder sql = new(); + sql.Append("SELECT A.AttachmentID, A.MRBNumber, A.FileName, A.UserID, CONVERT(VARCHAR(10), A.UploadDate, 101) AS UploadDate, "); + sql.Append("U.FirstName + ' ' + U.LastName AS FullName, A.Path "); + sql.Append("FROM MRBAttachment A INNER JOIN Users U ON A.UserID = U.UserID "); + sql.Append("WHERE MRBNumber = @MRBNumber "); + + List attachments = db.Query(sql.ToString(), new { MRBNumber = mrbNumber }).ToList(); + return attachments; + } + + public MRBAttachment GetMRBAttachment(int attachmentID) { + StringBuilder sql = new(); + sql.Append("SELECT A.AttachmentID, A.MRBNumber, A.FileName, A.UserID, CONVERT(VARCHAR(10), A.UploadDate, 101) AS UploadDate, "); + sql.Append("U.FirstName + ' ' + U.LastName AS FullName, A.Path "); + sql.Append("FROM MRBAttachment A INNER JOIN Users U ON A.UserID = U.UserID "); + sql.Append("WHERE A.AttachmentID = @AttachmentID "); + + return db.Query(sql.ToString(), new { AttachmentID = attachmentID }).SingleOrDefault(); + } + + //internal IEnumerable GetMRBAttachmentsByFilename(string fileName) + //{ + // StringBuilder sql = new StringBuilder(); + // sql.Append("SELECT A.AttachmentID, A.MRBNumber, A.FileName, A.UserID, CONVERT(VARCHAR(10), A.UploadDate, 101) AS UploadDate, "); + // sql.Append("U.FirstName + ' ' + U.LastName AS FullName "); + // sql.Append("FROM MRBAttachment A INNER JOIN Users U ON A.UserID = U.UserID "); + // sql.Append("WHERE A.Filename = @filename"); + + // var attachments = this.db.Query(sql.ToString(), new { filename = fileName }).ToList(); + // return attachments; + //} + + internal void DeleteMRBAttachment(int attachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@AttachmentID", attachmentID); + db.Execute("MRBDeleteAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal void InsertMRBAttachment(MRBAttachment attach) { + DynamicParameters parameters = new(); + parameters.Add("@MRBNumber", attach.MRBNumber); + parameters.Add("@UserID", attach.UserID); + parameters.Add("@FileName", attach.FileName); + parameters.Add("@Path", attach.Path); + + db.Execute("MRBInsertAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + internal IEnumerable GetContainmentActions(int mrbNumber) { + //db.Open(); + + //string sql = "SELECT * FROM MRBContainmentAction WHERE MRBNumber = " + mrbNumber; + //var data = this.db.Query(sql).ToList(); + + DynamicParameters parameters = new(); + parameters.Add("@MRBNumber", mrbNumber); + + List data = db.Query("MRBGetContainmentActions", parameters, commandType: CommandType.StoredProcedure).ToList(); + + return data; + } + + internal void InsertContainmentAction(ContainmentActionObj model) { + DynamicParameters parameters = new(); + parameters.Add("@ContainmentActionID", model.ContainmentActionID, DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@MRBNumber", model.MRBNumber); + parameters.Add("@ContainmentAction", model.ContainmentAction); + //parameters.Add("@ResponsibilityOwner", model.ResponsibilityOwner); + parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); + parameters.Add("@ECD", model.ECD); + parameters.Add("@ImplementedDate", model.ImplementedDate); + + db.Execute("MRBInsertContainmentAction", parameters, commandType: CommandType.StoredProcedure); + + int id = parameters.Get("@ContainmentActionID"); + model.ContainmentActionID = id; + } + + public void UpdateContainmentAction(ContainmentActionObj model) { + DynamicParameters parameters = new(); + parameters.Add("@ContainmentActionID", model.ContainmentActionID); + parameters.Add("@ContainmentAction", model.ContainmentAction); + parameters.Add("@ResponsibilityOwnerID", model.ResponsibilityOwnerID); + //parameters.Add("@ResponsibilityOwner", model.ResponsibilityOwner); + parameters.Add("@ECD", model.ECD); + parameters.Add("@ImplementedDate", model.ImplementedDate); + + db.Execute("MRBUpdateContainmentAction", parameters, commandType: CommandType.StoredProcedure); + } + + internal void DeleteContainmentAction(ContainmentActionObj model) { + DynamicParameters parameters = new(); + parameters.Add("@ContainmentActionID", model.ContainmentActionID); + db.Execute("MRBDeleteContainmentAction", parameters, commandType: CommandType.StoredProcedure); + } + + internal void SubmitDocument(int mrbNumber, int userID) { + string subRoles = wfDMO.GetSubRoleItems(mrbNumber, (int)GlobalVars.DocumentType.MRB); + + // bubble the error + int appoverCount = 0; + DynamicParameters parameters = new(); + parameters.Add("@MRBNumber", mrbNumber); + parameters.Add("@UserID", userID); + parameters.Add("@DocumentTypeID", (int)GlobalVars.DocumentType.MRB); + parameters.Add("@SubRoleCategoriesClause", subRoles); + parameters.Add("@AppoverCount", appoverCount, dbType: DbType.Int32, direction: ParameterDirection.Output); + + db.Execute("MRBSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); + + parameters.Get("@AppoverCount"); + } + + internal void CloseDocument(int mrbNumber) => + db.Execute("UPDATE MRB SET ApprovalStatus = " + (int)GlobalVars.ApprovalOption.Closed + ", CloseDate = GETDATE() WHERE MRBNumber = " + mrbNumber, commandType: CommandType.Text); + + internal void SetDispositionTypeForAllLots(int mrbNumber, string dispoType) => + //var sql = "UPDATE MRBLot SET DispoType = '" + dispoType + "' WHERE MRBNumber = " + mrbNumber; + //this.db.Execute(sql, commandType: CommandType.Text); + + db.Execute("MRBSetDispositionTypeForAllLots", new { @MRBNumber = mrbNumber, @DispoType = dispoType }, commandType: CommandType.StoredProcedure); + + internal void GetLotWaferDieCount(int mrbNumber, out int lotCount, out int waferCount, out int dieCount) { + lotCount = 0; + waferCount = 0; + dieCount = 0; + + DynamicParameters parameters = new(); + parameters.Add("@MRBNumber", mrbNumber); + parameters.Add("@LotCount", lotCount, dbType: DbType.Int32, direction: ParameterDirection.Output); + parameters.Add("@WaferCount", waferCount, dbType: DbType.Int32, direction: ParameterDirection.Output); + parameters.Add("@DieCount", dieCount, dbType: DbType.Int32, direction: ParameterDirection.Output); + + db.Execute("MRBGetLotWaferDieCount", parameters, commandType: CommandType.StoredProcedure); + + lotCount = parameters.Get("@LotCount"); + waferCount = parameters.Get("@WaferCount"); + dieCount = parameters.Get("@DieCount"); + } + + internal IEnumerable GetMRBHoldLots(int mrbNumber) { + List data = db.Query("MRBGetMRBHoldLots", new { @MRBNumber = mrbNumber }, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + internal void LogHoldFlagSentToSPNHistory(int mrbNumber) => + db.Execute("MRBLogHoldFlagSentToSPNHistory", new { @MRBNumber = mrbNumber }, commandType: CommandType.StoredProcedure); + + //internal IEnumerable GetSPN_MRB_HoldFlagLots(int mrbNumber) + //{ + // var disposition = this.db.Query("MRBGet_SPN_HoldLots", new { @MRBNumber = mrbNumber }, commandType: CommandType.StoredProcedure).ToList(); + // return disposition; + //} + + //internal void InsertSPN_MRB_HoldFlagLots(int mrbNumber) + //{ + // var disposition = this.db.Query("MRBInsertSPN_HoldFlagLots", new { @MRBNumber = mrbNumber }, commandType: CommandType.StoredProcedure).ToList(); + // //return disposition; + //} + + internal void InsertMRB_QDB_HoldFlag(string guid, string data, string operation) { + string[] tempData = data.Split(new char[] { '~' }); + + DynamicParameters parameters = new(); + parameters.Add("@GUID", guid); + parameters.Add("@LotNumber", tempData[0].ToString()); + parameters.Add("@MRBNumber", tempData[1].ToString()); + parameters.Add("@IncludeChildLots", tempData[2].ToUpper() == "YES" ? 1 : 0); + parameters.Add("@Operation", operation); + db.Execute("MRBInsertQDB_HoldFlag", parameters, commandType: CommandType.StoredProcedure); + } + + internal IEnumerable GetMRB_QDB_HoldFlags(string guid) { + List data = db.Query("MRBGetMRB_QDB_HoldFlags", new { @Guid = guid }, commandType: CommandType.StoredProcedure).ToList(); + return data; + } + + internal void UpdateMRB_QDB_HoldFlag(string guid, bool successResult) { + DynamicParameters parameters = new(); + parameters.Add("@GUID", guid); + parameters.Add("@SuccessResult", successResult); + db.Execute("MRBUpdateQDB_HoldProcessedFlag", parameters, commandType: CommandType.StoredProcedure); + } + + //internal IEnumerable GetLotsForMRBHoldFlags(string guid) + //{ + // var data = this.db.Query("MRBGetMRB_QDB_HoldFlags", new { @Guid = guid }, commandType: CommandType.StoredProcedure).ToList(); + // return data; + //} + + public IEnumerable GetUserList() { + DynamicParameters parameters = new(); + List userList = db.Query("_8DGetUserList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return userList; + } + + public static string FormCSV(params object[] args) { + bool first = true; + StringBuilder sb = new(); + foreach (object arg in args) { + if (!first) + sb.Append(","); + string s = Convert.ToString(arg); + s = s.Replace('\r', ' ').Replace('\n', ' ').Replace('"', ' '); + if (s.Contains(',')) { + sb.Append("\""); + sb.Append(s); + sb.Append("\""); + } else { + sb.Append(s); + } + first = false; + } + return sb.ToString(); + } + + public string ImportRemoveQDBFlag(string operation, out string physicalPath, string userIdentityName, string a, string b, string c, string fullFileName, Stream stream) { + IEnumerable lotDataList = null; + var guid = Guid.NewGuid().ToString(); + + var fileExtension = Path.GetExtension(fullFileName); + physicalPath = Path.Combine(_AppSettings.LotTempPipeLine, guid + "." + fileExtension); + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } +#if !NET8 + ExcelData x = new ExcelData(physicalPath); + lotDataList = x.ReadQDBFlagData(); + + foreach (string lotData in lotDataList) { + InsertMRB_QDB_HoldFlag(guid, lotData, operation); + } +#endif + + FileInfo f = new(physicalPath); + if (f.Exists) + f.Delete(); + + //Send the data to SPN + if (SendQDBFlagToSPN(guid, userIdentityName, a, b, c)) + UpdateMRB_QDB_HoldFlag(guid, true); + else { + UpdateMRB_QDB_HoldFlag(guid, false); + return "Problems while uploading to SPN"; + } + return string.Empty; + } + + public bool BatchFTP(string sourceFile, string destFile, string ftpLogDirectory, string userIdentityName, string a, string b, string c) { + FileInfo sourcefile = new(sourceFile); + + //FileInfo sourcefile = new FileInfo(@"C:\Websites\ECNViewerAckResultToSPN\S15122017102017.ecn"); + + try { + //Functions.WriteEvent("HR Emp", "SPNData - Start Send(): FTPing " + sourceFile + " to SPN server.", System.Diagnostics.EventLogEntryType.Information); + + //System.Security.SecureString ss = new System.Security.SecureString(); + //foreach (char c in credentialsStorage.Password) + // ss.AppendChar(c); + + ProcessStartInfo psiFab1 = new(); + Process procFab1 = new(); + StringBuilder sb = new(); + + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { + psiFab1.FileName = a; // Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch_Test()); + } else { + psiFab1.FileName = b; // Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch()); + } + + psiFab1.Arguments = sourcefile.FullName + " " + destFile; + + psiFab1.RedirectStandardOutput = true; + psiFab1.UseShellExecute = false; + psiFab1.WorkingDirectory = c; // Server.MapPath("/FTPBatch/"); + //credentialsStorage = MiscDMO.GetCredentialsInfo("TEMSA01EC", "LocalAdmin"); + //psiFab1.UserName = credentialsStorage.UserName; + //psiFab1.Password = ss; + + procFab1.StartInfo = psiFab1; + procFab1.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data); + ; + procFab1.Start(); + procFab1.BeginOutputReadLine(); + procFab1.WaitForExit(4000); + + File.WriteAllText(Path.Combine(ftpLogDirectory, sourcefile.Name + ".txt"), sb.ToString()); + + //procFab1.StartInfo = psiFab1; + //procFab1.Start(); + + //Functions.WriteEvent("HR Emp", "SPNData - Finish FTPing to SPN server.", System.Diagnostics.EventLogEntryType.Information); + + return true; + } catch (Exception e) { + Functions.WriteEvent(_AppSettings, userIdentityName + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error); + return false; + } + + } + + public bool SendQDBFlagToSPN(string guid, string userIdentityName, string a, string b, string c) { + StringBuilder output = new(); + try { + IEnumerable data = GetMRB_QDB_HoldFlags(guid); + foreach (string tempData in data) { + //output = new StringBuilder(); + output.Append(tempData.Trim() + Environment.NewLine); + + } + + try { + if (output.Length > 0) { + DateTime dt = DateTime.Now; + string newsourceFileName = "S" + dt.Day.ToString("00") + dt.Month.ToString("00") + dt.Year.ToString("00") + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb"; + string newDestFileName = "S" + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb"; + + //string outputFile = @"C:\Websites\SPNLotHoldFlag\" + newsourceFileName; + string outputFile = _AppSettings.HoldFlagDirectory + newsourceFileName; + + File.WriteAllText(outputFile, output.ToString()); + +#if (DEBUG) + Thread.Sleep(1000); +#endif + try { + //#if (!DEBUG) + //FTPWrapper spfSPN = new FTPWrapper(outputFile, newDestFileName); + //spfSPN.FTPToSPN(); + + if (BatchFTP(outputFile, newDestFileName, _AppSettings.SPNMRBHoldFlagFTPLogDirectory, userIdentityName, a, b, c)) { + UpdateMRB_QDB_HoldFlag(guid, true); + } else { + UpdateMRB_QDB_HoldFlag(guid, false); + } + + //#endif + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + guid.ToString() + " FTPToSPN(): FTP Upload Error " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = userIdentityName, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + return false; + } + + } + + return true; + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + guid.ToString() + " SPN Hold Flag(SendToSPN) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, userIdentityName + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = userIdentityName, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + return false; + } + + } catch (Exception e) { + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "GUID =" + guid.ToString() + " SPN Hold Flag(SendToSPN) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(_AppSettings, userIdentityName + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = userIdentityName, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + return false; + } + + } + + public string ImportAddQDBFlag(string operation, out string physicalPath, string userIdentityName, string a, string b, string c, string fullFileName, Stream stream) { + IEnumerable lotDataList = null; + var guid = Guid.NewGuid().ToString(); + + var fileExtension = Path.GetExtension(fullFileName); + physicalPath = Path.Combine(_AppSettings.LotTempPipeLine, guid + "." + fileExtension); + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + +#if !NET8 + ExcelData x = new ExcelData(physicalPath); + lotDataList = x.ReadQDBFlagData(); + + foreach (string lotData in lotDataList) { + InsertMRB_QDB_HoldFlag(guid, lotData, operation); + } +#endif + + FileInfo f = new(physicalPath); + if (f.Exists) + f.Delete(); + + if (SendQDBFlagToSPN(guid, userIdentityName, a, b, c)) + UpdateMRB_QDB_HoldFlag(guid, true); + else { + UpdateMRB_QDB_HoldFlag(guid, false); + return "Problems while uploading to SPN"; + } + return string.Empty; + } + + public void AttachSave(int mrbNumber, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + var fileName = Path.GetFileName(fullFileName); + string physicalFileName; + string physicalPath; + + // Check to see if this filename is in use + var attachments = GetMRBAttachments(mrbNumber); + if (attachments.Count() > 0) { + if (attachments.Count(a => string.Equals(a.FileName, fileName, StringComparison.OrdinalIgnoreCase)) > 0) { + // This filename is used on this MRB + // So we want to delete those records so the new record replaces them + foreach (var a in attachments) { + DeleteMRBAttachment(a.AttachmentID); + + physicalFileName = a.Path; + if (string.IsNullOrEmpty(physicalFileName)) + physicalFileName = a.FileName; + physicalPath = Path.Combine(_AppSettings.AttachmentFolder + "MRB", physicalFileName); + + if (File.Exists(physicalPath)) + File.Delete(physicalPath); + } + } + } + + physicalFileName = mrbNumber.ToString() + "_" + Guid.NewGuid().ToString() + Path.GetExtension(fileName); + physicalPath = Path.Combine(_AppSettings.AttachmentFolder + "MRB", physicalFileName); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + MRBAttachment attach = new() { + MRBNumber = mrbNumber, + FileName = fileName, + Path = physicalFileName, +#if (DEBUG) + UserID = 114, +#endif + +#if (!DEBUG) + UserID = userId, +#endif + }; + InsertMRBAttachment(attach); + } + + public string ExcelLotOpen(int mrbNumber, StringBuilder warnings, IEnumerable dispos, string userIdentityName, string lotTempPipeLine, string fullFileName, Stream stream) { + var fileName = Path.GetFileName(fullFileName); + var fileExtension = Path.GetExtension(fullFileName); + string fName = userIdentityName + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); + string physicalPath = Path.Combine(lotTempPipeLine, fName + "." + fileExtension); + +#if !NET8 + IEnumerable lotNumbers; + + try { + using (var fileStream = new FileStream(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + ExcelData x = new ExcelData(physicalPath); + lotNumbers = x.ReadData(); + } catch (Exception ex) { + throw new Exception(String.Format("Invalid file format for {0}: {1}", fileName, ex.Message)); + } + + // Get Tool, Issue Start and End Date + + MRB mrbInfo = GetToolIssueStartEndDateData(mrbNumber, null); + + foreach (var lotInfo in lotNumbers) { + if (lotInfo.LotDispo.Length == 1) { + if (dispos.Count(d => d.DispositionType.Trim().ToUpper() == lotInfo.LotDispo.Trim().ToUpper()) == 0) { + throw new Exception(String.Format("Invalid lot disposition {0} for lot no {1}", + lotInfo.LotDispo, lotInfo.LotNo)); + } + } + } + // RJK - 12/17 + // Only find the child Splits when a Tool or a list of Tools is provided + if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) { + foreach (var lotInfo in lotNumbers) { + bool existingLotUpdated; + Lot l = new Lot(); + l.LotNumber = lotInfo.LotNo; + if (lotInfo.LotDispo.Length == 1) { + l.DispoType = lotInfo.LotDispo[0]; + } + l.MRBNumber = mrbNumber; + InsertLot(l, true, out existingLotUpdated); + // cannot do the check below , because what if the parent lot had splits after the prior lot split analysis + //if (!existingLotUpdated) + //{ + if (!InsertLotSplitsAffectedByIncident(mrbNumber, l.LotNumber, mrbInfo.ToolCSV, mrbInfo.IssueStartDate, mrbInfo.IssueEndDate)) { + warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n Uploaded without Lot Genealogy tracing", l.LotNumber); + } + //} + } + + // Not required - Will be using each lot's Insert Date time stamp, + // as lot could be added using search functionality + // UpdateLastLotSplitAnalysisTime(mrbNumber); + + } else { + // RJK - 12/17 + // Only find the child Splits when a Tool or a list of Tools is provided + foreach (var lotInfo in lotNumbers) { + bool existingLotUpdated; + Lot l = new Lot(); + l.LotNumber = lotInfo.LotNo; + if (lotInfo.LotDispo.Length == 1) { + l.DispoType = lotInfo.LotDispo[0]; + } + l.MRBNumber = mrbNumber; + // do not insert any new lots when importing from excel + InsertLot(l, true, out existingLotUpdated); + //UpdateLotDispoType(mrbNumber, l.LotNumber, l.DispoType); + + //if (!existingLotUpdated) + //{ + // if (!InsertLotSplitsAffectedByIncident(mrbNumber, l.LotNumber, mrbInfo.ToolCSV, mrbInfo.IssueStartDate, mrbInfo.IssueEndDate)) + // { + // warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n", l.LotNumber); + // } + //} + } + } +#endif + + FileInfo f = new(physicalPath); + if (f.Exists) + f.Delete(); + + return physicalPath; + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/MiscDMO.cs b/Fab2ApprovalSystem/DMO/MiscDMO.cs index 71b40a0..ecad775 100644 --- a/Fab2ApprovalSystem/DMO/MiscDMO.cs +++ b/Fab2ApprovalSystem/DMO/MiscDMO.cs @@ -1,644 +1,443 @@ -using Fab2ApprovalSystem.Models; using System; using System.Collections.Generic; -using System.Linq; -using System.Web; -using Dapper; using System.Data; using System.Data.SqlClient; -using System.Configuration; +using System.Linq; using System.Text; + +using Dapper; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.ViewModels; -namespace Fab2ApprovalSystem.DMO -{ - public class MiscDMO - { - - /// - /// - /// - /// - /// - public static IEnumerable SearchLots(string searchText, string searchBy) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - IEnumerable lotList; +namespace Fab2ApprovalSystem.DMO; - string sql = ""; - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") - { - if (searchBy == GlobalVars.LOT_NO) - //sql = "SELECT WP_LOT_NO + '/' + ISNULL(WP_LOT_NO,'') AS LotNumber FROM WP_RECORD_MJ WHERE WP_LOT_NO LIKE '%" + searchText + "%' "; - sql = "SELECT WP_LOT_NO + '/' + ISNULL(WP_LOT_NO,'') AS LotNumber FROM SPNLot WHERE WP_LOT_NO LIKE '%" + searchText + "%' "; - else if (searchBy == GlobalVars.LOCATION) - { - sql = "SELECT WP_LOT_NO + '/' + ISNULL(WP_LOT_NO,'') AS LotNumber FROM SPNLot WHERE WP_CURRENT_LOCATION = '" + searchText.Trim() + "' AND WP_LOT_NO + '/' + ISNULL(WP_LOT_NO,'') IS NOT NULL"; - } - lotList = db.Query(sql).ToList(); - db.Close(); - } - else - { - if (searchBy == GlobalVars.LOT_NO) - sql = "SELECT WP_LOT_NO + '/' + ISNULL(DieLotNumber,'') AS LotNumber FROM SPNLot WHERE WP_LOT_NO LIKE '%" + searchText + "%' OR DieLotNumber LIKE '%" + searchText + "%' "; - else if (searchBy == GlobalVars.LOCATION) - { - sql = "SELECT WP_LOT_NO + '/' + ISNULL(DieLotNumber,'') AS LotNumber FROM SPNLot WHERE WP_CURRENT_LOCATION = '" + searchText.Trim() + "' AND WP_LOT_NO + '/' + ISNULL(DieLotNumber,'') IS NOT NULL"; - } - lotList = db.Query(sql).ToList(); - db.Close(); - } +public class MiscDMO { - - return lotList; - } - public static IEnumerable GetUserIDsBySubRoleID(int subRoleID) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - IEnumerable userList; - - string sql = ""; - sql = "SELECT UserID FROM UserSubRole WHERE SubRoleID = " + subRoleID; - userList = db.Query(sql).ToList(); - db.Close(); - return userList; - } - - /// - /// - /// - /// - /// - /// - public static IEnumerable SearchLTLots(string searchText, string searchBy) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - string sql = ""; - + public static IEnumerable SearchLots(string searchText, string searchBy) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + IEnumerable lotList; + string sql = ""; + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { if (searchBy == GlobalVars.LOT_NO) - sql = "SELECT DISTINCT WP_LOT_NO AS LotNumber FROM vFAB2SPN_WP_RECORD WP WHERE WP_LOT_NO LIKE '%" + searchText.Trim() + "%' "; - else if (searchBy == GlobalVars.LOCATION) - { - sql = "SELECT DISTINCT WP_LOT_NO AS LotNumber FROM vFAB2SPN_WP_RECORD WP WHERE WP_CURRENT_LOCATION = '" + searchText.Trim() + "'"; - } - var lotList = db.Query(sql).ToList(); - db.Close(); - return lotList; - } - - /// - /// - /// - /// - /// - public static IEnumerable SearchLTParts(string searchText) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - StringBuilder sql = new StringBuilder(); - sql.Append("SELECT PartNumber + '~' + SiliconPart + '~' + ProcessFlow + '~' + PartDescription AS WIPPartData "); - sql.Append("FROM vWIPPartData WHERE PartNumber LIKE '%" + searchText + "%' ORDER BY PartNumber"); - - //StringBuilder sql = new StringBuilder(); - //sql.Append("SELECT TO_PART AS PartNumber, FROM_PART AS SiliconPart, P.MP_DESCRIPTION AS PartDescirption, "); - //sql.Append("RTRIM(LTRIM(SUBSTRING(TO_PART_PROC, PATINDEX('% %', TO_PART_PROC), LEN(TO_PART_PROC)))) AS ProcessFlow "); - //sql.Append("FROM TEMIRWAP019.FAB2SPN.dbo.PG_RECORD W "); - //sql.Append("INNER JOIN TEMIRWAP019.Fab2SPN.dbo.MP_RECORD P ON W.TO_PART = P.MP_PART_NUMBER "); - //sql.Append("WHERE PartNumber LIKE '%" + searchText + "%' ORDER BY PartNumber "); - - - var parList = db.Query(sql.ToString()).ToList(); - db.Close(); - return parList; - } - - /// - /// - /// - /// - public static void GetLotInformation(Lot lot) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - StringBuilder qryLotInfo = new StringBuilder(); - qryLotInfo.Append("SELECT WP_STATUS , WP_LOT_NO, WP_PART_NUMBER, MP_PRODUCT_FAMILY, MP_DESCRIPTION, "); - qryLotInfo.Append("WP_CURRENT_QTY, WP_CURRENT_LOCATION, DieLotNumber, DiePartNo, DieCount, MP_QUALITY_CODE FROM SPNLot "); - qryLotInfo.Append("WHERE WP_Lot_No = @LotNumber "); - - //var tempLotNumber = lot.LotNumber.Substring(0, 9); - var tempLotNumber = ""; - if (lot.LotNumber.IndexOf('/') >= 0) - { - tempLotNumber = lot.LotNumber.Substring(0, lot.LotNumber.IndexOf('/')); + //sql = "SELECT WP_LOT_NO + '/' + ISNULL(WP_LOT_NO,'') AS LotNumber FROM WP_RECORD_MJ WHERE WP_LOT_NO LIKE '%" + searchText + "%' "; + sql = "SELECT WP_LOT_NO + '/' + ISNULL(WP_LOT_NO,'') AS LotNumber FROM SPNLot WHERE WP_LOT_NO LIKE '%" + searchText + "%' "; + else if (searchBy == GlobalVars.LOCATION) { + sql = "SELECT WP_LOT_NO + '/' + ISNULL(WP_LOT_NO,'') AS LotNumber FROM SPNLot WHERE WP_CURRENT_LOCATION = '" + searchText.Trim() + "' AND WP_LOT_NO + '/' + ISNULL(WP_LOT_NO,'') IS NOT NULL"; } - else - tempLotNumber = lot.LotNumber; - - lot.LotNumber = tempLotNumber; - var lotInfoRow = db.Query(qryLotInfo.ToString(), new { LotNumber = tempLotNumber }).ToList(); - foreach (dynamic lotInfoColumn in lotInfoRow) - { - lot.LotNumber = lotInfoColumn.WP_LOT_NO; - if (lot.DieLotNumber == null || lot.DieLotNumber == "") - lot.DieLotNumber = lotInfoColumn.DieLotNumber; - - if (lotInfoColumn.WP_PART_NUMBER != null) - lot.WipPartNo = lotInfoColumn.WP_PART_NUMBER.Trim(); - - if (lotInfoColumn.WP_CURRENT_LOCATION != null) - { - // The data is returned from a view which is a combination from various sources and at times when the - // Lot is at the QDB location, which is extracted out of SAP, it also shows up at the 6600 location in SPN. - // There is a duplication. - //if the result returns 2 records , QDB overrides the other location (6600) - if (lot.Location == "QDB" && lotInfoColumn.WP_CURRENT_LOCATION == "6600") - lot.Location = "QDB"; - else - lot.Location = lotInfoColumn.WP_CURRENT_LOCATION; - } - - - if (lotInfoColumn.MP_DESCRIPTION != null) - { - lot.Description = lotInfoColumn.MP_DESCRIPTION; - if (lot.Description.Length > 0) - { - string[] temp = lot.Description.Split(new char[] { ',' }); - if (temp.Length > 0) - { - try - { - lot.ProductFamily = temp[0]; - } - catch { } // ignore the error - - try - { - //lot.Gen = double.Parse(temp[2].Substring(1, temp[2].Length - 1)); - if (lot.Description.StartsWith("MA,")) - lot.Gen = temp[2]; - else - lot.Gen = temp[2].Substring(1, temp[2].Length - 1); - } - catch { }// ignore the error - try - { - //lot.Hexsize = double.Parse(temp[6]); - lot.Hexsize = temp[6]; - } - catch { }// ignore the error - - } - } - } - - if (lotInfoColumn.WP_STATUS != null) - lot.Status = lotInfoColumn.WP_STATUS; - - - - if (lotInfoColumn.DiePartNo != null) - lot.DiePartNo = lotInfoColumn.DiePartNo.Trim(); - - if (lotInfoColumn.WP_CURRENT_QTY != null) - lot.WaferCount = lotInfoColumn.WP_CURRENT_QTY; - - if (lot.WipPartNo.Length > 0 || lot.DiePartNo.Length > 0) - { - qryLotInfo.Clear(); - qryLotInfo.Append("SELECT DiePartNo, SourceFAB, Diameter, Silicon, Gen, Layers,HexSize,Voltage,Channel, Type AS ProductFamily, "); - qryLotInfo.Append("WaferCost, DieCost FROM StdCost WHERE WIPWaferNo = @WIPPartNo OR DiePartNo = @DiePartNo "); - var moreLotInfoRow = db.Query(qryLotInfo.ToString(), new { WIPPartNo = lot.WipPartNo, DiePartNo = lot.DiePartNo }).ToList(); - - foreach (var moreLotInfoColumn in moreLotInfoRow) - { - if (lotInfoColumn.DieCount != null && lotInfoColumn.DieCount != 0) - lot.DieCount = int.Parse(lotInfoColumn.DieCount.ToString()); - lot.DieCost = double.Parse(moreLotInfoColumn.DieCost.ToString()); - lot.WaferCost = double.Parse(moreLotInfoColumn.WaferCost.ToString()); - - - - if (moreLotInfoColumn.Channel != null) - lot.Channel = moreLotInfoColumn.Channel; - - if (moreLotInfoColumn.Hexsize != null) - lot.Hexsize = moreLotInfoColumn.Hexsize; - - if (moreLotInfoColumn.Voltage != null) - lot.Voltage = moreLotInfoColumn.Voltage; - - - if (lot.DieCount > 0) - lot.TotalCost = Math.Round(lot.DieCount * lot.DieCost, 2); - else if (lot.WaferCount > 0) - lot.TotalCost = Math.Round(lot.WaferCount * lot.WaferCost, 2); - } - - } - - // added this code if the data shows up at the 6600 location and also at QDB for a lot. - //if (lot.DieCost > 0) - // lot.Location = "QDB"; - - if (lotInfoColumn.MP_QUALITY_CODE != null) - lot.QualityCode = lotInfoColumn.MP_QUALITY_CODE.Trim(); - - } - + lotList = db.Query(sql).ToList(); db.Close(); - //return lotStatusOption; - - } - - /// - /// / - /// - /// - public static IEnumerable GetUserList() - { - - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - - StringBuilder sql = new StringBuilder(); - sql.Append("SELECT FirstName + ' ' + LastName AS FullName, U.UserID AS UserId "); - sql.Append("FROM Users U "); - sql.Append("ORDER BY FirstName"); - - return db.Query(sql.ToString()).ToList(); - } - - /// - /// - /// - /// - /// - /// - /// - public static List GetApproverEmailListByDocument(int issueID, byte step, int documentType) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - - var parameters = new DynamicParameters(); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@IssueID", issueID); - parameters.Add("@Step", step); - var emailList = db.Query("GetApproverEmailListByDocument", parameters, commandType: CommandType.StoredProcedure).ToList(); - return emailList; - - } - - - - - - - /// - /// - /// - /// - /// - /// - /// - public static List GetApproversListByDocument(int issueID, byte step, int documentType) - { - - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - - var parameters = new DynamicParameters(); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@IssueID", issueID); - parameters.Add("@Step", step); - var approverList = db.Query("GetApproversListByDocument", parameters, commandType: CommandType.StoredProcedure).ToList(); - return approverList; - } - - public static IEnumerable GetApprovalsByDocument(int issueID, int documentType) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - - var parameters = new DynamicParameters(); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@IssueID", issueID); - var approvalList = db.Query( - "SELECT * FROM Approval WHERE IssueID = @IssueID AND DocumentTypeID = @DocumentTypeID", parameters); - return approvalList.ToList(); - } - - /// - /// NOT IN USE YET - /// - /// - /// - /// - /// - public static IEnumerable GetApprovedApproversListByDocument(int issueID, int currentStep, int documentType) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - return db.Query("GetApprovedApproversListByDocument", new { @DocumentTypeID = documentType, @IssueID = issueID, @Step = currentStep }, commandType: CommandType.StoredProcedure).ToList(); - - } - - - /// - /// - /// - /// - /// - /// - /// - public static List GetPendingApproversListByDocument(int issueID, byte step, int documentType) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@IssueID", issueID); - parameters.Add("@Step", step); - var approverList = db.Query("GetPendingApproversListByDocument", parameters, commandType: CommandType.StoredProcedure).ToList(); - return approverList; - } - - - /// - /// - /// - /// - /// - public static List GetEmergencyTECNApprovalNotifyList(int ecnNumber) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - var approverList = db.Query("ECNGetETECNApprovalNotificationList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return approverList; - } - - /// - /// - /// - /// - /// - public static List GetTECNCancelledApprovalNotifyList(int ecnNumber) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - var approverList = db.Query("ECN_TECNCancelledApprovalNotifyList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return approverList; - } - - - /// - /// - /// - /// - /// - public static List GetFabGroupNotifyList(int workRequestID) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@WorkRequestID", workRequestID); - var notifyList = db.Query("LTFabGroupApprovalNotificationList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return notifyList; - } - - - /// - /// - /// - /// - /// - public static List GetWorkRequestRevisionNotifyList(int notificationType, int workRequestID, int userID) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@NotificationType", notificationType); - parameters.Add("@UserID", userID); - parameters.Add("@WorkRequestID", workRequestID); - var notifyList = db.Query("LTGetWorkRequestRevisionNotifyList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return notifyList; - } - - - /// - /// - /// - /// - /// - /// - /// - public static List GetWorkRequestApprovedNotifyList(int notificationType, int workRequestID, int userID) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@NotificationType", notificationType); - parameters.Add("@UserID", userID); - parameters.Add("@WorkRequestID", workRequestID); - var notifyList = db.Query("LTGetWorkRequestApprovedNotifyList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return notifyList; - } - - /// - /// - /// - /// - /// - /// - /// - public static List GetLotTravelerCreationAndRevisionNotifyList(int ltLotID, int workRequestID, int userID) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@LotID", ltLotID); - parameters.Add("@UserID", userID); - parameters.Add("@WorkRequestID", workRequestID); - var notifyList = db.Query("LTGetLotTravelerCreationAndRevisionNotifyList", parameters, commandType: CommandType.StoredProcedure).ToList(); - return notifyList; - } - - - - /// - /// - /// - /// - /// - /// - /// - public static int EnableOOOStatus(int oooUserID, int delegatedTo, DateTime startDate, DateTime endDate) - { - int returnValue = 0; - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - - var parameters = new DynamicParameters(); - parameters.Add("@OOOUserID", oooUserID); - parameters.Add("@DelegatedTo", delegatedTo); - parameters.Add("@OOOStartDate", startDate); - parameters.Add("@OOOExpirationDate", endDate); - parameters.Add("@ReturnValue", value: returnValue, direction: ParameterDirection.Output); - - db.Execute("EnableOOOStatus", parameters, commandType: CommandType.StoredProcedure); - - returnValue = parameters.Get("@ReturnValue"); - - return returnValue; - - - } - - - /// - /// - /// - /// - /// - /// - /// - public static void ExpireOOOStatus(int oooUserID) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - - var parameters = new DynamicParameters(); - parameters.Add("@OOOUserID", oooUserID); - var approverList = db.Execute("ExpireOOOStatus", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - public static List GetDepartments() - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var departments = db.Query("GetDepartments", null, commandType: CommandType.StoredProcedure).ToList(); - return departments; - - } - - /// - /// - /// - /// - public static List GetModules() - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - - var modules = db.Query("GetModules", null, commandType: CommandType.StoredProcedure).ToList(); - return modules; - - } - - /// - /// - /// - /// - public static void GetLTLotInformation(LTLot lot) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - StringBuilder qryLotInfo = new StringBuilder(); - //qryLotInfo.Append("SELECT DISTINCT "); - //qryLotInfo.Append("WP_LOT_NO, WP_CURRENT_QTY, WP.WP_PART_NUMBER, MP_DESCRIPTION, WP_PROCESS, WO_LOCATION, WO_OPER_NO, WP_STATUS "); - //qryLotInfo.Append("FROM TEMIRWAP019.FAB2SPN.dbo.WO_RECORD WO "); - //qryLotInfo.Append("INNER JOIN TEMIRWAP019.FAB2SPN.dbo.WP_RECORD WP "); - //qryLotInfo.Append("ON WO.WO_LOT_NO = WP.WP_LOT_NO AND WO.InTime = (SELECT MAX(InTime) FROM TEMIRWAP019.FAB2SPN.dbo.WO_RECORD WHERE WO_LOT_NO = @LotNumber) "); - //qryLotInfo.Append("LEFT JOIN TEMIRWAP019.FAB2SPN.dbo.MP_RECORD MP "); - //qryLotInfo.Append("ON WP.WP_PART_NUMBER = MP.MP_PART_NUMBER "); - //qryLotInfo.Append("WHERE WO_LOT_NO = @LotNumber "); - - qryLotInfo.Append("SELECT DISTINCT "); - qryLotInfo.Append("WP_LOT_NO, WP_CURRENT_QTY, WP.WP_PART_NUMBER, MP_DESCRIPTION, WP_PROCESS, WP_CURRENT_LOCATION, WP_OPER_NO, WP_STATUS "); - qryLotInfo.Append("FROM vFAB2SPN_WP_RECORD WP "); - qryLotInfo.Append("LEFT JOIN vFAB2SPN_MP_RECORD MP "); - qryLotInfo.Append("ON WP.WP_PART_NUMBER = MP.MP_PART_NUMBER "); - qryLotInfo.Append("WHERE WP_LOT_NO = @LotNumber "); - - //var tempLotNumber = lot.LotNumber.Substring(0, 9); - - var tempLotNumber = ""; - if (lot.LotNumber.IndexOf('/') >= 0) - { - tempLotNumber = lot.LotNumber.Substring(0, lot.LotNumber.IndexOf('/')); + } else { + if (searchBy == GlobalVars.LOT_NO) + sql = "SELECT WP_LOT_NO + '/' + ISNULL(DieLotNumber,'') AS LotNumber FROM SPNLot WHERE WP_LOT_NO LIKE '%" + searchText + "%' OR DieLotNumber LIKE '%" + searchText + "%' "; + else if (searchBy == GlobalVars.LOCATION) { + sql = "SELECT WP_LOT_NO + '/' + ISNULL(DieLotNumber,'') AS LotNumber FROM SPNLot WHERE WP_CURRENT_LOCATION = '" + searchText.Trim() + "' AND WP_LOT_NO + '/' + ISNULL(DieLotNumber,'') IS NOT NULL"; } - else - tempLotNumber = lot.LotNumber; - - lot.LotNumber = tempLotNumber; - - lot.LotNumber = tempLotNumber; - var lotInfoRow = db.Query(qryLotInfo.ToString(), new { LotNumber = tempLotNumber }).ToList(); - foreach (dynamic lotInfoColumn in lotInfoRow) - { - lot.WIPPartNumber = lotInfoColumn.WP_PART_NUMBER; - lot.WaferQty = lotInfoColumn.WP_CURRENT_QTY; - lot.PartDescription = lotInfoColumn.MP_DESCRIPTION; - lot.Process = lotInfoColumn.WP_PROCESS; - lot.Operation = lotInfoColumn.WP_OPER_NO; - lot.LotStatus = lotInfoColumn.WP_STATUS; - lot.Location = lotInfoColumn.WP_CURRENT_LOCATION; - } - + lotList = db.Query(sql).ToList(); + db.Close(); } - - /// - /// - /// - /// - /// - public static string GetEmail(int? userID) - { - - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - var email = db.Query("GetEmail", parameters, commandType: CommandType.StoredProcedure).Single(); - return email; - } - - - /// - /// - /// - /// - /// - public static List Get8DEmailListForClosureNotification(int issueID) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - - var parameters = new DynamicParameters(); - - parameters.Add("@DocID", issueID); - var emailList = db.Query("_8DGetEmailListClosureNotification", parameters, commandType: CommandType.StoredProcedure).ToList(); - return emailList; - - } - - public static CredentialsStorage GetCredentialsInfo(string serverName, string credentialType) // TODO - need to use an enum for the credentialType - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@ServerName", serverName); - parameters.Add("@CredentialType", credentialType); - var data = db.Query("GetCredentialsInfo", param: parameters, commandType: CommandType.StoredProcedure).Single(); - return data; - } - - public List GetApprovalReminderList() - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var approvals = db.Query("GetApprovalForNotifcation", null, commandType: CommandType.StoredProcedure).ToList(); - return approvals; - } - public void UpdateApprovalNotifyDate(int approvalId) - { - IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - var parameters = new DynamicParameters(); - parameters.Add("@ApprovalId", approvalId); - db.Query("UpdateApprovalLastNotifyDate", param: parameters, commandType: CommandType.StoredProcedure).Single(); - //return data; - } - //================================================================== End of Class + return lotList; } -} + + public static IEnumerable GetUserIDsBySubRoleID(int subRoleID) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + IEnumerable userList; + + string sql = ""; + sql = "SELECT UserID FROM UserSubRole WHERE SubRoleID = " + subRoleID; + userList = db.Query(sql).ToList(); + db.Close(); + return userList; + } + + public static IEnumerable SearchLTLots(string searchText, string searchBy) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + string sql = ""; + + if (searchBy == GlobalVars.LOT_NO) + sql = "SELECT DISTINCT WP_LOT_NO AS LotNumber FROM vFAB2SPN_WP_RECORD WP WHERE WP_LOT_NO LIKE '%" + searchText.Trim() + "%' "; + else if (searchBy == GlobalVars.LOCATION) { + sql = "SELECT DISTINCT WP_LOT_NO AS LotNumber FROM vFAB2SPN_WP_RECORD WP WHERE WP_CURRENT_LOCATION = '" + searchText.Trim() + "'"; + } + List lotList = db.Query(sql).ToList(); + db.Close(); + return lotList; + } + + public static IEnumerable SearchLTParts(string searchText) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + StringBuilder sql = new(); + sql.Append("SELECT PartNumber + '~' + SiliconPart + '~' + ProcessFlow + '~' + PartDescription AS WIPPartData "); + sql.Append("FROM vWIPPartData WHERE PartNumber LIKE '%" + searchText + "%' ORDER BY PartNumber"); + + //StringBuilder sql = new StringBuilder(); + //sql.Append("SELECT TO_PART AS PartNumber, FROM_PART AS SiliconPart, P.MP_DESCRIPTION AS PartDescirption, "); + //sql.Append("RTRIM(LTRIM(SUBSTRING(TO_PART_PROC, PATINDEX('% %', TO_PART_PROC), LEN(TO_PART_PROC)))) AS ProcessFlow "); + //sql.Append("FROM TEMIRWAP019.FAB2SPN.dbo.PG_RECORD W "); + //sql.Append("INNER JOIN TEMIRWAP019.Fab2SPN.dbo.MP_RECORD P ON W.TO_PART = P.MP_PART_NUMBER "); + //sql.Append("WHERE PartNumber LIKE '%" + searchText + "%' ORDER BY PartNumber "); + + List parList = db.Query(sql.ToString()).ToList(); + db.Close(); + return parList; + } + + public static void GetLotInformation(Lot lot) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + StringBuilder qryLotInfo = new(); + qryLotInfo.Append("SELECT WP_STATUS , WP_LOT_NO, WP_PART_NUMBER, MP_PRODUCT_FAMILY, MP_DESCRIPTION, "); + qryLotInfo.Append("WP_CURRENT_QTY, WP_CURRENT_LOCATION, DieLotNumber, DiePartNo, DieCount, MP_QUALITY_CODE FROM SPNLot "); + qryLotInfo.Append("WHERE WP_Lot_No = @LotNumber "); + + //var tempLotNumber = lot.LotNumber.Substring(0, 9); + var tempLotNumber = ""; + if (lot.LotNumber.IndexOf('/') >= 0) { + tempLotNumber = lot.LotNumber.Substring(0, lot.LotNumber.IndexOf('/')); + } else + tempLotNumber = lot.LotNumber; + + lot.LotNumber = tempLotNumber; + List lotInfoRow = db.Query(qryLotInfo.ToString(), new { LotNumber = tempLotNumber }).ToList(); + foreach (dynamic lotInfoColumn in lotInfoRow) { + lot.LotNumber = lotInfoColumn.WP_LOT_NO; + if (lot.DieLotNumber == null || lot.DieLotNumber == "") + lot.DieLotNumber = lotInfoColumn.DieLotNumber; + + if (lotInfoColumn.WP_PART_NUMBER != null) + lot.WipPartNo = lotInfoColumn.WP_PART_NUMBER.Trim(); + + if (lotInfoColumn.WP_CURRENT_LOCATION != null) { + // The data is returned from a view which is a combination from various sources and at times when the + // Lot is at the QDB location, which is extracted out of SAP, it also shows up at the 6600 location in SPN. + // There is a duplication. + //if the result returns 2 records , QDB overrides the other location (6600) + if (lot.Location == "QDB" && lotInfoColumn.WP_CURRENT_LOCATION == "6600") + lot.Location = "QDB"; + else + lot.Location = lotInfoColumn.WP_CURRENT_LOCATION; + } + + if (lotInfoColumn.MP_DESCRIPTION != null) { + lot.Description = lotInfoColumn.MP_DESCRIPTION; + if (lot.Description.Length > 0) { + string[] temp = lot.Description.Split(new char[] { ',' }); + if (temp.Length > 0) { + try { + lot.ProductFamily = temp[0]; + } catch { } // ignore the error + + try { + //lot.Gen = double.Parse(temp[2].Substring(1, temp[2].Length - 1)); + if (lot.Description.StartsWith("MA,")) + lot.Gen = temp[2]; + else + lot.Gen = temp[2].Substring(1, temp[2].Length - 1); + } catch { }// ignore the error + try { + //lot.Hexsize = double.Parse(temp[6]); + lot.Hexsize = temp[6]; + } catch { }// ignore the error + + } + } + } + + if (lotInfoColumn.WP_STATUS != null) + lot.Status = lotInfoColumn.WP_STATUS; + + if (lotInfoColumn.DiePartNo != null) + lot.DiePartNo = lotInfoColumn.DiePartNo.Trim(); + + if (lotInfoColumn.WP_CURRENT_QTY != null) + lot.WaferCount = lotInfoColumn.WP_CURRENT_QTY; + + if (lot.WipPartNo.Length > 0 || lot.DiePartNo.Length > 0) { + qryLotInfo.Clear(); + qryLotInfo.Append("SELECT DiePartNo, SourceFAB, Diameter, Silicon, Gen, Layers,HexSize,Voltage,Channel, Type AS ProductFamily, "); + qryLotInfo.Append("WaferCost, DieCost FROM StdCost WHERE WIPWaferNo = @WIPPartNo OR DiePartNo = @DiePartNo "); + List moreLotInfoRow = db.Query(qryLotInfo.ToString(), new { WIPPartNo = lot.WipPartNo, DiePartNo = lot.DiePartNo }).ToList(); + + foreach (var moreLotInfoColumn in moreLotInfoRow) { + if (lotInfoColumn.DieCount != null && lotInfoColumn.DieCount != 0) + lot.DieCount = int.Parse(lotInfoColumn.DieCount.ToString()); + lot.DieCost = double.Parse(moreLotInfoColumn.DieCost.ToString()); + lot.WaferCost = double.Parse(moreLotInfoColumn.WaferCost.ToString()); + + if (moreLotInfoColumn.Channel != null) + lot.Channel = moreLotInfoColumn.Channel; + + if (moreLotInfoColumn.Hexsize != null) + lot.Hexsize = moreLotInfoColumn.Hexsize; + + if (moreLotInfoColumn.Voltage != null) + lot.Voltage = moreLotInfoColumn.Voltage; + + if (lot.DieCount > 0) + lot.TotalCost = Math.Round(lot.DieCount * lot.DieCost, 2); + else if (lot.WaferCount > 0) + lot.TotalCost = Math.Round(lot.WaferCount * lot.WaferCost, 2); + } + + } + + // added this code if the data shows up at the 6600 location and also at QDB for a lot. + //if (lot.DieCost > 0) + // lot.Location = "QDB"; + + if (lotInfoColumn.MP_QUALITY_CODE != null) + lot.QualityCode = lotInfoColumn.MP_QUALITY_CODE.Trim(); + + } + + db.Close(); + //return lotStatusOption; + } + + /// + /// / + /// + public static IEnumerable GetUserList() { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + + StringBuilder sql = new(); + sql.Append("SELECT FirstName + ' ' + LastName AS FullName, U.UserID AS UserId "); + sql.Append("FROM Users U "); + sql.Append("ORDER BY FirstName"); + + return db.Query(sql.ToString()).ToList(); + } + + public static List GetApproverEmailListByDocument(int issueID, byte step, int documentType) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + + DynamicParameters parameters = new(); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@IssueID", issueID); + parameters.Add("@Step", step); + List emailList = db.Query("GetApproverEmailListByDocument", parameters, commandType: CommandType.StoredProcedure).ToList(); + return emailList; + } + + public static List GetApproversListByDocument(int issueID, byte step, int documentType) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + + DynamicParameters parameters = new(); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@IssueID", issueID); + parameters.Add("@Step", step); + List approverList = db.Query("GetApproversListByDocument", parameters, commandType: CommandType.StoredProcedure).ToList(); + return approverList; + } + + public static IEnumerable GetApprovalsByDocument(int issueID, int documentType) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + + DynamicParameters parameters = new(); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@IssueID", issueID); + var approvalList = db.Query( + "SELECT * FROM Approval WHERE IssueID = @IssueID AND DocumentTypeID = @DocumentTypeID", parameters); + return approvalList.ToList(); + } + + /// + /// NOT IN USE YET + /// + + public static IEnumerable GetApprovedApproversListByDocument(int issueID, int currentStep, int documentType) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + return db.Query("GetApprovedApproversListByDocument", new { @DocumentTypeID = documentType, @IssueID = issueID, @Step = currentStep }, commandType: CommandType.StoredProcedure).ToList(); + } + + public static List GetPendingApproversListByDocument(int issueID, byte step, int documentType) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + DynamicParameters parameters = new(); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@IssueID", issueID); + parameters.Add("@Step", step); + List approverList = db.Query("GetPendingApproversListByDocument", parameters, commandType: CommandType.StoredProcedure).ToList(); + return approverList; + } + + public static List GetEmergencyTECNApprovalNotifyList(int ecnNumber) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", ecnNumber); + List approverList = db.Query("ECNGetETECNApprovalNotificationList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return approverList; + } + + public static List GetTECNCancelledApprovalNotifyList(int ecnNumber) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", ecnNumber); + List approverList = db.Query("ECN_TECNCancelledApprovalNotifyList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return approverList; + } + + public static List GetFabGroupNotifyList(int workRequestID) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + DynamicParameters parameters = new(); + parameters.Add("@WorkRequestID", workRequestID); + List notifyList = db.Query("LTFabGroupApprovalNotificationList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return notifyList; + } + + public static List GetWorkRequestRevisionNotifyList(int notificationType, int workRequestID, int userID) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + DynamicParameters parameters = new(); + parameters.Add("@NotificationType", notificationType); + parameters.Add("@UserID", userID); + parameters.Add("@WorkRequestID", workRequestID); + List notifyList = db.Query("LTGetWorkRequestRevisionNotifyList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return notifyList; + } + + public static List GetWorkRequestApprovedNotifyList(int notificationType, int workRequestID, int userID) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + DynamicParameters parameters = new(); + parameters.Add("@NotificationType", notificationType); + parameters.Add("@UserID", userID); + parameters.Add("@WorkRequestID", workRequestID); + List notifyList = db.Query("LTGetWorkRequestApprovedNotifyList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return notifyList; + } + + public static List GetLotTravelerCreationAndRevisionNotifyList(int ltLotID, int workRequestID, int userID) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + DynamicParameters parameters = new(); + parameters.Add("@LotID", ltLotID); + parameters.Add("@UserID", userID); + parameters.Add("@WorkRequestID", workRequestID); + List notifyList = db.Query("LTGetLotTravelerCreationAndRevisionNotifyList", parameters, commandType: CommandType.StoredProcedure).ToList(); + return notifyList; + } + + public static int EnableOOOStatus(int oooUserID, int delegatedTo, DateTime startDate, DateTime endDate) { + int returnValue = 0; + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + + DynamicParameters parameters = new(); + parameters.Add("@OOOUserID", oooUserID); + parameters.Add("@DelegatedTo", delegatedTo); + parameters.Add("@OOOStartDate", startDate); + parameters.Add("@OOOExpirationDate", endDate); + parameters.Add("@ReturnValue", value: returnValue, direction: ParameterDirection.Output); + + db.Execute("EnableOOOStatus", parameters, commandType: CommandType.StoredProcedure); + + returnValue = parameters.Get("@ReturnValue"); + + return returnValue; + } + + public static void ExpireOOOStatus(int oooUserID) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + + DynamicParameters parameters = new(); + parameters.Add("@OOOUserID", oooUserID); + var approverList = db.Execute("ExpireOOOStatus", parameters, commandType: CommandType.StoredProcedure); + } + + public static List GetDepartments() { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + List departments = db.Query("GetDepartments", null, commandType: CommandType.StoredProcedure).ToList(); + return departments; + } + + public static List GetModules() { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + + List modules = db.Query("GetModules", null, commandType: CommandType.StoredProcedure).ToList(); + return modules; + } + + public static void GetLTLotInformation(LTLot lot) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + StringBuilder qryLotInfo = new(); + //qryLotInfo.Append("SELECT DISTINCT "); + //qryLotInfo.Append("WP_LOT_NO, WP_CURRENT_QTY, WP.WP_PART_NUMBER, MP_DESCRIPTION, WP_PROCESS, WO_LOCATION, WO_OPER_NO, WP_STATUS "); + //qryLotInfo.Append("FROM TEMIRWAP019.FAB2SPN.dbo.WO_RECORD WO "); + //qryLotInfo.Append("INNER JOIN TEMIRWAP019.FAB2SPN.dbo.WP_RECORD WP "); + //qryLotInfo.Append("ON WO.WO_LOT_NO = WP.WP_LOT_NO AND WO.InTime = (SELECT MAX(InTime) FROM TEMIRWAP019.FAB2SPN.dbo.WO_RECORD WHERE WO_LOT_NO = @LotNumber) "); + //qryLotInfo.Append("LEFT JOIN TEMIRWAP019.FAB2SPN.dbo.MP_RECORD MP "); + //qryLotInfo.Append("ON WP.WP_PART_NUMBER = MP.MP_PART_NUMBER "); + //qryLotInfo.Append("WHERE WO_LOT_NO = @LotNumber "); + + qryLotInfo.Append("SELECT DISTINCT "); + qryLotInfo.Append("WP_LOT_NO, WP_CURRENT_QTY, WP.WP_PART_NUMBER, MP_DESCRIPTION, WP_PROCESS, WP_CURRENT_LOCATION, WP_OPER_NO, WP_STATUS "); + qryLotInfo.Append("FROM vFAB2SPN_WP_RECORD WP "); + qryLotInfo.Append("LEFT JOIN vFAB2SPN_MP_RECORD MP "); + qryLotInfo.Append("ON WP.WP_PART_NUMBER = MP.MP_PART_NUMBER "); + qryLotInfo.Append("WHERE WP_LOT_NO = @LotNumber "); + + //var tempLotNumber = lot.LotNumber.Substring(0, 9); + + var tempLotNumber = ""; + if (lot.LotNumber.IndexOf('/') >= 0) { + tempLotNumber = lot.LotNumber.Substring(0, lot.LotNumber.IndexOf('/')); + } else + tempLotNumber = lot.LotNumber; + + lot.LotNumber = tempLotNumber; + + lot.LotNumber = tempLotNumber; + List lotInfoRow = db.Query(qryLotInfo.ToString(), new { LotNumber = tempLotNumber }).ToList(); + foreach (dynamic lotInfoColumn in lotInfoRow) { + lot.WIPPartNumber = lotInfoColumn.WP_PART_NUMBER; + lot.WaferQty = lotInfoColumn.WP_CURRENT_QTY; + lot.PartDescription = lotInfoColumn.MP_DESCRIPTION; + lot.Process = lotInfoColumn.WP_PROCESS; + lot.Operation = lotInfoColumn.WP_OPER_NO; + lot.LotStatus = lotInfoColumn.WP_STATUS; + lot.Location = lotInfoColumn.WP_CURRENT_LOCATION; + } + + } + + public static string GetEmail(int? userID) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + var email = db.Query("GetEmail", parameters, commandType: CommandType.StoredProcedure).Single(); + return email; + } + + public static List Get8DEmailListForClosureNotification(int issueID) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + + DynamicParameters parameters = new(); + + parameters.Add("@DocID", issueID); + List emailList = db.Query("_8DGetEmailListClosureNotification", parameters, commandType: CommandType.StoredProcedure).ToList(); + return emailList; + } + + public static CredentialsStorage GetCredentialsInfo(string serverName, string credentialType) // TODO - need to use an enum for the credentialType + { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + DynamicParameters parameters = new(); + parameters.Add("@ServerName", serverName); + parameters.Add("@CredentialType", credentialType); + var data = db.Query("GetCredentialsInfo", param: parameters, commandType: CommandType.StoredProcedure).Single(); + return data; + } + + public List GetApprovalReminderList() { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + List approvals = db.Query("GetApprovalForNotifcation", null, commandType: CommandType.StoredProcedure).ToList(); + return approvals; + } + + public void UpdateApprovalNotifyDate(int approvalId) { + IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); + DynamicParameters parameters = new(); + parameters.Add("@ApprovalId", approvalId); + db.Query("UpdateApprovalLastNotifyDate", param: parameters, commandType: CommandType.StoredProcedure).Single(); + //return data; + } + //================================================================== End of Class +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/PartsRequestDMO.cs b/Fab2ApprovalSystem/DMO/PartsRequestDMO.cs index c778aad..8d48a9b 100644 --- a/Fab2ApprovalSystem/DMO/PartsRequestDMO.cs +++ b/Fab2ApprovalSystem/DMO/PartsRequestDMO.cs @@ -1,129 +1,141 @@ -using System; using System.Collections.Generic; -using System.Configuration; using System.Data; using System.Data.SqlClient; +using System.IO; using System.Linq; -using System.Web; -using Fab2ApprovalSystem.Models; + using Dapper; -using System.Transactions; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.DMO -{ - public class PartsRequestDMO - { - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); +namespace Fab2ApprovalSystem.DMO; - WorkflowDMO wfDMO = new WorkflowDMO(); +public class PartsRequestDMO { - public IEnumerable GetPartsRequestList() - { - var r = this.db.Query("PartsRequestGetList", commandType: CommandType.StoredProcedure).ToList(); - return r; - } + private readonly AppSettings _AppSettings; + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - public void Insert(PartsRequest pr) - { - var parameters = new DynamicParameters(); - parameters.Add("@PRNumber", value: pr.PRNumber, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@OriginatorID", pr.OriginatorID); - - this.db.Execute("PartsRequestInsert", parameters, commandType: CommandType.StoredProcedure); - - pr.PRNumber = parameters.Get("@PRNumber"); - } - - public void Update(PartsRequest pr) - { - var parameters = new DynamicParameters(); - parameters.Add("@PRNumber", pr.PRNumber); - parameters.Add("@Title", pr.Title); - parameters.Add("@RequestorID", pr.RequestorID); - parameters.Add("@TechLeadID", pr.TechLeadID); - parameters.Add("@Description", pr.Description); - - this.db.Execute("PartsRequestUpdate", parameters, commandType: CommandType.StoredProcedure); - } - - public PartsRequest Get(int PRNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@PRNumber", value: PRNumber, dbType: DbType.Int32); - - return this.db.Query("PartsRequestGet", parameters, commandType: CommandType.StoredProcedure).SingleOrDefault(); - } - - public IEnumerable GetAttachments(int prNumber) - { - var attachments = this.db.Query( - "SELECT AttachmentID, PRNumber, FileName, A.UserID, UploadDate, U.FirstName + ' ' + U.LastName AS FullName " + - "FROM PartsRequestAttachment A " + - "INNER JOIN Users U ON U.UserID = A.UserID " + - "WHERE PRNumber = @PRNumber", - new { PRNumber = prNumber }).ToList(); - return attachments; - } - - public void InsertAttachment(PartsRequestAttachment attach) - { - var parameters = new DynamicParameters(); - parameters.Add("@PRNumber", attach.PRNumber); - parameters.Add("@UserID", attach.UserID); - parameters.Add("@FileName", attach.FileName); - - this.db.Execute("PartsRequestInsertAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - public string GetFileName(string attachmentID) - { - var parameters = new DynamicParameters(); - parameters.Add("@AttachmentID", attachmentID); - var fileName = this.db.Query("PartsRequestGetAttachmentFileName", parameters, commandType: CommandType.StoredProcedure).Single(); - return fileName; - } - - public void DeleteAttachment(int attachmentID) - { - var parameters = new DynamicParameters(); - parameters.Add("@AttachmentID", attachmentID); - this.db.Execute("PartsRequestDeleteAttachment", parameters, commandType: CommandType.StoredProcedure); - } - - public void Submit(int prNumber, int userID) - { - var parameters = new DynamicParameters(); - parameters.Add("@PRNumber", prNumber); - parameters.Add("@UserID", userID); - this.db.Execute("PartsRequestSubmitForApproval", parameters, commandType: CommandType.StoredProcedure ); - } - - public IEnumerable GetApprovalLogHistory(int prNumber) - { - var parameters = new DynamicParameters(); - parameters.Add("@PRNumber", prNumber); - var approverList = this.db.Query("PartsRequestGetApprovalLogHistory", parameters, commandType: CommandType.StoredProcedure).ToList(); - return approverList; - } - - public IEnumerable GetMyPartsRequests(int userID) - { - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - - var r = this.db.Query("PartsRequestGetListByUser", parameters, commandType: CommandType.StoredProcedure); - return r.ToList(); - } - - public void DeleteDocument(int prNumber, int userid) - { - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userid); - parameters.Add("@PRNumber", prNumber); - - this.db.Execute("PartsRequestDelete", parameters, commandType: CommandType.StoredProcedure); - } + public PartsRequestDMO(AppSettings appSettings) => + _AppSettings = appSettings; + public IEnumerable GetPartsRequestList() { + List r = db.Query("PartsRequestGetList", commandType: CommandType.StoredProcedure).ToList(); + return r; } -} + + public void Insert(PartsRequest pr) { + DynamicParameters parameters = new(); + parameters.Add("@PRNumber", value: pr.PRNumber, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@OriginatorID", pr.OriginatorID); + + db.Execute("PartsRequestInsert", parameters, commandType: CommandType.StoredProcedure); + + pr.PRNumber = parameters.Get("@PRNumber"); + } + + public void Update(PartsRequest pr) { + DynamicParameters parameters = new(); + parameters.Add("@PRNumber", pr.PRNumber); + parameters.Add("@Title", pr.Title); + parameters.Add("@RequestorID", pr.RequestorID); + parameters.Add("@TechLeadID", pr.TechLeadID); + parameters.Add("@Description", pr.Description); + + db.Execute("PartsRequestUpdate", parameters, commandType: CommandType.StoredProcedure); + } + + public PartsRequest Get(int PRNumber) { + DynamicParameters parameters = new(); + parameters.Add("@PRNumber", value: PRNumber, dbType: DbType.Int32); + + return db.Query("PartsRequestGet", parameters, commandType: CommandType.StoredProcedure).SingleOrDefault(); + } + + public IEnumerable GetAttachments(int prNumber) { + List attachments = db.Query( + "SELECT AttachmentID, PRNumber, FileName, A.UserID, UploadDate, U.FirstName + ' ' + U.LastName AS FullName " + + "FROM PartsRequestAttachment A " + + "INNER JOIN Users U ON U.UserID = A.UserID " + + "WHERE PRNumber = @PRNumber", + new { PRNumber = prNumber }).ToList(); + return attachments; + } + + public void InsertAttachment(PartsRequestAttachment attach) { + DynamicParameters parameters = new(); + parameters.Add("@PRNumber", attach.PRNumber); + parameters.Add("@UserID", attach.UserID); + parameters.Add("@FileName", attach.FileName); + + db.Execute("PartsRequestInsertAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + public string GetFileName(string attachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@AttachmentID", attachmentID); + var fileName = db.Query("PartsRequestGetAttachmentFileName", parameters, commandType: CommandType.StoredProcedure).Single(); + return fileName; + } + + public void DeleteAttachment(int attachmentID) { + DynamicParameters parameters = new(); + parameters.Add("@AttachmentID", attachmentID); + db.Execute("PartsRequestDeleteAttachment", parameters, commandType: CommandType.StoredProcedure); + } + + public void Submit(int prNumber, int userID) { + DynamicParameters parameters = new(); + parameters.Add("@PRNumber", prNumber); + parameters.Add("@UserID", userID); + db.Execute("PartsRequestSubmitForApproval", parameters, commandType: CommandType.StoredProcedure); + } + + public IEnumerable GetApprovalLogHistory(int prNumber) { + DynamicParameters parameters = new(); + parameters.Add("@PRNumber", prNumber); + List approverList = db.Query("PartsRequestGetApprovalLogHistory", parameters, commandType: CommandType.StoredProcedure).ToList(); + return approverList; + } + + public IEnumerable GetMyPartsRequests(int userID) { + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + + IEnumerable r = db.Query("PartsRequestGetListByUser", parameters, commandType: CommandType.StoredProcedure); + return r.ToList(); + } + + public void DeleteDocument(int prNumber, int userid) { + DynamicParameters parameters = new(); + parameters.Add("@UserID", userid); + parameters.Add("@PRNumber", prNumber); + + db.Execute("PartsRequestDelete", parameters, commandType: CommandType.StoredProcedure); + } + + public void AttachSave(int prNumber, int userId, string fullFileName, Stream stream) { + // Some browsers send file names with full path. + // We are only interested in the file name. + var fileName = Path.GetFileName(fullFileName); + + string prFolderPath = _AppSettings.AttachmentFolder + "PartsRequest\\" + prNumber.ToString(); + + DirectoryInfo di = new(prFolderPath); + if (!di.Exists) + di.Create(); + + var physicalPath = Path.Combine(prFolderPath, fileName); + + using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { + stream.CopyTo(fileStream); + } + PartsRequestAttachment attach = new() { + PRNumber = prNumber, + FileName = fileName, + UserID = userId, + }; + InsertAttachment(attach); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/SAM_DMO.cs b/Fab2ApprovalSystem/DMO/SAM_DMO.cs index 74d8fb3..08cb4cc 100644 --- a/Fab2ApprovalSystem/DMO/SAM_DMO.cs +++ b/Fab2ApprovalSystem/DMO/SAM_DMO.cs @@ -1,29 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Configuration; +using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; -using System.Web; -using Dapper; using System.Text; -namespace Fab2ApprovalSystem.DMO -{ - public class SAM_DMO - { - private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["SAMDBConnectionString"].ConnectionString); +using Dapper; +namespace Fab2ApprovalSystem.DMO; - public int HasITARAccess(string userID) - { +public class SAM_DMO { + private readonly IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["SAMDBConnectionString"].ConnectionString); - StringBuilder query = new StringBuilder("SELECT COUNT(*) FROM dbo.fnIsUserITARCompliant(@UserID) "); - //query.Append("WHERE UserID = @UserID AND AND EmployeeStatus = 'Active'"); - return this.db.Query(query.ToString(), new { UserID = userID }).SingleOrDefault(); - - } - - + public int HasITARAccess(string userID) { + StringBuilder query = new("SELECT COUNT(*) FROM dbo.fnIsUserITARCompliant(@UserID) "); + //query.Append("WHERE UserID = @UserID AND AND EmployeeStatus = 'Active'"); + return db.Query(query.ToString(), new { UserID = userID }).SingleOrDefault(); } + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/TrainingDMO.cs b/Fab2ApprovalSystem/DMO/TrainingDMO.cs index b6ae55a..5b3b05c 100644 --- a/Fab2ApprovalSystem/DMO/TrainingDMO.cs +++ b/Fab2ApprovalSystem/DMO/TrainingDMO.cs @@ -1,479 +1,538 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; -using System.Web; + using Dapper; -using Fab2ApprovalSystem.Models; -using System.Text; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.DMO -{ - public class TrainingDMO - { - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - private static FabApprovalTrainingEntities FabApprovalDB = new FabApprovalTrainingEntities(); +namespace Fab2ApprovalSystem.DMO; - public int Create(int issueId) - { - var parameters = new DynamicParameters(); +public class TrainingDMO { + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); +#if !NET8 + private static FabApprovalTrainingEntities FabApprovalDB = new FabApprovalTrainingEntities(); +#endif - parameters = new DynamicParameters(); - parameters.Add("@TrainingId", dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@ECNNumber", issueId); + public int Create(int issueId) { + DynamicParameters parameters = new(); - this.db.Execute("InsertTrainingItem", parameters, commandType: CommandType.StoredProcedure); - int trainingId = parameters.Get("@TrainingId"); + parameters = new DynamicParameters(); + parameters.Add("@TrainingId", dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@ECNNumber", issueId); - return trainingId; + db.Execute("InsertTrainingItem", parameters, commandType: CommandType.StoredProcedure); + int trainingId = parameters.Get("@TrainingId"); + + return trainingId; + } + + public int CreateAssignment(int trainingId, int userId) { + DynamicParameters parameters = new(); + + parameters = new DynamicParameters(); + //parameters.Add("@TrainingId", dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@TrainingID", trainingId); + parameters.Add("@UserID", userId); + parameters.Add("@AssignmentID", dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + + db.Execute("InsertTrainingAssignment", parameters, commandType: CommandType.StoredProcedure); + int assignmentId = parameters.Get("@AssignmentID"); + + return assignmentId; + } + + public IEnumerable GetAllTrainings() { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + IEnumerable allTrainings = (from a in db.Trainings select a).ToList(); + + return allTrainings; +#else + throw new NotImplementedException(); +#endif + } + + public Training GetTraining(int trainingId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + Training trainingRecord = new Training(); + trainingRecord = (from a in db.Trainings where a.TrainingID == trainingId select a).FirstOrDefault(); + return trainingRecord; +#else + throw new NotImplementedException(); +#endif + } + + public TrainingAssignment GetAssignment(int assignmentId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + TrainingAssignment assignmentRecord = (from a in db.TrainingAssignments where a.ID == assignmentId select a).FirstOrDefault(); + return assignmentRecord; +#else + throw new NotImplementedException(); +#endif + } + + public int GetTrainingId(int issueId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + int ECNId = issueId; + int trainingId = (from a in db.Trainings where a.ECN == ECNId select a.TrainingID).FirstOrDefault(); + + return trainingId; +#else + throw new NotImplementedException(); +#endif + } + + public List GetTrainees(int groupId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + var users = (from a in db.TrainingGroupMembers where a.TrainingGroupID == groupId select a.UserID).ToList(); + + return users; +#else + throw new NotImplementedException(); +#endif + } + + public bool isUserTrainingMember(int groupId, int userId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + var users = (from a in db.TrainingGroupMembers where a.TrainingGroupID == groupId && a.UserID == userId select a).FirstOrDefault(); + + if (users == null) { + return false; + } else { + return true; } - public int CreateAssignment(int trainingId, int userId) - { - var parameters = new DynamicParameters(); +#else + throw new NotImplementedException(); +#endif + } - parameters = new DynamicParameters(); - //parameters.Add("@TrainingId", dbType: DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@TrainingID", trainingId); - parameters.Add("@UserID", userId); - parameters.Add("@AssignmentID", dbType: DbType.Int32, direction: ParameterDirection.InputOutput); + public List GetTrainingGroups() { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + return (from a in db.TrainingGroups select a).ToList(); +#else + throw new NotImplementedException(); +#endif + } - this.db.Execute("InsertTrainingAssignment", parameters, commandType: CommandType.StoredProcedure); - int assignmentId = parameters.Get("@AssignmentID"); + public TrainingGroup GetTrainingGroupByID(int groupId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + TrainingGroup groups = (from a in db.TrainingGroups where a.TrainingGroupID == groupId select a).FirstOrDefault(); + return groups; +#else + throw new NotImplementedException(); +#endif + } - return assignmentId; + public List GetECNAssignedTrainingGroups(int ECNNumber) { +#if !NET8 + List trainingGroups = (from a in FabApprovalDB.ECNTrainingBies where a.ECNNumber == ECNNumber select a.AcknowledgementTrainingByID).ToList(); + + return trainingGroups; +#else + throw new NotImplementedException(); +#endif + } + + public void AddTrainingGroupToECN(int ECNNumber, int groupId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + //ECNTrainingBy ecnTraining = new ECNTrainingBy(); + //ecnTraining.AcknowledgementTrainingByID = groupId; + //ecnTraining.ECNNumber = ECNNumber; + + var parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ECNNumber); + parameters.Add("@TrainingByID", groupId); + + this.db.Execute("ECNInsertTrainingBy", parameters, commandType: CommandType.StoredProcedure); + + //db.ECNTrainingBies.Add(ecnTraining); +#else + throw new NotImplementedException(); +#endif + } + + public void SetTrainingFlag(int ECNNumber) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + //ECNTrainingBy ecnTraining = new ECNTrainingBy(); + //ecnTraining.AcknowledgementTrainingByID = groupId; + //ecnTraining.ECNNumber = ECNNumber; + + var parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ECNNumber); + + this.db.Execute("ECNSetTrainingFlag", parameters, commandType: CommandType.StoredProcedure); + + //db.ECNTrainingBies.Add(ecnTraining); +#else + throw new NotImplementedException(); +#endif + } + + public List GetAllTrainingAssignments(int TrainingID) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + var TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a; + + RefreshTrainingData(TrainingID, TrainingData); + + TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a; + + return TrainingData.ToList(); +#else + throw new NotImplementedException(); +#endif + } + + public List GetTrainingAssignments(int TrainingID) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + var TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID && a.Deleted != true select a; + + RefreshTrainingData(TrainingID, TrainingData); + + TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a; + + return TrainingData.ToList(); +#else + throw new NotImplementedException(); +#endif + } + + public List GetTrainingAssignmentsByUser(int TrainingID, int userID) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + var TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID && a.UserID == userID select a; + + return TrainingData.ToList(); +#else + throw new NotImplementedException(); +#endif + } + + public List GetAssignedDocs(int trainingAssignmentId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + var docs = (from a in db.TrainingDocAcks where a.TrainingAssignmentID == trainingAssignmentId && a.Deleted != true select a).ToList(); + + return docs; +#else + throw new NotImplementedException(); +#endif + } + + public void AcknowledgeDocument(int trainingDocAckID) { + DynamicParameters parameters = new(); + + parameters = new DynamicParameters(); + parameters.Add("@TrainingDocAckID", trainingDocAckID); + //parameters.Add("@AttachmentID", attachmentID); + + db.Execute("TrainingAcknowledgeDocument", parameters, commandType: CommandType.StoredProcedure); + } + + public void UpdateAssignmentStatus(int trainingAssignmentID) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + var RecordToUpdate = (from a in db.TrainingAssignments where a.ID == trainingAssignmentID select a).SingleOrDefault(); + if (RecordToUpdate.status != true) { + RecordToUpdate.DateCompleted = DateTime.Now; + RecordToUpdate.status = true; + try { + db.SaveChanges(); + } catch (InvalidOperationException e) { + string exception = e.ToString(); + Console.WriteLine(e); + } } - public IEnumerable GetAllTrainings() - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - IEnumerable allTrainings = (from a in db.Trainings select a).ToList(); +#else + throw new NotImplementedException(); +#endif + } - return allTrainings; - } - public Training GetTraining(int trainingId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - Training trainingRecord = new Training(); - trainingRecord = (from a in db.Trainings where a.TrainingID == trainingId select a).FirstOrDefault(); - return trainingRecord; - } - public TrainingAssignment GetAssignment(int assignmentId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - TrainingAssignment assignmentRecord = (from a in db.TrainingAssignments where a.ID == assignmentId select a).FirstOrDefault(); - return assignmentRecord; - } - public int GetTrainingId(int issueId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - int ECNId = issueId; - int trainingId = (from a in db.Trainings where a.ECN == ECNId select a.TrainingID).FirstOrDefault(); + public int GetTrainingIdByAssignment(int trainingAssignmentID) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + int trainingID = (from a in db.TrainingAssignments where a.ID == trainingAssignmentID select a.TrainingID).SingleOrDefault(); - return trainingId; - } - public List GetTrainees(int groupId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - var users = (from a in db.TrainingGroupMembers where a.TrainingGroupID == groupId select a.UserID).ToList(); + return trainingID; +#else + throw new NotImplementedException(); +#endif + } - return users; - } - public bool isUserTrainingMember(int groupId, int userId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - var users = (from a in db.TrainingGroupMembers where a.TrainingGroupID == groupId && a.UserID == userId select a).FirstOrDefault(); + public void UpdateTrainingStatus(int trainingId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + Training training = (from a in db.Trainings where a.TrainingID == trainingId select a).SingleOrDefault(); - if (users == null) - { + if (training != null) { + training.CompletedDate = DateTime.Now; + training.Status = true; + + try { + db.SaveChanges(); + } catch (InvalidOperationException e) { + string exception = e.ToString(); + Console.WriteLine(e); + } + } +#else + throw new NotImplementedException(); +#endif + } + + public void reOpenTraining(int trainingId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + Training training = (from a in db.Trainings where a.TrainingID == trainingId select a).SingleOrDefault(); + + if (training != null) { + training.CompletedDate = null; + training.Status = false; + + try { + db.SaveChanges(); + } catch (InvalidOperationException e) { + string exception = e.ToString(); + Console.WriteLine(e); + } + } +#else + throw new NotImplementedException(); +#endif + } + + public bool CheckTrainingStatus(int trainingAssignmentID) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + bool isFinished = true; + int trainingID = (from a in db.TrainingAssignments where a.ID == trainingAssignmentID select a.TrainingID).SingleOrDefault(); + var trainingAssignments = from a in db.TrainingAssignments where a.TrainingID == trainingID && a.Deleted != true select a; + + foreach (var training in trainingAssignments) { + if (training.status == false) { + isFinished = false; + } + } + return isFinished; +#else + throw new NotImplementedException(); +#endif + } + + public bool CheckTrainingAssignmentStatus(int trainingAssignmentID) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + bool isFinished = true; + //TrainingDocAck docsAssigned = null; + + var docsAssigned = from a in db.TrainingDocAcks where a.TrainingAssignmentID == trainingAssignmentID && a.Deleted != true select a; + + foreach (var doc in docsAssigned) { + if (doc.Reviewed == false) { + isFinished = false; + } + } + + return isFinished; +#else + throw new NotImplementedException(); +#endif + } + + public bool IsUserAssigned(int userId, int trainingId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + bool userHasAssignment = false; + + var assignments = (from a in db.TrainingAssignments where a.TrainingID == trainingId && a.UserID == userId && a.Deleted != true select a).ToList(); + + if (assignments.Count() > 0) { + userHasAssignment = true; + } + + return userHasAssignment; +#else + throw new NotImplementedException(); +#endif + } + + public List GetTrainings() { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + var trainings = from a in db.Trainings select a; + + return trainings.ToList(); +#else + throw new NotImplementedException(); +#endif + } + + public List GetTrainingAssignmentsByUserID(int userID) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + var trainingAssignments = from a in db.TrainingAssignments where a.UserID == userID && a.Deleted != true select a; + + return trainingAssignments.ToList(); +#else + throw new NotImplementedException(); +#endif + } + + public void DeleteTrainingAssignment(int trainingAssignmentId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + var trainingAssignments = from a in db.TrainingAssignments where a.ID == trainingAssignmentId select a; + + foreach (var item in trainingAssignments) { + item.Deleted = true; + item.DeletedDate = DateTime.Now; + } + try { + db.SaveChanges(); + } catch (InvalidOperationException e) { + string exception = e.ToString(); + Console.WriteLine(e); + } +#else + throw new NotImplementedException(); +#endif + } + + public void DeleteTrainingDocAck(int trainingAssignmentId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + var trainingDocAcks = from a in db.TrainingDocAcks where a.TrainingAssignmentID == trainingAssignmentId select a; + + foreach (var item in trainingDocAcks) { + item.Deleted = true; + item.DeletedDate = DateTime.Now; + } + try { + db.SaveChanges(); + } catch (InvalidOperationException e) { + string exception = e.ToString(); + Console.WriteLine(e); + } +#else + throw new NotImplementedException(); +#endif + } + + public void DeleteTraining(int trainingId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + Training training = (from a in db.Trainings where a.TrainingID == trainingId select a).FirstOrDefault(); + + if (training != null) { + training.Deleted = true; + training.DeletedDate = DateTime.Now; + } + + List trainingAssignments = (from a in db.TrainingAssignments where a.TrainingID == trainingId select a).ToList(); + db.SaveChanges(); + foreach (TrainingAssignment trainingAssignment in trainingAssignments) { + DeleteTrainingAssignment(trainingAssignment.ID); + DeleteTrainingDocAck(trainingAssignment.ID); + //db.SaveChanges(); + } +#else + throw new NotImplementedException(); +#endif + } + + public void DeleteAssignmentByUserId(int userId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + + var userAssignments = (from a in db.TrainingAssignments where a.UserID == userId select a).ToList(); + + foreach (var item in userAssignments) { + //get document assignments + var docAssignments = (from a in db.TrainingDocAcks where a.TrainingAssignmentID == item.TrainingID select a).ToList(); + //delete each docAssignment + foreach (var docAssignment in docAssignments) { + DeleteTrainingDocAck(docAssignment.ID); + } + DeleteTrainingAssignment(item.ID); + } +#else + throw new NotImplementedException(); +#endif + } + + public bool CheckValidDocAck(int docAckId) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + TrainingDocAck ack = (from a in db.TrainingDocAcks where a.ID == docAckId select a).FirstOrDefault(); + + //TODO Check the user is valid + + //Check that the assignment exists + if (ack != null) { + //Check that the assignment isn't deleted + if (ack.Deleted == true) { return false; } - else - { + //Check that the assignment isn't completed + else if (ack.Reviewed == true) { + return false; + } else { return true; } - - } - public List GetTrainingGroups() - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - return (from a in db.TrainingGroups select a).ToList(); - } - public TrainingGroup GetTrainingGroupByID(int groupId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - TrainingGroup groups = (from a in db.TrainingGroups where a.TrainingGroupID == groupId select a).FirstOrDefault(); - return groups; - } - public List GetECNAssignedTrainingGroups(int ECNNumber) - { - List trainingGroups = (from a in FabApprovalDB.ECNTrainingBies where a.ECNNumber == ECNNumber select a.AcknowledgementTrainingByID).ToList(); - - return trainingGroups; - } - public void AddTrainingGroupToECN(int ECNNumber, int groupId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - //ECNTrainingBy ecnTraining = new ECNTrainingBy(); - //ecnTraining.AcknowledgementTrainingByID = groupId; - //ecnTraining.ECNNumber = ECNNumber; - - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ECNNumber); - parameters.Add("@TrainingByID", groupId); - - this.db.Execute("ECNInsertTrainingBy", parameters, commandType: CommandType.StoredProcedure); - - - - - //db.ECNTrainingBies.Add(ecnTraining); - - } - public void SetTrainingFlag(int ECNNumber) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - //ECNTrainingBy ecnTraining = new ECNTrainingBy(); - //ecnTraining.AcknowledgementTrainingByID = groupId; - //ecnTraining.ECNNumber = ECNNumber; - - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ECNNumber); - - this.db.Execute("ECNSetTrainingFlag", parameters, commandType: CommandType.StoredProcedure); - - - - - //db.ECNTrainingBies.Add(ecnTraining); - - } - public List GetAllTrainingAssignments(int TrainingID) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - var TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a; - - RefreshTrainingData(TrainingID, TrainingData); - - TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a; - - return TrainingData.ToList(); - } - public List GetTrainingAssignments(int TrainingID) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - var TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID && a.Deleted != true select a; - - RefreshTrainingData(TrainingID, TrainingData); - - TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a; - - return TrainingData.ToList(); - } - public List GetTrainingAssignmentsByUser(int TrainingID, int userID) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - var TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID && a.UserID == userID select a; - - return TrainingData.ToList(); - } - public List GetAssignedDocs(int trainingAssignmentId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - var docs = (from a in db.TrainingDocAcks where a.TrainingAssignmentID == trainingAssignmentId && a.Deleted != true select a).ToList(); - - return docs; - } - public void AcknowledgeDocument(int trainingDocAckID) - { - var parameters = new DynamicParameters(); - - parameters = new DynamicParameters(); - parameters.Add("@TrainingDocAckID", trainingDocAckID); - //parameters.Add("@AttachmentID", attachmentID); - - this.db.Execute("TrainingAcknowledgeDocument", parameters, commandType: CommandType.StoredProcedure); - - } - public void UpdateAssignmentStatus(int trainingAssignmentID) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - var RecordToUpdate = (from a in db.TrainingAssignments where a.ID == trainingAssignmentID select a).SingleOrDefault(); - if(RecordToUpdate.status != true) - { - RecordToUpdate.DateCompleted = DateTime.Now; - RecordToUpdate.status = true; - try - { - db.SaveChanges(); - } - catch (InvalidOperationException e) - { - string exception = e.ToString(); - Console.WriteLine(e); - } - } - - - } - public int GetTrainingIdByAssignment(int trainingAssignmentID) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - int trainingID = (from a in db.TrainingAssignments where a.ID == trainingAssignmentID select a.TrainingID).SingleOrDefault(); - - return trainingID; - } - public void UpdateTrainingStatus(int trainingId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - Training training = (from a in db.Trainings where a.TrainingID == trainingId select a).SingleOrDefault(); - - if (training != null) - { - training.CompletedDate = DateTime.Now; - training.Status = true; - - try - { - db.SaveChanges(); - } - catch (InvalidOperationException e) - { - string exception = e.ToString(); - Console.WriteLine(e); - } - } - } - public void reOpenTraining(int trainingId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - Training training = (from a in db.Trainings where a.TrainingID == trainingId select a).SingleOrDefault(); - - if (training != null) - { - training.CompletedDate = null; - training.Status = false; - - try - { - db.SaveChanges(); - } - catch (InvalidOperationException e) - { - string exception = e.ToString(); - Console.WriteLine(e); - } - } - } - - public bool CheckTrainingStatus(int trainingAssignmentID) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - bool isFinished = true; - int trainingID = (from a in db.TrainingAssignments where a.ID == trainingAssignmentID select a.TrainingID).SingleOrDefault(); - var trainingAssignments = from a in db.TrainingAssignments where a.TrainingID == trainingID && a.Deleted != true select a; - - foreach (var training in trainingAssignments) - { - if (training.status == false) - { - isFinished = false; - } - } - - - return isFinished; - } - - public bool CheckTrainingAssignmentStatus(int trainingAssignmentID) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - bool isFinished = true; - //TrainingDocAck docsAssigned = null; - - var docsAssigned = from a in db.TrainingDocAcks where a.TrainingAssignmentID == trainingAssignmentID && a.Deleted != true select a; - - - - - foreach (var doc in docsAssigned) - { - if (doc.Reviewed == false) - { - isFinished = false; - } - } - - return isFinished; - } - public bool IsUserAssigned(int userId, int trainingId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - bool userHasAssignment = false; - - var assignments = (from a in db.TrainingAssignments where a.TrainingID == trainingId && a.UserID == userId && a.Deleted != true select a).ToList(); - - if(assignments.Count() > 0) - { - userHasAssignment = true; - } - - return userHasAssignment; - } - public List GetTrainings() - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - var trainings = from a in db.Trainings select a; - - return trainings.ToList(); - } - public List GetTrainingAssignmentsByUserID(int userID) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - var trainingAssignments = from a in db.TrainingAssignments where a.UserID == userID && a.Deleted != true select a; - - return trainingAssignments.ToList(); - } - - public void DeleteTrainingAssignment(int trainingAssignmentId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - var trainingAssignments = from a in db.TrainingAssignments where a.ID == trainingAssignmentId select a; - - foreach (var item in trainingAssignments) - { - item.Deleted = true; - item.DeletedDate = DateTime.Now; - } - try - { - db.SaveChanges(); - } - catch (InvalidOperationException e) - { - string exception = e.ToString(); - Console.WriteLine(e); - } - } - public void DeleteTrainingDocAck(int trainingAssignmentId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - var trainingDocAcks = from a in db.TrainingDocAcks where a.TrainingAssignmentID == trainingAssignmentId select a; - - foreach (var item in trainingDocAcks) - { - item.Deleted = true; - item.DeletedDate = DateTime.Now; - } - try - { - db.SaveChanges(); - } - catch (InvalidOperationException e) - { - string exception = e.ToString(); - Console.WriteLine(e); - } - } - public void DeleteTraining(int trainingId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - Training training = (from a in db.Trainings where a.TrainingID == trainingId select a).FirstOrDefault(); - - if (training != null) - { - training.Deleted = true; - training.DeletedDate = DateTime.Now; - } - - List trainingAssignments = (from a in db.TrainingAssignments where a.TrainingID == trainingId select a).ToList(); - db.SaveChanges(); - foreach (TrainingAssignment trainingAssignment in trainingAssignments) - { - DeleteTrainingAssignment(trainingAssignment.ID); - DeleteTrainingDocAck(trainingAssignment.ID); - //db.SaveChanges(); - } - - - } - public void DeleteAssignmentByUserId(int userId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - - var userAssignments = (from a in db.TrainingAssignments where a.UserID == userId select a).ToList(); - - foreach (var item in userAssignments) - { - //get document assignments - var docAssignments = (from a in db.TrainingDocAcks where a.TrainingAssignmentID == item.TrainingID select a).ToList(); - //delete each docAssignment - foreach (var docAssignment in docAssignments) - { - DeleteTrainingDocAck(docAssignment.ID); - } - DeleteTrainingAssignment(item.ID); - } - } - public bool CheckValidDocAck(int docAckId) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - TrainingDocAck ack = (from a in db.TrainingDocAcks where a.ID == docAckId select a).FirstOrDefault(); - - //TODO Check the user is valid - - //Check that the assignment exists - if (ack != null) - { - //Check that the assignment isn't deleted - if (ack.Deleted == true) - { - return false; - } - //Check that the assignment isn't completed - else if (ack.Reviewed == true) - { - return false; - } - else - { - return true; - } - } - else - { - return false; - } - - } - public List GetAllOpenTrainings() - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - List openTrainings = (from a in db.Trainings where a.Status != true && a.Deleted != true select a).ToList(); - return openTrainings; - } - public List GetOpenAssignmentsByTrainingID(int trainingID) - { - FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); - List openAssignments = (from a in FabApprovalDB.TrainingAssignments where a.TrainingID == trainingID && a.status != true && a.Deleted != true select a).ToList(); - return openAssignments; - } - - private void RefreshTrainingData(int TrainingID, IQueryable TrainingData) - { - bool assignmentIsIncomplete = false; - UserAccountDMO userAccountDMO = new UserAccountDMO(); - foreach (TrainingAssignment assignment in TrainingData) - { - LoginModel userModel = userAccountDMO.GetUserByID(assignment.UserID); - if (!userModel.IsActive) UpdateAssignmentStatus(assignment.ID); - if (assignment.Deleted != true && (assignment.DateCompleted is null || assignment.DateCompleted > DateTime.Now)) - assignmentIsIncomplete = true; - } - - if (!assignmentIsIncomplete) - UpdateTrainingStatus(TrainingID); + } else { + return false; } +#else + throw new NotImplementedException(); +#endif } -} + + public List GetAllOpenTrainings() { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + List openTrainings = (from a in db.Trainings where a.Status != true && a.Deleted != true select a).ToList(); + return openTrainings; +#else + throw new NotImplementedException(); +#endif + } + + public List GetOpenAssignmentsByTrainingID(int trainingID) { +#if !NET8 + FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); + List openAssignments = (from a in FabApprovalDB.TrainingAssignments where a.TrainingID == trainingID && a.status != true && a.Deleted != true select a).ToList(); + return openAssignments; +#else + throw new NotImplementedException(); +#endif + } + + private void RefreshTrainingData(int TrainingID, IQueryable TrainingData) { + bool assignmentIsIncomplete = false; + UserAccountDMO userAccountDMO = new(); + foreach (TrainingAssignment assignment in TrainingData) { + LoginModel userModel = userAccountDMO.GetUserByID(assignment.UserID); + if (!userModel.IsActive) + UpdateAssignmentStatus(assignment.ID); + if (assignment.Deleted != true && (assignment.DateCompleted is null || assignment.DateCompleted > DateTime.Now)) + assignmentIsIncomplete = true; + } + + if (!assignmentIsIncomplete) + UpdateTrainingStatus(TrainingID); + } +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/UserAccountDMO.cs b/Fab2ApprovalSystem/DMO/UserAccountDMO.cs index b8db94f..df28cda 100644 --- a/Fab2ApprovalSystem/DMO/UserAccountDMO.cs +++ b/Fab2ApprovalSystem/DMO/UserAccountDMO.cs @@ -1,212 +1,149 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; -using System.Web; -using Dapper; -using Fab2ApprovalSystem.Models; using System.Text; + +using Dapper; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.DMO -{ - public class UserAccountDMO - { - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); +namespace Fab2ApprovalSystem.DMO; +public class UserAccountDMO { + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - //public List GetUser(string loginID) - //{ - // StringBuilder sql = new StringBuilder(); - // sql.Append("SELECT * FROM Users WHERE LoginID = '" + loginID + "'"); + public IEnumerable GetAllUsers() { + StringBuilder sql = new(); + //sql.Append("SELECT U.FirstName + ' ' + U.LastName AS FullName, U1.FirstName + ' ' + U1.LastName AS DelegatedToFullName, U.* "); + //sql.Append("FROM Users U LEFT JOIN Users U1 "); + //sql.Append("ON U.UserID = U1.DelegatedTo ORDER BY FirstName "); - // return this.db.Query(sql.ToString()).ToList(); - //} + //sql.Append("SELECT FirstName + ' ' + LastName AS FullName, * FROM Users ORDER BY FirstName "); + sql.Append(" SELECT U.FirstName + ' ' + U.LastName AS FullName, U.* , U1.FirstName + ' ' + U1.LastName AS DelegatedToFullName "); + sql.Append("FROM Users U LEFT JOIN Users U1 ON U.DelegatedTo = U1.UserID "); + sql.Append("ORDER BY FirstName "); - public IEnumerable GetAllUsers() - { - StringBuilder sql = new StringBuilder(); - //sql.Append("SELECT U.FirstName + ' ' + U.LastName AS FullName, U1.FirstName + ' ' + U1.LastName AS DelegatedToFullName, U.* "); - //sql.Append("FROM Users U LEFT JOIN Users U1 "); - //sql.Append("ON U.UserID = U1.DelegatedTo ORDER BY FirstName "); - - //sql.Append("SELECT FirstName + ' ' + LastName AS FullName, * FROM Users ORDER BY FirstName "); - sql.Append(" SELECT U.FirstName + ' ' + U.LastName AS FullName, U.* , U1.FirstName + ' ' + U1.LastName AS DelegatedToFullName "); - sql.Append("FROM Users U LEFT JOIN Users U1 ON U.DelegatedTo = U1.UserID "); - sql.Append("ORDER BY FirstName "); - - return this.db.Query(sql.ToString()).ToList(); - } - public IEnumerable GetAllActiveUsers() - { - StringBuilder sql = new StringBuilder(); - //sql.Append("SELECT U.FirstName + ' ' + U.LastName AS FullName, U1.FirstName + ' ' + U1.LastName AS DelegatedToFullName, U.* "); - //sql.Append("FROM Users U LEFT JOIN Users U1 "); - //sql.Append("ON U.UserID = U1.DelegatedTo ORDER BY FirstName "); - - //sql.Append("SELECT FirstName + ' ' + LastName AS FullName, * FROM Users ORDER BY FirstName "); - sql.Append(" SELECT U.FirstName + ' ' + U.LastName AS FullName, U.* , U1.FirstName + ' ' + U1.LastName AS DelegatedToFullName "); - sql.Append("FROM Users U LEFT JOIN Users U1 ON U.DelegatedTo = U1.UserID "); - sql.Append("WHERE U.IsActive = 1 "); - sql.Append("ORDER BY FirstName "); - - return this.db.Query(sql.ToString()).ToList(); - } - - - - - - public LoginModel GetUser(string loginID) - { - //StringBuilder sql = new StringBuilder(); - //sql.Append("SELECT * FROM Users WHERE LoginID = '" + loginID + "'"); - - //return this.db.Query(sql.ToString()).SingleOrDefault(); - - - return this.db.Query("SELECT FirstName + ' ' + LastName AS FullName, * FROM Users WHERE LoginID = @loginID AND IsActive = 1 ", new { loginID = loginID }).Take(1).SingleOrDefault(); - } - - public LoginModel GetUserByID(int userID) - { - return this.db.Query( - "SELECT FirstName + ' ' + LastName AS FullName, * FROM Users WHERE UserID = @UserID ", - new { UserID = userID }).Take(1).SingleOrDefault(); - } - - public string GetUserEmailByID(string userID) - { - return this.db.Query( - "SELECT Email FROM Users WHERE UserID = @UserID ", - new { UserID = userID }).Take(1).SingleOrDefault(); - } - - /// - /// - /// - /// - internal void UpdateUser(LoginModel model) - { - string sql; - sql = "UPDATE Users SET LoginID = @LoginID, FirstName = @FirstName, LastName = @LastName, Email = @Email, IsActive = @IsActive, IsAdmin = @IsAdmin WHERE UserID = @UserID"; - var parameters = new DynamicParameters(); - parameters.Add("@UserID", model.UserID); - parameters.Add("@LoginID", model.LoginID); - parameters.Add("@FirstName", model.FirstName); - parameters.Add("@LastName", model.LastName ); - parameters.Add("@Email", model.Email); - parameters.Add("@IsAdmin", model.IsAdmin); - parameters.Add("@IsActive", model.IsActive); - - this.db.Execute(sql, parameters); - } - - /// - /// - /// - /// - internal void DeleteUser(LoginModel model) - { - string sql; - //sql = "DELETE Users WHERE UserID = @UserID"; - sql = "UPDATE Users SET IsActive = 0 WHERE UserID = @UserID"; - var parameters = new DynamicParameters(); - parameters.Add("@UserID", model.UserID); - - this.db.Execute(sql, parameters); - } - - - /// - /// - /// - /// - internal void InsertUser(LoginModel model) - { - //string sql; - //sql = "INSERT Users (LoginID, FirstName, LastName, IsAdmin) VALUES (@LoginID, @FirstName, @LastName, @IsAdmin )"; - var parameters = new DynamicParameters(); - parameters.Add("@UserID", model.UserID, DbType.Int32, direction: ParameterDirection.InputOutput); - parameters.Add("@LoginID", model.LoginID); - parameters.Add("@FirstName", model.FirstName); - parameters.Add("@LastName", model.LastName); - parameters.Add("@Email", model.Email); - parameters.Add("@IsAdmin", model.IsAdmin); - - this.db.Execute("InsertUsers", parameters, commandType: CommandType.StoredProcedure); - int userid = parameters.Get("@UserID"); - model.UserID = userid; - - } - - /// - /// - /// - /// - /// - internal void UpdateInsertITARAccess(string userID, string hasITARAccess) - { - - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - parameters.Add("@HasITARAccess", hasITARAccess); - - this.db.Execute("ITARAccessUpdateInsert", parameters, commandType: CommandType.StoredProcedure); - - } - - /// - /// - /// - /// - /// - internal bool GetITARAccess(int userID) - { - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - - var results = this.db.Query( - "SELECT HasITARAccess FROM SAMUsers, Users WHERE Users.UserID = @UserID AND SAMUsers.UserID = Users.LoginID", - parameters, commandType: CommandType.Text); - if ((results != null) && (results.Count() > 0) && (results.First() == "1")) - return true; - - return false; - } - - /// - /// - /// - /// - /// - internal bool GetEC_AD_Users(string userID) - { - var parameters = new DynamicParameters(); - parameters.Add("@UserID", userID); - - var results = this.db.Query( - "SELECT UserID FROM EC_AD_Users WHERE UserID = @UserID", - parameters, commandType: CommandType.Text); - if ((results != null) && (results.Count() > 0)) - return true; - - return false; - } - - internal void ProcessOoO() - { - var parameters = new DynamicParameters(); - this.db.Execute("ProcesOOOEnableStatus", commandType: CommandType.StoredProcedure); - - } - internal void ExpireOoO() - { - var parameters = new DynamicParameters(); - this.db.Execute("ProcesOOOExpiration", commandType: CommandType.StoredProcedure); - - } + return db.Query(sql.ToString()).ToList(); } -} + + public IEnumerable GetAllActiveUsers() { + StringBuilder sql = new(); + //sql.Append("SELECT U.FirstName + ' ' + U.LastName AS FullName, U1.FirstName + ' ' + U1.LastName AS DelegatedToFullName, U.* "); + //sql.Append("FROM Users U LEFT JOIN Users U1 "); + //sql.Append("ON U.UserID = U1.DelegatedTo ORDER BY FirstName "); + + //sql.Append("SELECT FirstName + ' ' + LastName AS FullName, * FROM Users ORDER BY FirstName "); + sql.Append(" SELECT U.FirstName + ' ' + U.LastName AS FullName, U.* , U1.FirstName + ' ' + U1.LastName AS DelegatedToFullName "); + sql.Append("FROM Users U LEFT JOIN Users U1 ON U.DelegatedTo = U1.UserID "); + sql.Append("WHERE U.IsActive = 1 "); + sql.Append("ORDER BY FirstName "); + + return db.Query(sql.ToString()).ToList(); + } + + public LoginModel GetUser(string loginID) => + //StringBuilder sql = new StringBuilder(); + //sql.Append("SELECT * FROM Users WHERE LoginID = '" + loginID + "'"); + //return this.db.Query(sql.ToString()).SingleOrDefault(); + db.Query("SELECT FirstName + ' ' + LastName AS FullName, * FROM Users WHERE LoginID = @loginID AND IsActive = 1 ", new { loginID = loginID }).Take(1).SingleOrDefault(); + + public LoginModel GetUserByID(int userID) { + return db.Query( + "SELECT FirstName + ' ' + LastName AS FullName, * FROM Users WHERE UserID = @UserID ", + new { UserID = userID }).Take(1).SingleOrDefault(); + } + + public string GetUserEmailByID(int userID) { + return db.Query( + "SELECT Email FROM Users WHERE UserID = @UserID ", + new { UserID = userID }).Take(1).SingleOrDefault(); + } + + internal void UpdateUser(LoginModel model) { + string sql; + sql = "UPDATE Users SET LoginID = @LoginID, FirstName = @FirstName, LastName = @LastName, Email = @Email, IsActive = @IsActive, IsAdmin = @IsAdmin WHERE UserID = @UserID"; + DynamicParameters parameters = new(); + parameters.Add("@UserID", model.UserID); + parameters.Add("@LoginID", model.LoginID); + parameters.Add("@FirstName", model.FirstName); + parameters.Add("@LastName", model.LastName); + parameters.Add("@Email", model.Email); + parameters.Add("@IsAdmin", model.IsAdmin); + parameters.Add("@IsActive", model.IsActive); + + db.Execute(sql, parameters); + } + + internal void DeleteUser(LoginModel model) { + string sql; + //sql = "DELETE Users WHERE UserID = @UserID"; + sql = "UPDATE Users SET IsActive = 0 WHERE UserID = @UserID"; + DynamicParameters parameters = new(); + parameters.Add("@UserID", model.UserID); + + db.Execute(sql, parameters); + } + + internal void InsertUser(LoginModel model) { + //string sql; + //sql = "INSERT Users (LoginID, FirstName, LastName, IsAdmin) VALUES (@LoginID, @FirstName, @LastName, @IsAdmin )"; + DynamicParameters parameters = new(); + parameters.Add("@UserID", model.UserID, DbType.Int32, direction: ParameterDirection.InputOutput); + parameters.Add("@LoginID", model.LoginID); + parameters.Add("@FirstName", model.FirstName); + parameters.Add("@LastName", model.LastName); + parameters.Add("@Email", model.Email); + parameters.Add("@IsAdmin", model.IsAdmin); + + db.Execute("InsertUsers", parameters, commandType: CommandType.StoredProcedure); + int userid = parameters.Get("@UserID"); + model.UserID = userid; + } + + internal void UpdateInsertITARAccess(string userID, string hasITARAccess) { + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + parameters.Add("@HasITARAccess", hasITARAccess); + + db.Execute("ITARAccessUpdateInsert", parameters, commandType: CommandType.StoredProcedure); + } + + internal bool GetITARAccess(int userID) { + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + + var results = db.Query( + "SELECT HasITARAccess FROM SAMUsers, Users WHERE Users.UserID = @UserID AND SAMUsers.UserID = Users.LoginID", + parameters, commandType: CommandType.Text); + if ((results != null) && (results.Count() > 0) && (results.First() == "1")) + return true; + + return false; + } + + internal bool GetEC_AD_Users(string userID) { + DynamicParameters parameters = new(); + parameters.Add("@UserID", userID); + + var results = db.Query( + "SELECT UserID FROM EC_AD_Users WHERE UserID = @UserID", + parameters, commandType: CommandType.Text); + if ((results != null) && (results.Count() > 0)) + return true; + + return false; + } + + internal void ProcessOoO() { + DynamicParameters parameters = new(); + db.Execute("ProcesOOOEnableStatus", commandType: CommandType.StoredProcedure); + } + + internal void ExpireOoO() { + DynamicParameters parameters = new(); + db.Execute("ProcesOOOExpiration", commandType: CommandType.StoredProcedure); + } +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/WorkflowDMO.cs b/Fab2ApprovalSystem/DMO/WorkflowDMO.cs index 9b8cb18..be2877b 100644 --- a/Fab2ApprovalSystem/DMO/WorkflowDMO.cs +++ b/Fab2ApprovalSystem/DMO/WorkflowDMO.cs @@ -1,1015 +1,805 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; -using System.Web; -using Fab2ApprovalSystem.Models; + using Dapper; -using System.Transactions; -using Fab2ApprovalSystem.ViewModels; -using System.Reflection; + using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; +namespace Fab2ApprovalSystem.DMO; -namespace Fab2ApprovalSystem.DMO -{ - public class WorkflowDMO - { - private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); +public class WorkflowDMO { + private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); - //delegate TResult MathFunction(T1 var1, T2 var2); + //delegate TResult MathFunction(T1 var1, T2 var2); - //static void PrintResult(MathFunction mathFunction, T1 var1, T2 var2) - //{ - // TResult result = mathFunction(var1, var2); - // Console.WriteLine(String.Format("Result is {0}", result)); - //} + //static void PrintResult(MathFunction mathFunction, T1 var1, T2 var2) + //{ + // TResult result = mathFunction(var1, var2); + // Console.WriteLine(String.Format("Result is {0}", result)); + //} - //PrintResult((x, y) => x / y, 2, 8); - //GenericDelegateNumber e = new GenericDelegateNumber(AddInt); + //PrintResult((x, y) => x / y, 2, 8); + //GenericDelegateNumber e = new GenericDelegateNumber(AddInt); - /// - /// - /// - /// - /// - /// - public string GetSubRoleItems(int issueID, int docType) - { + public string GetSubRoleItems(int issueID, int docType) { + List subRoleItems = new(); + StringBuilder sqlString = new(); + string resultInClause = ""; - List subRoleItems = new List(); - StringBuilder sqlString = new StringBuilder(); - string resultInClause = ""; - - // LOTDISPSITION - if (GlobalVars.DocumentType.LotDisposition == (GlobalVars.DocumentType)docType) - { - resultInClause = GetLotDispositionSubRoleItems(issueID); - } - // MRB - else if (GlobalVars.DocumentType.MRB == (GlobalVars.DocumentType)docType) - { - subRoleItems.Add("'MRBApprover'"); // TODO remove Hard coding - resultInClause = "(" + String.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; - } - else if (GlobalVars.DocumentType.MRB == (GlobalVars.DocumentType)docType) - { - subRoleItems.Add("'QA_Admin'"); // TODO remove Hard coding - resultInClause = "(" + String.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; - } - else if (GlobalVars.DocumentType.ECN == (GlobalVars.DocumentType)docType || GlobalVars.DocumentType.TECNCancelledExpired == (GlobalVars.DocumentType)docType) - { - // TODO remove Hard coding - resultInClause = GetECNSubRoleItems(issueID, docType); - } - else if (GlobalVars.DocumentType.EECN == (GlobalVars.DocumentType)docType) - { - - resultInClause = GetECNSubRoleItems(issueID, docType); - } - - else if (GlobalVars.DocumentType.LotTraveler == (GlobalVars.DocumentType)docType) - { - resultInClause = GetLotTravelerSubRoleItems(issueID); - } - else if (GlobalVars.DocumentType.CorrectiveAction == (GlobalVars.DocumentType)docType) - { - resultInClause = GetCorrectiveActionSubRoleItems(issueID); - } - else if (GlobalVars.DocumentType.CorrectiveActionSection == (GlobalVars.DocumentType)docType) - { - resultInClause = GetCorrectiveActionSectionSubRoleItems(issueID); - } - else if (GlobalVars.DocumentType.PartsRequest == (GlobalVars.DocumentType)docType) - { - resultInClause = GetSubRolesForPartsRequestNextStep(issueID); - } - - return resultInClause; + // LOTDISPSITION + if (GlobalVars.DocumentType.LotDisposition == (GlobalVars.DocumentType)docType) { + resultInClause = GetLotDispositionSubRoleItems(issueID); + } + // MRB + else if (GlobalVars.DocumentType.MRB == (GlobalVars.DocumentType)docType) { + subRoleItems.Add("'MRBApprover'"); // TODO remove Hard coding + resultInClause = "(" + string.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; + } else if (GlobalVars.DocumentType.MRB == (GlobalVars.DocumentType)docType) { + subRoleItems.Add("'QA_Admin'"); // TODO remove Hard coding + resultInClause = "(" + string.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; + } else if (GlobalVars.DocumentType.ECN == (GlobalVars.DocumentType)docType || GlobalVars.DocumentType.TECNCancelledExpired == (GlobalVars.DocumentType)docType) { + // TODO remove Hard coding + resultInClause = GetECNSubRoleItems(issueID, docType); + } else if (GlobalVars.DocumentType.EECN == (GlobalVars.DocumentType)docType) { + resultInClause = GetECNSubRoleItems(issueID, docType); + } else if (GlobalVars.DocumentType.LotTraveler == (GlobalVars.DocumentType)docType) { + resultInClause = GetLotTravelerSubRoleItems(issueID); + } else if (GlobalVars.DocumentType.CorrectiveAction == (GlobalVars.DocumentType)docType) { + resultInClause = GetCorrectiveActionSubRoleItems(issueID); + } else if (GlobalVars.DocumentType.CorrectiveActionSection == (GlobalVars.DocumentType)docType) { + resultInClause = GetCorrectiveActionSectionSubRoleItems(issueID); + } else if (GlobalVars.DocumentType.PartsRequest == (GlobalVars.DocumentType)docType) { + resultInClause = GetSubRolesForPartsRequestNextStep(issueID); } - /// - /// - /// - /// - /// - string GetCorrectiveActionSubRoleItems(int caNo) - { - List subRoleItems = new List(); - StringBuilder sqlString = new StringBuilder(); - subRoleItems.Add("'Integration'"); + return resultInClause; + } - string resultInClause = "(" + String.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; - return resultInClause; - } - string GetCorrectiveActionSectionSubRoleItems(int caNo) - { - List subRoleItems = new List(); - StringBuilder sqlString = new StringBuilder(); - subRoleItems.Add("'8DQA'"); + private string GetCorrectiveActionSubRoleItems(int caNo) { + List subRoleItems = new(); + StringBuilder sqlString = new(); + subRoleItems.Add("'Integration'"); - string resultInClause = "(" + String.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; - return resultInClause; - } + string resultInClause = "(" + string.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; + return resultInClause; + } - /// - /// Get the Lot Disposition Document WorkFlow Sub Roles - /// - /// - /// - string GetLotDispositionSubRoleItems(int issueID) - { - List subRoleItems = new List(); - int recordCount = 0; - StringBuilder sqlString = new StringBuilder(); + private string GetCorrectiveActionSectionSubRoleItems(int caNo) { + List subRoleItems = new(); + StringBuilder sqlString = new(); + subRoleItems.Add("'8DQA'"); - // Check if "Disposition by OCAP" is checked - sqlString.Append("SELECT COUNT(*) FROM LotDisposition WHERE (DispositionByOCAP = 1) AND IssueID = @IssueID "); - recordCount = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).Single(); + string resultInClause = "(" + string.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; + return resultInClause; + } - if (recordCount > 0) - { - // if "Disposition by OCAP" is checked only the get roles for the "Execution" level only + /// + /// Get the Lot Disposition Document WorkFlow Sub Roles + /// - // For Step 3 - // Get the Location Role - sqlString = new StringBuilder(); - sqlString.Append("SELECT Location FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE LD.IssueID = @IssueID "); - var dataRows = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); - string tempLocation = ""; - foreach (var dataRow in dataRows) - { - tempLocation = dataRow.Location.ToString(); - if (tempLocation == "QDB" || tempLocation == "EDB") - subRoleItems.Add("'" + tempLocation + "'"); - else if (tempLocation == "6300" || tempLocation == "6400" || tempLocation == "6600") - subRoleItems.Add("'Probe'"); - else - subRoleItems.Add("'Fab'"); - } + private string GetLotDispositionSubRoleItems(int issueID) { + List subRoleItems = new(); + int recordCount = 0; + StringBuilder sqlString = new(); - } - else - { - // NOT "Disposition by OCAP" + // Check if "Disposition by OCAP" is checked + sqlString.Append("SELECT COUNT(*) FROM LotDisposition WHERE (DispositionByOCAP = 1) AND IssueID = @IssueID "); + recordCount = db.Query(sqlString.ToString(), new { IssueID = issueID }).Single(); - // For Step 1 - // Get the "Issue" - sqlString = new StringBuilder(); - sqlString.Append("SELECT Issue FROM LotDisposition LD INNER JOIN ResponsibilityIssue R ON LD.ResponsibilityIssueID = R.ResponsibilityIssueID WHERE LD.IssueID = @IssueID "); - var dataRows = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.Issue.ToString() + "'"); - } + if (recordCount > 0) { + // if "Disposition by OCAP" is checked only the get roles for the "Execution" level only - #region YE Role - - // ==================================================================YE ROLE=============================================================================================== - // For Step 1 - - // check if there any IG Medical products - sqlString = new StringBuilder(); - sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE LD.IssueID = @IssueID AND (L.Description LIKE 'IG,%' AND L.Description LIKE '%MA,%')"); - int recordCountForIG_MA = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).Single(); - - // Get list of the YE "Product-Generation" - sqlString = new StringBuilder(); - sqlString.Append("SELECT DISTINCT SubRoleCategoryItem, LTRIM(RTRIM(L.ProductFamily)) + '-' + ISNULL(LTRIM(RTRIM(CONVERT(varchar(10), L.Gen))), 'NULL') AS LotFamilyGen, "); - sqlString.Append("CASE WHEN L.LotStatusOptionID = 2 OR (ISNULL(S.ScrapCount, 0) > 0 AND ISNULL(S.ReleaseCount, 0) = 0) THEN 1 ELSE 0 END AS LotIsFullyScrapped, "); - sqlString.Append("L.Location "); - sqlString.Append("FROM Lot L "); - sqlString.Append("LEFT OUTER JOIN vFamilyGenYESubRole ON FamilyGen = LTRIM(RTRIM(L.ProductFamily)) + @FamilySuffix + '-' + LTRIM(RTRIM(CONVERT(varchar(10), L.Gen))) "); - sqlString.Append("LEFT OUTER JOIN ScrapLot S on S.LotNo = L.LotNumber AND S.IssueID = L.IssueID "); - sqlString.Append("WHERE L.IssueID = @IssueID "); - - dataRows = this.db.Query(sqlString.ToString(), new { IssueID = issueID, FamilySuffix = (recordCountForIG_MA > 0 ? "_MA" : "") }).ToList(); - foreach (var dataRow in dataRows) - { - if (dataRow.LotIsFullyScrapped == 1) - { // if lot is fully scrapped - int location = 0; - if (!Int32.TryParse(dataRow.Location, out location)) - location = 9999; - if (location < 6300) // only add YE if location is >= 6300 - continue; - } - if (dataRow.SubRoleCategoryItem == null) - throw new Exception("Missing YE for family/gen: " + dataRow.LotFamilyGen); - - subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - } - - #endregion - - #region PE Role - - // ==================================================================PE ROLE=============================================================================================== - // For Step 1 - - // check if all wafers with in the lots for the Dispo are "SCRAP" - sqlString = new StringBuilder(); - sqlString.Append("SELECT COUNT(*) FROM [ScrapLot] S "); - sqlString.Append("INNER JOIN Lot L ON S.LotNo = L.LotNumber "); - sqlString.Append("WHERE L.IssueID = @IssueID AND (L.LotStatusOptionID <> 2 OR S.ReleaseCount > 0)"); - bool allLotsAreScrap = (this.db.Query(sqlString.ToString(), new { IssueID = issueID }).Single() == 0); - - // If PE Required OR MRB Required (Could be combined with the MA OR RH rule) - // But not if all lots are scrap - sqlString = new StringBuilder(); - sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID "); - sqlString.Append("WHERE (PERequired = 1 OR Location = 'QDB' OR Location = 'EDB' ) AND LD.IssueID = @IssueID "); - recordCount = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).Single(); - if ((recordCount > 0) && (allLotsAreScrap == false)) - { - // check if there any IG Medical products - if (recordCountForIG_MA > 0) - { - sqlString = new StringBuilder(); - sqlString.Append("SELECT 'PE_' + LTRIM(RTRIM(L.ProductFamily)) + '_MA-' + LTRIM(RTRIM(CONVERT(NCHAR(10),L.Gen))) AS ProdGen "); - sqlString.Append("FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE LD.IssueID = @IssueID "); - dataRows = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.ProdGen.ToString() + "'"); - } - } - else - { - // Get list of the PE "Product-Generation" - sqlString = new StringBuilder(); - sqlString.Append("SELECT 'PE_' + LTRIM(RTRIM(L.ProductFamily)) + '-' + LTRIM(RTRIM(CONVERT(NCHAR(10),L.Gen))) AS ProdGen "); - sqlString.Append("FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE LD.IssueID = @IssueID "); - dataRows = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.ProdGen.ToString() + "'"); - } - } - } - - - #endregion - - // For Step 1 and Step 2 - // check to see if the Lot has any M_Suffix - sqlString = new StringBuilder(); - sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE (L.LotStatusOptionID = 4) AND LD.IssueID = @IssueID "); - recordCount = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).Single(); - if (recordCount > 0) - { - subRoleItems.Add("'M_Suffix'"); - } - - // get wafer scrap counts - - sqlString = new StringBuilder(); - sqlString.Append("SELECT ISNULL(SUM(ScrapCount), 0) AS ScrapCount FROM Lot L "); - sqlString.Append("INNER JOIN ScrapLot S ON S.IssueID = L.IssueID AND S.LotNo = L.LotNumber "); - sqlString.Append("WHERE L.IssueID = @IssueID AND L.Location < '6300'"); - int scrapCountLocationBelow6300 = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).SingleOrDefault(); - - if (scrapCountLocationBelow6300 > 10) - { - // For Step 2 - if (!subRoleItems.Contains("'Engineering'")) - subRoleItems.Add("'Engineering'"); - } - - sqlString = new StringBuilder(); - sqlString.Append("SELECT ISNULL(SUM(ScrapCount), 0) AS ScrapCount FROM Lot L "); - sqlString.Append("INNER JOIN ScrapLot S ON S.IssueID = L.IssueID AND S.LotNo = L.LotNumber "); - sqlString.Append("WHERE L.IssueID = @IssueID AND L.Location >= '6300'"); - int scrapCountLocation6300AndGreater = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).SingleOrDefault(); - - if (scrapCountLocation6300AndGreater > 10) - { - // For Step 2 - if (!subRoleItems.Contains("'Integration / YE'")) - subRoleItems.Add("'Integration / YE'"); - } - - /* ===== Remove the code for Director Approval Loop - Changed per Dixie's request 08/06/2018 - */ - - //If Location = "QDB" OR PRRequired or MRB Required OR(Product = MA / RH AND Location = Probe) Get "Director" Role for all departments, except "Facilities" - - sqlString = new StringBuilder(); - //sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID "); - //sqlString.Append("WHERE ( ((L.ProductFamily = 'RH' OR L.ProductFamily = 'MA') "); - //sqlString.Append("AND (Location = '6300' OR Location = '6400' OR Location = '6600')) "); - //sqlString.Append("OR Location = 'QDB' OR Location = 'EDB' OR LD.PERequired = 1 OR LD.MRBRequired = 1) AND LD.IssueID = @IssueID "); - - // 09/01/2020 - - // Per Hans, do not include directors if PE required is checked - //sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID "); - //sqlString.Append("WHERE (LD.PERequired = 1 OR Location = 'QDB' OR Location = 'EDB' ) "); - //sqlString.Append("AND LD.IssueID = @IssueID "); - - // 09/01/2020 - // Per Hans, do not include directors if PE required is checked - sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID "); - sqlString.Append("WHERE (Location = 'QDB' OR Location = 'EDB' ) "); - sqlString.Append("AND LD.IssueID = @IssueID "); - - - recordCount = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).Single(); - if (recordCount > 0) - { - // For Step 2 - // get all the departments, except the 'Facilities' and 'Die bank' dept - sqlString = new StringBuilder(); - sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'Department' AND SubRoleCategoryItem <> 'Facilities' AND SubRoleCategoryItem <> 'Die Bank' "); - dataRows = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - } - } - - - - // For Step 3 - // Get the Location Role - sqlString = new StringBuilder(); - sqlString.Append("SELECT Location FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE LD.IssueID = @IssueID "); - dataRows = this.db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); - string tempLocation = ""; - foreach (var dataRow in dataRows) - { - tempLocation = dataRow.Location.ToString(); - if (tempLocation.ToUpper() == "QDB" || tempLocation.ToUpper() == "EDB") - subRoleItems.Add("'" + tempLocation + "'"); - else if (tempLocation == "6300" || tempLocation == "6400" || tempLocation == "6600") - subRoleItems.Add("'Probe'"); - else - subRoleItems.Add("'Fab'"); - } + // For Step 3 + // Get the Location Role + sqlString = new StringBuilder(); + sqlString.Append("SELECT Location FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE LD.IssueID = @IssueID "); + List dataRows = db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); + string tempLocation = ""; + foreach (var dataRow in dataRows) { + tempLocation = dataRow.Location.ToString(); + if (tempLocation == "QDB" || tempLocation == "EDB") + subRoleItems.Add("'" + tempLocation + "'"); + else if (tempLocation == "6300" || tempLocation == "6400" || tempLocation == "6600") + subRoleItems.Add("'Probe'"); + else + subRoleItems.Add("'Fab'"); } - string resultInClause = "(" + String.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; - return resultInClause; + } else { + // NOT "Disposition by OCAP" - } - - /// - /// - /// - /// - /// - /// - string GetECNSubRoleItems(int ecnNumber, int documentType) - { - StringBuilder qryString = new StringBuilder(); - List subRoleItems = new List(); - - int recordCount = 0; - // EMERGENCY TECNS ============================================================================================== - if (GlobalVars.DocumentType.EECN == (GlobalVars.DocumentType)documentType) - { - //subRoleItems.Add("'QA Pre Approver'"); - qryString.Clear(); - qryString.Append("SELECT DISTINCT SRC.SubRoleCategoryItem FROM DocumentType D "); - qryString.Append("INNER JOIN Workflows W ON D.DocumentTypeID = W.DocumentTypeID "); - qryString.Append("INNER JOIN WorkFlowSteps WS ON W.WorkflowID = WS.WorkflowID "); - qryString.Append("INNER JOIN Role R ON WS.RoleID = R.RoleID "); - qryString.Append("INNER JOIN SubRole SR ON R.RoleID = SR.RoleID "); - qryString.Append("INNER JOIN SubRoleCategory SRC ON SR.SubRoleCategoryID = SRC.SubRoleCategoryID "); - qryString.Append("WHERE D.DocumentTypeID = @DocumentType"); - //qryString.Append("WHERE D.DocumentTypeID = 3"); - //subRoleItems.Add("'QA_Admin'"); - var dataRows = this.db.Query(qryString.ToString(), new { DocumentType = documentType }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - } - //subRoleItems.Add("'QA Final Approver'"); - } //=============================================================================================================== - else - { - subRoleItems.Add("'QA Pre Approver'"); - // get the affected Department: Removed by JRO per Jeanne - //qryString.Clear(); - //qryString.Append("SELECT ModuleName FROM ECNModule E INNER JOIN ECNAffectedModule AM ON E.ModuleID = AM.ModuleID WHERE AM.ECNNumber= @ECNNumber"); - //var dataRows = this.db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).ToList(); - //foreach (var dataRow in dataRows) - //{ - // subRoleItems.Add("'" + dataRow.ModuleName.ToString() + "'"); - //} - // get the approvers - qryString.Clear(); - qryString.Append("SELECT SubRoleCategoryItem FROM SubRoleCategory S INNER JOIN ECNAffectedDepartment AD ON S.SubRoleCategoryID = AD.DepartmentID WHERE AD.ECNNumber= @ECNNumber"); - var dataRows = this.db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - } - - // Add Directors if # of Lots Affected is > 10 - - qryString.Clear(); - // Impact / Change Sub Roles ======================================================================================================================= - - // Get the "Environment" Impact SubRole - qryString.Clear(); - qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND ImpactOnEnvironment = 2 "); - recordCount = this.db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); - if (recordCount > 0) - { - subRoleItems.Add("'Environment'"); - //qryString.Clear(); - //qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategoryItem = 'Environment' "); - //dataRows = this.db.Query(qryString.ToString()).ToList(); - //foreach (var dataRow in dataRows) - //{ - // subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - //} - } - - - // Get the "Capacity" Impact SubRole - qryString.Clear(); - qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (ImpactOnCapacity = 1 )"); - recordCount = this.db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); - if (recordCount > 0) - { - subRoleItems.Add("'Capacity'"); - //qryString.Clear(); - //qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategoryItem = 'Capacity' "); - //dataRows = this.db.Query(qryString.ToString()).ToList(); - //foreach (var dataRow in dataRows) - //{ - // subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - //} - } - - // Get the "MaterialConsumptionChangeRequired" Impact SubRole - qryString.Clear(); - qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (MaterialConsumptionChangeRequired = 1 )"); - recordCount = this.db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); - if (recordCount > 0) - { - subRoleItems.Add("'MaterialConsumption'"); - //qryString.Clear(); - //qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategoryItem = 'MaterialConsumption' "); - //dataRows = this.db.Query(qryString.ToString()).ToList(); - //foreach (var dataRow in dataRows) - //{ - // subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - //} - } - - // Get the "NewPartFlow" Impact SubRole - qryString.Clear(); - qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (NewPartFlowRequired = 1 )"); - recordCount = this.db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); - if (recordCount > 0) - { - subRoleItems.Add("'NewPartFlow'"); - subRoleItems.Add("'SPN-Execution'"); - //subRoleItems.Add("'TestProgram'"); - subRoleItems.Add("'Metrology Change'"); - subRoleItems.Add("'SPC'"); - //qryString.Clear(); - //qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategoryItem = 'NewPartFlow' "); - //dataRows = this.db.Query(qryString.ToString()).ToList(); - //foreach (var dataRow in dataRows) - //{ - // subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - //} - } - - - - subRoleItems.Add("'Document Control Admin'"); - subRoleItems.Add("'Training Notification'"); - //======================================================================================================================= - - // Execution level======================================================================================================== - // Get the "SPN" SubRole - qryString.Clear(); - qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (SPNChangeRequired = 1) "); - recordCount = this.db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); - if (recordCount > 0) - { - //subRoleItems.Add("'SPN-Execution'"); - - //qryString.Clear(); - //qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategoryItem = 'SPN' "); - //dataRows = this.db.Query(qryString.ToString()).ToList(); - //foreach (var dataRow in dataRows) - //{ - // subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - //} - } - - // Get the "Metrology Change" SubRole - qryString.Clear(); - qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (MetrologyChangeRequired = 1) "); - recordCount = this.db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); - if (recordCount > 0) - { - subRoleItems.Add("'Metrology Change'"); - } - - - - // Get the "SPCChange" SubRole - qryString.Clear(); - qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (SPCChangeRequired = 1) "); - recordCount = this.db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); - if (recordCount > 0) - { - subRoleItems.Add("'SPC'"); - } - - // Get the "FIChange" SubRole - qryString.Clear(); - qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (FIChangeRequired = 1) "); - recordCount = this.db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); - if (recordCount > 0) - { - subRoleItems.Add("'FI-Execution'"); - } + // For Step 1 + // Get the "Issue" + sqlString = new StringBuilder(); + sqlString.Append("SELECT Issue FROM LotDisposition LD INNER JOIN ResponsibilityIssue R ON LD.ResponsibilityIssueID = R.ResponsibilityIssueID WHERE LD.IssueID = @IssueID "); + List dataRows = db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.Issue.ToString() + "'"); } - string resultInClause = "(" + String.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; - return resultInClause; - } + #region YE Role - /// - /// - /// - /// - /// - string GetLotTravelerSubRoleItems(int workRequestID) - { - List subRoleItems = new List(); - StringBuilder qryString = new StringBuilder(); - - // get the affected Modules - qryString.Clear(); - qryString.Append("SELECT ModuleName FROM Module M INNER JOIN LTAffectedModule AM ON M.ModuleID = AM.ModuleID WHERE AM.LTWorkRequestID = @WorkRequestID"); - var dataRows = this.db.Query(qryString.ToString(), new { WorkRequestID = workRequestID }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.ModuleName.ToString() + "'"); - } + // ==================================================================YE ROLE=============================================================================================== + // For Step 1 + // check if there any IG Medical products + sqlString = new StringBuilder(); + sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE LD.IssueID = @IssueID AND (L.Description LIKE 'IG,%' AND L.Description LIKE '%MA,%')"); + int recordCountForIG_MA = db.Query(sqlString.ToString(), new { IssueID = issueID }).Single(); + + // Get list of the YE "Product-Generation" + sqlString = new StringBuilder(); + sqlString.Append("SELECT DISTINCT SubRoleCategoryItem, LTRIM(RTRIM(L.ProductFamily)) + '-' + ISNULL(LTRIM(RTRIM(CONVERT(varchar(10), L.Gen))), 'NULL') AS LotFamilyGen, "); + sqlString.Append("CASE WHEN L.LotStatusOptionID = 2 OR (ISNULL(S.ScrapCount, 0) > 0 AND ISNULL(S.ReleaseCount, 0) = 0) THEN 1 ELSE 0 END AS LotIsFullyScrapped, "); + sqlString.Append("L.Location "); + sqlString.Append("FROM Lot L "); + sqlString.Append("LEFT OUTER JOIN vFamilyGenYESubRole ON FamilyGen = LTRIM(RTRIM(L.ProductFamily)) + @FamilySuffix + '-' + LTRIM(RTRIM(CONVERT(varchar(10), L.Gen))) "); + sqlString.Append("LEFT OUTER JOIN ScrapLot S on S.LotNo = L.LotNumber AND S.IssueID = L.IssueID "); + sqlString.Append("WHERE L.IssueID = @IssueID "); + + dataRows = db.Query(sqlString.ToString(), new { IssueID = issueID, FamilySuffix = (recordCountForIG_MA > 0 ? "_MA" : "") }).ToList(); + foreach (var dataRow in dataRows) { + if (dataRow.LotIsFullyScrapped == 1) { // if lot is fully scrapped + int location = 0; + if (!int.TryParse(dataRow.Location, out location)) + location = 9999; + if (location < 6300) // only add YE if location is >= 6300 + continue; + } + if (dataRow.SubRoleCategoryItem == null) + throw new Exception("Missing YE for family/gen: " + dataRow.LotFamilyGen); - - // get the affected Department - qryString.Clear(); - qryString.Append("SELECT SubRoleCategoryItem FROM SubRoleCategory S INNER JOIN LTAffectedDepartment AD ON S.SubRoleCategoryID = AD.DepartmentID WHERE AD.LTWorkRequestID= @WorkRequestID"); - dataRows = this.db.Query(qryString.ToString(), new { WorkRequestID = workRequestID }).ToList(); - foreach (var dataRow in dataRows) - { subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); } - qryString.Clear(); - qryString.Append("SELECT * FROM LTWorkRequest WHERE ID = @WorkRequestID"); - dataRows = this.db.Query(qryString.ToString(), new { WorkRequestID = workRequestID }).ToList(); - var engLotStartReq = -1; - var lotTypeConversion = -1; - foreach (dynamic dataRow in dataRows) - { - engLotStartReq = dataRow.EngLotStartRequired; - lotTypeConversion = dataRow.LotTypeConversion; + #endregion + + #region PE Role + + // ==================================================================PE ROLE=============================================================================================== + // For Step 1 + + // check if all wafers with in the lots for the Dispo are "SCRAP" + sqlString = new StringBuilder(); + sqlString.Append("SELECT COUNT(*) FROM [ScrapLot] S "); + sqlString.Append("INNER JOIN Lot L ON S.LotNo = L.LotNumber "); + sqlString.Append("WHERE L.IssueID = @IssueID AND (L.LotStatusOptionID <> 2 OR S.ReleaseCount > 0)"); + bool allLotsAreScrap = (db.Query(sqlString.ToString(), new { IssueID = issueID }).Single() == 0); + + // If PE Required OR MRB Required (Could be combined with the MA OR RH rule) + // But not if all lots are scrap + sqlString = new StringBuilder(); + sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID "); + sqlString.Append("WHERE (PERequired = 1 OR Location = 'QDB' OR Location = 'EDB' ) AND LD.IssueID = @IssueID "); + recordCount = db.Query(sqlString.ToString(), new { IssueID = issueID }).Single(); + if ((recordCount > 0) && (allLotsAreScrap == false)) { + // check if there any IG Medical products + if (recordCountForIG_MA > 0) { + sqlString = new StringBuilder(); + sqlString.Append("SELECT 'PE_' + LTRIM(RTRIM(L.ProductFamily)) + '_MA-' + LTRIM(RTRIM(CONVERT(NCHAR(10),L.Gen))) AS ProdGen "); + sqlString.Append("FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE LD.IssueID = @IssueID "); + dataRows = db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.ProdGen.ToString() + "'"); + } + } else { + // Get list of the PE "Product-Generation" + sqlString = new StringBuilder(); + sqlString.Append("SELECT 'PE_' + LTRIM(RTRIM(L.ProductFamily)) + '-' + LTRIM(RTRIM(CONVERT(NCHAR(10),L.Gen))) AS ProdGen "); + sqlString.Append("FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE LD.IssueID = @IssueID "); + dataRows = db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.ProdGen.ToString() + "'"); + } + } } - if (engLotStartReq == 1 ) - { - if (!subRoleItems.Contains("Operations")) // need to remove the hard coding - { - subRoleItems.Add("'Operations'"); - } - if (!subRoleItems.Contains("Engineering")) // need to remove the hard coding - { + #endregion + + // For Step 1 and Step 2 + // check to see if the Lot has any M_Suffix + sqlString = new StringBuilder(); + sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE (L.LotStatusOptionID = 4) AND LD.IssueID = @IssueID "); + recordCount = db.Query(sqlString.ToString(), new { IssueID = issueID }).Single(); + if (recordCount > 0) { + subRoleItems.Add("'M_Suffix'"); + } + + // get wafer scrap counts + + sqlString = new StringBuilder(); + sqlString.Append("SELECT ISNULL(SUM(ScrapCount), 0) AS ScrapCount FROM Lot L "); + sqlString.Append("INNER JOIN ScrapLot S ON S.IssueID = L.IssueID AND S.LotNo = L.LotNumber "); + sqlString.Append("WHERE L.IssueID = @IssueID AND L.Location < '6300'"); + int scrapCountLocationBelow6300 = db.Query(sqlString.ToString(), new { IssueID = issueID }).SingleOrDefault(); + + if (scrapCountLocationBelow6300 > 10) { + // For Step 2 + if (!subRoleItems.Contains("'Engineering'")) subRoleItems.Add("'Engineering'"); - } + } - if (!subRoleItems.Contains("Integration / YE")) // need to remove the hard coding - { + sqlString = new StringBuilder(); + sqlString.Append("SELECT ISNULL(SUM(ScrapCount), 0) AS ScrapCount FROM Lot L "); + sqlString.Append("INNER JOIN ScrapLot S ON S.IssueID = L.IssueID AND S.LotNo = L.LotNumber "); + sqlString.Append("WHERE L.IssueID = @IssueID AND L.Location >= '6300'"); + int scrapCountLocation6300AndGreater = db.Query(sqlString.ToString(), new { IssueID = issueID }).SingleOrDefault(); + + if (scrapCountLocation6300AndGreater > 10) { + // For Step 2 + if (!subRoleItems.Contains("'Integration / YE'")) subRoleItems.Add("'Integration / YE'"); - } - - } - if (lotTypeConversion == 1) - { - if (!subRoleItems.Contains("Operations")) // need to remove the hard coding - { - subRoleItems.Add("'Operations'"); - } } - if (engLotStartReq == 1 || lotTypeConversion == 1) - { - // END OF DEpartments= =========================================================== - qryString.Clear(); + /* ===== Remove the code for Director Approval Loop - Changed per Dixie's request 08/06/2018 + */ - qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'FabPlanner' "); - dataRows = this.db.Query(qryString.ToString(), new { WorkRequestID = workRequestID }).ToList(); - foreach (var dataRow in dataRows) - { + //If Location = "QDB" OR PRRequired or MRB Required OR(Product = MA / RH AND Location = Probe) Get "Director" Role for all departments, except "Facilities" + + sqlString = new StringBuilder(); + //sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID "); + //sqlString.Append("WHERE ( ((L.ProductFamily = 'RH' OR L.ProductFamily = 'MA') "); + //sqlString.Append("AND (Location = '6300' OR Location = '6400' OR Location = '6600')) "); + //sqlString.Append("OR Location = 'QDB' OR Location = 'EDB' OR LD.PERequired = 1 OR LD.MRBRequired = 1) AND LD.IssueID = @IssueID "); + + // 09/01/2020 - + // Per Hans, do not include directors if PE required is checked + //sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID "); + //sqlString.Append("WHERE (LD.PERequired = 1 OR Location = 'QDB' OR Location = 'EDB' ) "); + //sqlString.Append("AND LD.IssueID = @IssueID "); + + // 09/01/2020 + // Per Hans, do not include directors if PE required is checked + sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID "); + sqlString.Append("WHERE (Location = 'QDB' OR Location = 'EDB' ) "); + sqlString.Append("AND LD.IssueID = @IssueID "); + + recordCount = db.Query(sqlString.ToString(), new { IssueID = issueID }).Single(); + if (recordCount > 0) { + // For Step 2 + // get all the departments, except the 'Facilities' and 'Die bank' dept + sqlString = new StringBuilder(); + sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'Department' AND SubRoleCategoryItem <> 'Facilities' AND SubRoleCategoryItem <> 'Die Bank' "); + dataRows = db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); + foreach (var dataRow in dataRows) { subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); } } - - - - - string resultInClause = "(" + String.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; - return resultInClause; - - } - /// - /// Returns a boolean to indicate whethere it is was the last step in the approval - /// - /// - /// - public bool Approve(int issueID, byte step, string comments, out bool lastStep, int userID, int documentType, int workFlowNumber) - { - bool lastApproverInCurrentStep = false; - try - { - string subRolesInClause = GetSubRoleItems(issueID, documentType); - - lastStep = false; - - - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID); - parameters.Add("@CurrentStep", step); - parameters.Add("@ItemStatus", (int)GlobalVars.ApprovalOption.Approved); - parameters.Add("@UserID", userID); - parameters.Add("@Comments", comments); - parameters.Add("@SubRoleCategoriesClause", subRolesInClause); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@LastStep", lastStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); - parameters.Add("@LastApproverInCurrentStep", lastApproverInCurrentStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); - parameters.Add("@WorkFlowNumber", workFlowNumber); - - this.db.Execute("UpdateApproval", parameters, commandType: CommandType.StoredProcedure); - - lastStep = parameters.Get("@LastStep"); - lastApproverInCurrentStep = parameters.Get("@LastApproverInCurrentStep"); + // For Step 3 + // Get the Location Role + sqlString = new StringBuilder(); + sqlString.Append("SELECT Location FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID WHERE LD.IssueID = @IssueID "); + dataRows = db.Query(sqlString.ToString(), new { IssueID = issueID }).ToList(); + string tempLocation = ""; + foreach (var dataRow in dataRows) { + tempLocation = dataRow.Location.ToString(); + if (tempLocation.ToUpper() == "QDB" || tempLocation.ToUpper() == "EDB") + subRoleItems.Add("'" + tempLocation + "'"); + else if (tempLocation == "6300" || tempLocation == "6400" || tempLocation == "6600") + subRoleItems.Add("'Probe'"); + else + subRoleItems.Add("'Fab'"); } - - catch (Exception e) - { - string detailedException = ""; - try - { - detailedException = e.InnerException.ToString(); - } - catch - { - detailedException = e.Message; - } - string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent("User ID:" + userID + "\r\n " + "ApproveDMO\r\n" + issueID.ToString() + "\r\n" + e.InnerException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = userID.ToString(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ApproveDMO - " + exceptionString }); - throw new Exception(e.Message); - } - - - return lastApproverInCurrentStep; - } + string resultInClause = "(" + string.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; + return resultInClause; + } - /// - /// - /// - /// - /// - /// - /// - /// - public bool Reject(int issueID, byte step, string comments, int userID, int docType) - { - bool lastStep = false; - bool lastApproverInCurrentStep = false; + private string GetECNSubRoleItems(int ecnNumber, int documentType) { + StringBuilder qryString = new(); + List subRoleItems = new(); - var parameters = new DynamicParameters(); + int recordCount = 0; + // EMERGENCY TECNS ============================================================================================== + if (GlobalVars.DocumentType.EECN == (GlobalVars.DocumentType)documentType) { + //subRoleItems.Add("'QA Pre Approver'"); + qryString.Clear(); + qryString.Append("SELECT DISTINCT SRC.SubRoleCategoryItem FROM DocumentType D "); + qryString.Append("INNER JOIN Workflows W ON D.DocumentTypeID = W.DocumentTypeID "); + qryString.Append("INNER JOIN WorkFlowSteps WS ON W.WorkflowID = WS.WorkflowID "); + qryString.Append("INNER JOIN Role R ON WS.RoleID = R.RoleID "); + qryString.Append("INNER JOIN SubRole SR ON R.RoleID = SR.RoleID "); + qryString.Append("INNER JOIN SubRoleCategory SRC ON SR.SubRoleCategoryID = SRC.SubRoleCategoryID "); + qryString.Append("WHERE D.DocumentTypeID = @DocumentType"); + //qryString.Append("WHERE D.DocumentTypeID = 3"); + //subRoleItems.Add("'QA_Admin'"); + List dataRows = db.Query(qryString.ToString(), new { DocumentType = documentType }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + } + //subRoleItems.Add("'QA Final Approver'"); + } //=============================================================================================================== + else { + subRoleItems.Add("'QA Pre Approver'"); + // get the affected Department: Removed by JRO per Jeanne + //qryString.Clear(); + //qryString.Append("SELECT ModuleName FROM ECNModule E INNER JOIN ECNAffectedModule AM ON E.ModuleID = AM.ModuleID WHERE AM.ECNNumber= @ECNNumber"); + //var dataRows = this.db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).ToList(); + //foreach (var dataRow in dataRows) + //{ + // subRoleItems.Add("'" + dataRow.ModuleName.ToString() + "'"); + //} + // get the approvers + qryString.Clear(); + qryString.Append("SELECT SubRoleCategoryItem FROM SubRoleCategory S INNER JOIN ECNAffectedDepartment AD ON S.SubRoleCategoryID = AD.DepartmentID WHERE AD.ECNNumber= @ECNNumber"); + List dataRows = db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + } + + // Add Directors if # of Lots Affected is > 10 + + qryString.Clear(); + // Impact / Change Sub Roles ======================================================================================================================= + + // Get the "Environment" Impact SubRole + qryString.Clear(); + qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND ImpactOnEnvironment = 2 "); + recordCount = db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); + if (recordCount > 0) { + subRoleItems.Add("'Environment'"); + //qryString.Clear(); + //qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategoryItem = 'Environment' "); + //dataRows = this.db.Query(qryString.ToString()).ToList(); + //foreach (var dataRow in dataRows) + //{ + // subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + //} + } + + // Get the "Capacity" Impact SubRole + qryString.Clear(); + qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (ImpactOnCapacity = 1 )"); + recordCount = db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); + if (recordCount > 0) { + subRoleItems.Add("'Capacity'"); + //qryString.Clear(); + //qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategoryItem = 'Capacity' "); + //dataRows = this.db.Query(qryString.ToString()).ToList(); + //foreach (var dataRow in dataRows) + //{ + // subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + //} + } + + // Get the "MaterialConsumptionChangeRequired" Impact SubRole + qryString.Clear(); + qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (MaterialConsumptionChangeRequired = 1 )"); + recordCount = db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); + if (recordCount > 0) { + subRoleItems.Add("'MaterialConsumption'"); + //qryString.Clear(); + //qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategoryItem = 'MaterialConsumption' "); + //dataRows = this.db.Query(qryString.ToString()).ToList(); + //foreach (var dataRow in dataRows) + //{ + // subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + //} + } + + // Get the "NewPartFlow" Impact SubRole + qryString.Clear(); + qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (NewPartFlowRequired = 1 )"); + recordCount = db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); + if (recordCount > 0) { + subRoleItems.Add("'NewPartFlow'"); + subRoleItems.Add("'SPN-Execution'"); + //subRoleItems.Add("'TestProgram'"); + subRoleItems.Add("'Metrology Change'"); + subRoleItems.Add("'SPC'"); + //qryString.Clear(); + //qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategoryItem = 'NewPartFlow' "); + //dataRows = this.db.Query(qryString.ToString()).ToList(); + //foreach (var dataRow in dataRows) + //{ + // subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + //} + } + + subRoleItems.Add("'Document Control Admin'"); + subRoleItems.Add("'Training Notification'"); + //======================================================================================================================= + + // Execution level======================================================================================================== + // Get the "SPN" SubRole + qryString.Clear(); + qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (SPNChangeRequired = 1) "); + recordCount = db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); + if (recordCount > 0) { + //subRoleItems.Add("'SPN-Execution'"); + + //qryString.Clear(); + //qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategoryItem = 'SPN' "); + //dataRows = this.db.Query(qryString.ToString()).ToList(); + //foreach (var dataRow in dataRows) + //{ + // subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + //} + } + + // Get the "Metrology Change" SubRole + qryString.Clear(); + qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (MetrologyChangeRequired = 1) "); + recordCount = db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); + if (recordCount > 0) { + subRoleItems.Add("'Metrology Change'"); + } + + // Get the "SPCChange" SubRole + qryString.Clear(); + qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (SPCChangeRequired = 1) "); + recordCount = db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); + if (recordCount > 0) { + subRoleItems.Add("'SPC'"); + } + + // Get the "FIChange" SubRole + qryString.Clear(); + qryString.Append("SELECT COUNT(*) FROM ECN WHERE ECNNumber= @ECNNumber AND (FIChangeRequired = 1) "); + recordCount = db.Query(qryString.ToString(), new { ECNNumber = ecnNumber }).Single(); + if (recordCount > 0) { + subRoleItems.Add("'FI-Execution'"); + } + } + + string resultInClause = "(" + string.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; + return resultInClause; + } + + private string GetLotTravelerSubRoleItems(int workRequestID) { + List subRoleItems = new(); + StringBuilder qryString = new(); + + // get the affected Modules + qryString.Clear(); + qryString.Append("SELECT ModuleName FROM Module M INNER JOIN LTAffectedModule AM ON M.ModuleID = AM.ModuleID WHERE AM.LTWorkRequestID = @WorkRequestID"); + List dataRows = db.Query(qryString.ToString(), new { WorkRequestID = workRequestID }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.ModuleName.ToString() + "'"); + } + + // get the affected Department + qryString.Clear(); + qryString.Append("SELECT SubRoleCategoryItem FROM SubRoleCategory S INNER JOIN LTAffectedDepartment AD ON S.SubRoleCategoryID = AD.DepartmentID WHERE AD.LTWorkRequestID= @WorkRequestID"); + dataRows = db.Query(qryString.ToString(), new { WorkRequestID = workRequestID }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + } + + qryString.Clear(); + qryString.Append("SELECT * FROM LTWorkRequest WHERE ID = @WorkRequestID"); + dataRows = db.Query(qryString.ToString(), new { WorkRequestID = workRequestID }).ToList(); + var engLotStartReq = -1; + var lotTypeConversion = -1; + foreach (dynamic dataRow in dataRows) { + engLotStartReq = dataRow.EngLotStartRequired; + lotTypeConversion = dataRow.LotTypeConversion; + } + + if (engLotStartReq == 1) { + if (!subRoleItems.Contains("Operations")) // need to remove the hard coding + { + subRoleItems.Add("'Operations'"); + } + if (!subRoleItems.Contains("Engineering")) // need to remove the hard coding + { + subRoleItems.Add("'Engineering'"); + } + + if (!subRoleItems.Contains("Integration / YE")) // need to remove the hard coding + { + subRoleItems.Add("'Integration / YE'"); + } + + } + if (lotTypeConversion == 1) { + if (!subRoleItems.Contains("Operations")) // need to remove the hard coding + { + subRoleItems.Add("'Operations'"); + } + } + + if (engLotStartReq == 1 || lotTypeConversion == 1) { + // END OF DEpartments= =========================================================== + qryString.Clear(); + + qryString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'FabPlanner' "); + dataRows = db.Query(qryString.ToString(), new { WorkRequestID = workRequestID }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + } + } + + string resultInClause = "(" + string.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; + return resultInClause; + } + /// + /// Returns a boolean to indicate whethere it is was the last step in the approval + /// + + public bool Approve(AppSettings appSettings, int issueID, byte step, string comments, out bool lastStep, int userID, int documentType, int workFlowNumber) { + bool lastApproverInCurrentStep = false; + try { + string subRolesInClause = GetSubRoleItems(issueID, documentType); + + lastStep = false; + + DynamicParameters parameters = new(); parameters.Add("@IssueID", issueID); parameters.Add("@CurrentStep", step); - parameters.Add("@ItemStatus", (int)GlobalVars.ApprovalOption.Denied); + parameters.Add("@ItemStatus", (int)GlobalVars.ApprovalOption.Approved); parameters.Add("@UserID", userID); parameters.Add("@Comments", comments); - parameters.Add("@DocumentTypeID", docType); - parameters.Add("@SubRoleCategoriesClause", string.Empty); + parameters.Add("@SubRoleCategoriesClause", subRolesInClause); + parameters.Add("@DocumentTypeID", documentType); parameters.Add("@LastStep", lastStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); parameters.Add("@LastApproverInCurrentStep", lastApproverInCurrentStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); + parameters.Add("@WorkFlowNumber", workFlowNumber); - - this.db.Execute("UpdateApproval", parameters, commandType: CommandType.StoredProcedure); + db.Execute("UpdateApproval", parameters, commandType: CommandType.StoredProcedure); lastStep = parameters.Get("@LastStep"); lastApproverInCurrentStep = parameters.Get("@LastApproverInCurrentStep"); - - return lastApproverInCurrentStep; - - - } - public bool Recall(int issueID, byte step, string comments, int userID, int docType) - { - bool lastStep = false; - bool lastApproverInCurrentStep = false; - - var parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID); - parameters.Add("@CurrentStep", step); - parameters.Add("@ItemStatus", (int)GlobalVars.ApprovalOption.Recalled); - parameters.Add("@UserID", userID); - parameters.Add("@Comments", comments); - parameters.Add("@DocumentTypeID", docType); - parameters.Add("@SubRoleCategoriesClause", string.Empty); - parameters.Add("@LastStep", lastStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); - parameters.Add("@LastApproverInCurrentStep", lastApproverInCurrentStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); - - - this.db.Execute("UpdateApproval", parameters, commandType: CommandType.StoredProcedure); - - lastStep = parameters.Get("@LastStep"); - lastApproverInCurrentStep = parameters.Get("@LastApproverInCurrentStep"); - - return lastApproverInCurrentStep; - - + } catch (Exception e) { + string detailedException = ""; + try { + detailedException = e.InnerException.ToString(); + } catch { + detailedException = e.Message; + } + string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); + Functions.WriteEvent(appSettings, "User ID:" + userID + "\r\n " + "ApproveDMO\r\n" + issueID.ToString() + "\r\n" + e.InnerException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = userID.ToString(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ApproveDMO - " + exceptionString }); + throw new Exception(e.Message); } + return lastApproverInCurrentStep; + } - /// - /// - /// - /// - /// - /// - /// - /// - /// - public void RejectTECNExtension(int ecnNumber, byte step, string comments, int userID, int docType) - { + public bool Reject(int issueID, byte step, string comments, int userID, int docType) { + bool lastStep = false; + bool lastApproverInCurrentStep = false; - var parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - parameters.Add("@CurrentStep", step); - parameters.Add("@UserID", userID); - parameters.Add("@DocumentTypeID", docType); + DynamicParameters parameters = new(); + parameters.Add("@IssueID", issueID); + parameters.Add("@CurrentStep", step); + parameters.Add("@ItemStatus", (int)GlobalVars.ApprovalOption.Denied); + parameters.Add("@UserID", userID); + parameters.Add("@Comments", comments); + parameters.Add("@DocumentTypeID", docType); + parameters.Add("@SubRoleCategoriesClause", string.Empty); + parameters.Add("@LastStep", lastStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); + parameters.Add("@LastApproverInCurrentStep", lastApproverInCurrentStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); + db.Execute("UpdateApproval", parameters, commandType: CommandType.StoredProcedure); - this.db.Execute("ECN_TECNExtensionRejection", parameters, commandType: CommandType.StoredProcedure); + lastStep = parameters.Get("@LastStep"); + lastApproverInCurrentStep = parameters.Get("@LastApproverInCurrentStep"); + return lastApproverInCurrentStep; + } - } + public bool Recall(int issueID, byte step, string comments, int userID, int docType) { + bool lastStep = false; + bool lastApproverInCurrentStep = false; - /// - /// - /// - /// - /// - /// - public string ReAssignApproval(int issueID, int assignedFromUser, int assignedToUser, byte step, int docType) - { + DynamicParameters parameters = new(); + parameters.Add("@IssueID", issueID); + parameters.Add("@CurrentStep", step); + parameters.Add("@ItemStatus", (int)GlobalVars.ApprovalOption.Recalled); + parameters.Add("@UserID", userID); + parameters.Add("@Comments", comments); + parameters.Add("@DocumentTypeID", docType); + parameters.Add("@SubRoleCategoriesClause", string.Empty); + parameters.Add("@LastStep", lastStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); + parameters.Add("@LastApproverInCurrentStep", lastApproverInCurrentStep, dbType: DbType.Boolean, direction: ParameterDirection.Output); - string email = ""; - //string emailArray = ""; - string emailIDArray = ""; + db.Execute("UpdateApproval", parameters, commandType: CommandType.StoredProcedure); + lastStep = parameters.Get("@LastStep"); + lastApproverInCurrentStep = parameters.Get("@LastApproverInCurrentStep"); - var parameters = new DynamicParameters(); ; + return lastApproverInCurrentStep; + } + + public void RejectTECNExtension(int ecnNumber, byte step, string comments, int userID, int docType) { + DynamicParameters parameters = new(); + parameters.Add("@ECNNumber", ecnNumber); + parameters.Add("@CurrentStep", step); + parameters.Add("@UserID", userID); + parameters.Add("@DocumentTypeID", docType); + + db.Execute("ECN_TECNExtensionRejection", parameters, commandType: CommandType.StoredProcedure); + } + + public string ReAssignApproval(int issueID, int assignedFromUser, int assignedToUser, byte step, int docType) { + string email = ""; + //string emailArray = ""; + string emailIDArray = ""; + + DynamicParameters parameters = new(); + ; + email = ""; + parameters = new DynamicParameters(); + parameters.Add("@IssueID", issueID); + parameters.Add("@Step", step); + parameters.Add("@AssignedFromUser", assignedFromUser); + parameters.Add("@AssignedToUser", assignedToUser); + parameters.Add("@DocumentTypeID", docType); + parameters.Add("@Email", email, DbType.String, direction: ParameterDirection.InputOutput); + + db.Execute("ReAssignApproval", parameters, commandType: CommandType.StoredProcedure); + emailIDArray += parameters.Get("@Email"); + + return emailIDArray; + } + + public string DelegateDocumentApproval(int issueID, int delegateFromUser, int delegateToUser) { + string email = ""; + //string emailArray = ""; + string emailID = ""; + + DynamicParameters parameters = new(); + ; + email = ""; + parameters = new DynamicParameters(); + parameters.Add("@IssueID", issueID); + parameters.Add("@DelegateFromUser", delegateFromUser); + parameters.Add("@DelegateToUser", delegateToUser); + parameters.Add("@Email", email, DbType.String, direction: ParameterDirection.InputOutput); + + db.Execute("DelegateApproval", parameters, commandType: CommandType.StoredProcedure); + emailID = parameters.Get("@Email"); + + return emailID; + } + + public string AddAdditionalApproval(int issueID, string userIDs, byte step, int documentType) { + string email = ""; + //string emailArray = ""; + string emailIDArray = ""; + + string[] arrayOfUsers = userIDs.Split(new char[] { '~' }); + + DynamicParameters parameters = new(); + ; + for (int i = 0; i < arrayOfUsers.Length; i++) { email = ""; parameters = new DynamicParameters(); parameters.Add("@IssueID", issueID); parameters.Add("@Step", step); - parameters.Add("@AssignedFromUser", assignedFromUser); - parameters.Add("@AssignedToUser", assignedToUser); - parameters.Add("@DocumentTypeID", docType); + parameters.Add("@UserID", arrayOfUsers[i]); + parameters.Add("@DocumentTypeID", documentType); parameters.Add("@Email", email, DbType.String, direction: ParameterDirection.InputOutput); - this.db.Execute("ReAssignApproval", parameters, commandType: CommandType.StoredProcedure); - emailIDArray = emailIDArray + parameters.Get("@Email"); - - - return emailIDArray; + db.Execute("InsertdAdditionalApproval", parameters, commandType: CommandType.StoredProcedure); + emailIDArray = emailIDArray + parameters.Get("@Email") + "~"; } + return emailIDArray; + } - /// - /// - /// - /// - /// - /// - /// - /// - public string DelegateDocumentApproval(int issueID, int delegateFromUser, int delegateToUser) - { + public string AddEECNApproval(int ecnNumber, byte step, int documentType, string engUserIDs, string opUserIDs) { + string email = ""; + //string emailArray = ""; + string emailIDArray = ""; - string email = ""; - //string emailArray = ""; - string emailID = ""; + string[] arrayOfUsers = engUserIDs.Split(new char[] { '~' }); - - var parameters = new DynamicParameters(); ; + //Engineering SubRole + DynamicParameters parameters = new(); + ; + for (int i = 0; i < arrayOfUsers.Length; i++) { email = ""; parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID); - parameters.Add("@DelegateFromUser", delegateFromUser); - parameters.Add("@DelegateToUser", delegateToUser); + parameters.Add("@ECNNumber", ecnNumber); + parameters.Add("@Step", step); + parameters.Add("@UserID", arrayOfUsers[i]); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@SubRoleCategoryName", "Engineering"); parameters.Add("@Email", email, DbType.String, direction: ParameterDirection.InputOutput); - this.db.Execute("DelegateApproval", parameters, commandType: CommandType.StoredProcedure); - emailID = parameters.Get("@Email"); - - return emailID; - + db.Execute("ECNInsertEmergencyECNApprovers", parameters, commandType: CommandType.StoredProcedure); + emailIDArray = emailIDArray + parameters.Get("@Email") + "~"; } - /// - /// - /// - /// - /// - /// - public string AddAdditionalApproval(int issueID, string userIDs, byte step, int documentType) - { + // Operations SubRole + arrayOfUsers = opUserIDs.Split(new char[] { '~' }); + parameters = new DynamicParameters(); + ; + for (int i = 0; i < arrayOfUsers.Length; i++) { + email = ""; + parameters = new DynamicParameters(); + parameters.Add("@ECNNumber", ecnNumber); + parameters.Add("@Step", step); + parameters.Add("@UserID", arrayOfUsers[i]); + parameters.Add("@DocumentTypeID", documentType); + parameters.Add("@SubRoleCategoryName", "Operations"); + parameters.Add("@Email", email, DbType.String, direction: ParameterDirection.InputOutput); - string email = ""; - //string emailArray = ""; - string emailIDArray = ""; - - string[] arrayOfUsers = userIDs.Split(new char[] { '~' }); - - var parameters = new DynamicParameters(); ; - for (int i = 0; i < arrayOfUsers.Length; i++) - { - email = ""; - parameters = new DynamicParameters(); - parameters.Add("@IssueID", issueID); - parameters.Add("@Step", step); - parameters.Add("@UserID", arrayOfUsers[i]); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@Email", email, DbType.String, direction: ParameterDirection.InputOutput); - - this.db.Execute("InsertdAdditionalApproval", parameters, commandType: CommandType.StoredProcedure); - emailIDArray = emailIDArray + parameters.Get("@Email") + "~"; - } - - return emailIDArray; - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - public string AddEECNApproval(int ecnNumber, byte step, int documentType, string engUserIDs, string opUserIDs) - { - - string email = ""; - //string emailArray = ""; - string emailIDArray = ""; - - string[] arrayOfUsers = engUserIDs.Split(new char[] { '~' }); - - //Engineering SubRole - var parameters = new DynamicParameters(); ; - for (int i = 0; i < arrayOfUsers.Length; i++) - { - email = ""; - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - parameters.Add("@Step", step); - parameters.Add("@UserID", arrayOfUsers[i]); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@SubRoleCategoryName", "Engineering"); - parameters.Add("@Email", email, DbType.String, direction: ParameterDirection.InputOutput); - - this.db.Execute("ECNInsertEmergencyECNApprovers", parameters, commandType: CommandType.StoredProcedure); - emailIDArray = emailIDArray + parameters.Get("@Email") + "~"; - } - - // Operations SubRole - arrayOfUsers = opUserIDs.Split(new char[] { '~' }); - parameters = new DynamicParameters(); ; - for (int i = 0; i < arrayOfUsers.Length; i++) - { - email = ""; - parameters = new DynamicParameters(); - parameters.Add("@ECNNumber", ecnNumber); - parameters.Add("@Step", step); - parameters.Add("@UserID", arrayOfUsers[i]); - parameters.Add("@DocumentTypeID", documentType); - parameters.Add("@SubRoleCategoryName", "Operations"); - parameters.Add("@Email", email, DbType.String, direction: ParameterDirection.InputOutput); - - this.db.Execute("ECNInsertEmergencyECNApprovers", parameters, commandType: CommandType.StoredProcedure); - emailIDArray = emailIDArray + parameters.Get("@Email") + "~"; - } - - return emailIDArray; - } - - - /// - /// - /// - /// - /// - public string GetApproversForCancelled_ExpiredTECNDocs(int ecnNumber) - { - List subRoleItems = new List(); - StringBuilder sqlString = new StringBuilder(); - sqlString.Append( - "SELECT TestProgramChangeRequired, SPCChangeRequired, NewPartFlowRequired, SPNChangeRequired, FIChangeRequired FROM ECN WHERE ECNNumber = @ecNumber "); - - var data = this.db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).Single(); - - if (data.TestProgramChangeRequired == 1) - { - sqlString.Clear(); - sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'TestProgram' "); - var dataRows = this.db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - } - } - if (data.SPCChangeRequired == 1) - { - sqlString.Clear(); - sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'SPC' "); - var dataRows = this.db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - } - - } - if (data.NewPartFlowRequired == 1) - { - sqlString.Clear(); - sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'NewPartFlow' "); - var dataRows = this.db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - } - } - if (data.SPNChangeRequired == 1) - { - sqlString.Clear(); - sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'SPN-Execution' "); - var dataRows = this.db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - } - } - if (data.FIChangeRequired == 1) - { - sqlString.Clear(); - sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'FI-Execution' "); - var dataRows = this.db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).ToList(); - foreach (var dataRow in dataRows) - { - subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); - } - } - - string resultInClause = "(" + String.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; - return resultInClause; - } - - public string GetSubRolesForPartsRequestNextStep(int prNumber) - { - string subRoles = this.db.Query("SELECT dbo.fnPartsRequestGetSubRolesForNextStep(@PRNumber)", - new { PRNumber = prNumber }, - commandType: CommandType.Text).First(); - subRoles = "('" + subRoles + "')"; - return subRoles; - } - - public WorkflowSteps GetWorkflowStep(int docTypeID, int wfNumber, int stepNumber) - { - return this.db.Query( - "SELECT s.* FROM WorkflowSteps s INNER JOIN Workflows w ON w.WorkflowID = s.WorkflowID " + - "WHERE w.DocumentTypeID = @docTypeID AND w.WorkFlowNumber = @wfNumber AND s.WorkflowStepNumber = @stepNumber", - param: new { docTypeID = docTypeID, wfNumber = wfNumber, stepNumber = stepNumber }, - commandType: CommandType.Text).FirstOrDefault(); + db.Execute("ECNInsertEmergencyECNApprovers", parameters, commandType: CommandType.StoredProcedure); + emailIDArray = emailIDArray + parameters.Get("@Email") + "~"; } + return emailIDArray; } -} + + public string GetApproversForCancelled_ExpiredTECNDocs(int ecnNumber) { + List subRoleItems = new(); + StringBuilder sqlString = new(); + sqlString.Append( + "SELECT TestProgramChangeRequired, SPCChangeRequired, NewPartFlowRequired, SPNChangeRequired, FIChangeRequired FROM ECN WHERE ECNNumber = @ecNumber "); + + var data = db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).Single(); + + if (data.TestProgramChangeRequired == 1) { + sqlString.Clear(); + sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'TestProgram' "); + List dataRows = db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + } + } + if (data.SPCChangeRequired == 1) { + sqlString.Clear(); + sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'SPC' "); + List dataRows = db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + } + + } + if (data.NewPartFlowRequired == 1) { + sqlString.Clear(); + sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'NewPartFlow' "); + List dataRows = db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + } + } + if (data.SPNChangeRequired == 1) { + sqlString.Clear(); + sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'SPN-Execution' "); + List dataRows = db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + } + } + if (data.FIChangeRequired == 1) { + sqlString.Clear(); + sqlString.Append("SELECT SubRoleCategoryItem FROM [SubRoleCategory] WHERE SubRoleCategory = 'FI-Execution' "); + List dataRows = db.Query(sqlString.ToString(), new { ecNumber = ecnNumber }).ToList(); + foreach (var dataRow in dataRows) { + subRoleItems.Add("'" + dataRow.SubRoleCategoryItem.ToString() + "'"); + } + } + + string resultInClause = "(" + string.Join(", ", subRoleItems.Distinct().ToArray()) + ")"; + return resultInClause; + } + + public string GetSubRolesForPartsRequestNextStep(int prNumber) { + string subRoles = db.Query("SELECT dbo.fnPartsRequestGetSubRolesForNextStep(@PRNumber)", + new { PRNumber = prNumber }, + commandType: CommandType.Text).First(); + subRoles = "('" + subRoles + "')"; + return subRoles; + } + + public WorkflowSteps GetWorkflowStep(int docTypeID, int wfNumber, int stepNumber) { + return db.Query( + "SELECT s.* FROM WorkflowSteps s INNER JOIN Workflows w ON w.WorkflowID = s.WorkflowID " + + "WHERE w.DocumentTypeID = @docTypeID AND w.WorkFlowNumber = @wfNumber AND s.WorkflowStepNumber = @stepNumber", + param: new { docTypeID = docTypeID, wfNumber = wfNumber, stepNumber = stepNumber }, + commandType: CommandType.Text).FirstOrDefault(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj b/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj index a7dfc48..8a39d82 100644 --- a/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj +++ b/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj @@ -14,6 +14,9 @@ Fab2ApprovalSystem Fab2ApprovalSystem v4.8 + 10.0 + disable + enable false true @@ -92,6 +95,144 @@ + + + + + + + + + + + + + + + + + + + Designer + + + Web.config + + + Web.config + + + ~/Views/Admin/EditorTemplates/Date.cshtml + + + + + Global.asax + + + FabApproval.tt + + + FabApproval.tt + + + TrainingDB.tt + + + TrainingDB.tt + + + TrainingDB.tt + + + TrainingDB.tt + + + TrainingDB.tt + + + TrainingDB.tt + + + TrainingDB.tt + + + TrainingDB.tt + + + Always + + + TrainingDB.edmx + + + FabApproval.edmx + + + + + EntityModelCodeGenerator + TrainingDB.Designer.cs + + + EntityModelCodeGenerator + FabApproval.Designer.cs + + + + + True + True + FabApproval.Context.tt + + + True + True + FabApproval.tt + + + True + True + FabApproval.edmx + + + True + True + TrainingDB.Context.tt + + + True + True + TrainingDB.tt + + + True + True + TrainingDB.edmx + + + + + TextTemplatingFileGenerator + FabApproval.edmx + FabApproval.Context.cs + + + TextTemplatingFileGenerator + FabApproval.edmx + FabApproval.cs + + + TextTemplatingFileGenerator + TrainingDB.edmx + TrainingDB.Context.cs + + + TextTemplatingFileGenerator + TrainingDB.edmx + TrainingDB.cs + + @@ -104,23 +245,24 @@ - - - + + + + - + @@ -131,9 +273,7 @@ - - Global.asax - + @@ -153,119 +293,230 @@ + + - - FabApproval.tt - - - FabApproval.tt - - - TrainingDB.tt - - - True - True - FabApproval.Context.tt - - - True - True - FabApproval.tt - - - True - True - FabApproval.edmx - + + + - - TrainingDB.tt - - - TrainingDB.tt - - - TrainingDB.tt - - - True - True - TrainingDB.Context.tt - - - True - True - TrainingDB.tt - - - True - True - TrainingDB.edmx - - - TrainingDB.tt - - - TrainingDB.tt - - - TrainingDB.tt - - - TrainingDB.tt - + + - - - - + + + + - - - - - - - - - + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - @@ -273,44 +524,47 @@ + + - - + - + + - - + - + + - - + - + + + @@ -349,117 +603,26 @@ - - - - - - - - - - - - - - - - - - - - Always - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - + + - - - - - - - EntityModelCodeGenerator - TrainingDB.Designer.cs - - - - TextTemplatingFileGenerator - FabApproval.edmx - FabApproval.Context.cs - - - TextTemplatingFileGenerator - FabApproval.edmx - FabApproval.cs - - - TrainingDB.edmx - - - EntityModelCodeGenerator - FabApproval.Designer.cs - - - FabApproval.edmx - - - - - - - - - - TextTemplatingFileGenerator - TrainingDB.edmx - TrainingDB.Context.cs - - - TextTemplatingFileGenerator - TrainingDB.edmx - TrainingDB.cs - + + + + + + + + - @@ -546,31 +709,31 @@ - - - - - + + + + + - + - + - + - + @@ -699,13 +862,16 @@ - + + + + @@ -724,9 +890,6 @@ - - - @@ -734,8 +897,8 @@ - + @@ -755,6 +918,8 @@ + + @@ -773,8 +938,6 @@ - - @@ -828,1039 +991,904 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - Designer - - - Web.config - - - Web.config - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ~/Views/Admin/EditorTemplates/Date.cshtml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Fab2ApprovalSystem/Global.asax.cs b/Fab2ApprovalSystem/Global.asax.cs index f307255..7b2daef 100644 --- a/Fab2ApprovalSystem/Global.asax.cs +++ b/Fab2ApprovalSystem/Global.asax.cs @@ -1,165 +1,128 @@ -using Fab2ApprovalSystem.Misc; using System; using System.Collections.Generic; +using System.Configuration; using System.Linq; using System.Web; using System.Web.Hosting; +using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; -using System.Configuration; + using Fab2ApprovalSystem.DMO; -using System.Web.Http; using Fab2ApprovalSystem.JobSchedules; +using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem -{ - public class MvcApplication : System.Web.HttpApplication - { - protected void Application_Start() - { - AreaRegistration.RegisterAllAreas(); - GlobalConfiguration.Configure(WebApiConfig.Register); - FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); - RouteConfig.RegisterRoutes(RouteTable.Routes); - BundleConfig.RegisterBundles(BundleTable.Bundles); +namespace Fab2ApprovalSystem; - string hostName = System.Net.Dns.GetHostEntry("").HostName; - GlobalVars.IS_INFINEON_DOMAIN = hostName.ToLower().Contains("infineon"); +public class MvcApplication : System.Web.HttpApplication { - string DevWebSiteUrl = ConfigurationManager.AppSettings["DevWebSiteURL"].ToString(); - string ProdWebSiteUrlEC = ConfigurationManager.AppSettings["ProdWebSiteURLEC"].ToString(); - string ProdWebSiteUrlStealth = ConfigurationManager.AppSettings["ProdWebSiteURLStealth"].ToString(); + protected void Application_Start() { + AreaRegistration.RegisterAllAreas(); + GlobalConfiguration.Configure(WebApiConfig.Register); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + BundleConfig.RegisterBundles(BundleTable.Bundles); - GlobalVars.SENDER_EMAIL = "FabApprovalSystem@Infineon.com"; // put in the Config File - if (ConfigurationManager.AppSettings["Notification Sender"] != null) - GlobalVars.SENDER_EMAIL = ConfigurationManager.AppSettings["Notification Sender"].ToString(); + string hostName = System.Net.Dns.GetHostEntry("").HostName; + GlobalVars.IS_INFINEON_DOMAIN = hostName.ToLower().Contains("infineon"); - GlobalVars.NDriveURL = ConfigurationManager.AppSettings["NDrive"].ToString(); - GlobalVars.WSR_URL = ConfigurationManager.AppSettings["WSR_URL"].ToString(); - GlobalVars.CA_BlankFormsLocation = ConfigurationManager.AppSettings["CA_BlankFormsLocation"].ToString(); + string DevWebSiteUrl = ConfigurationManager.AppSettings["DevWebSiteURL"].ToString(); + string ProdWebSiteUrlEC = ConfigurationManager.AppSettings["ProdWebSiteURLEC"].ToString(); + string ProdWebSiteUrlStealth = ConfigurationManager.AppSettings["ProdWebSiteURLStealth"].ToString(); - //GlobalVars.AttachmentUrl = connectionstring.ToUpper().Contains("TEST") ? @"http://" + DevAttachmentUrl + "/" : @"http://" + ProdAttachmentUrl + "/"; ; + GlobalVars.SENDER_EMAIL = "FabApprovalSystem@Infineon.com"; // put in the Config File + if (ConfigurationManager.AppSettings["Notification Sender"] != null) + GlobalVars.SENDER_EMAIL = ConfigurationManager.AppSettings["Notification Sender"].ToString(); + + GlobalVars.NDriveURL = ConfigurationManager.AppSettings["NDrive"].ToString(); + GlobalVars.WSR_URL = ConfigurationManager.AppSettings["WSR_URL"].ToString(); + GlobalVars.CA_BlankFormsLocation = ConfigurationManager.AppSettings["CA_BlankFormsLocation"].ToString(); #if (!DEBUG) - OOOTrainingReportJobSchedule.Start(); + OOOTrainingReportJobSchedule.Start(); - if (GlobalVars.IS_INFINEON_DOMAIN) { - GlobalVars.DB_CONNECTION_STRING = ConfigurationManager.ConnectionStrings["FabApprovalConnectionStealth"].ConnectionString.ToString(); - GlobalVars.hostURL = @"https://" + ProdWebSiteUrlStealth; - } else { - GlobalVars.DB_CONNECTION_STRING = ConfigurationManager.ConnectionStrings["FabApprovalConnectionEC"].ConnectionString.ToString(); - GlobalVars.hostURL = @"https://" + ProdWebSiteUrlEC; - } + if (GlobalVars.IS_INFINEON_DOMAIN) { + GlobalVars.DB_CONNECTION_STRING = ConfigurationManager.ConnectionStrings["FabApprovalConnectionStealth"].ConnectionString.ToString(); + GlobalVars.hostURL = @"https://" + ProdWebSiteUrlStealth; + } else { + GlobalVars.DB_CONNECTION_STRING = ConfigurationManager.ConnectionStrings["FabApprovalConnectionEC"].ConnectionString.ToString(); + GlobalVars.hostURL = @"https://" + ProdWebSiteUrlEC; + } #else - GlobalVars.DB_CONNECTION_STRING = ConfigurationManager.ConnectionStrings["FabApprovalConnectionDev"].ConnectionString.ToString(); - GlobalVars.hostURL = @"https://" + DevWebSiteUrl; + GlobalVars.DB_CONNECTION_STRING = ConfigurationManager.ConnectionStrings["FabApprovalConnectionDev"].ConnectionString.ToString(); + GlobalVars.hostURL = @"https://" + DevWebSiteUrl; #endif - GlobalVars.DBConnection = GlobalVars.DB_CONNECTION_STRING.ToUpper().Contains("TEST") ? "TEST" : GlobalVars.DB_CONNECTION_STRING.ToUpper().Contains("QUALITY") ? "QUALITY" : "PROD"; - } - - - //void Application_BeginRequest(Object source, EventArgs e) - //{ - - // HttpApplication app = (HttpApplication)source; - // HttpContext context = app.Context; - // GlobalVars.hostURL = context.Request.Url.AbsoluteUri; - // // Attempt to peform first request initialization - - //} - - protected void Application_EndRequest() - { - var context = new HttpContextWrapper(Context); - - //Do a direct 401 unautorized - if (Context.Response.StatusCode == 301 && context.Request.IsAjaxRequest()) - { - Context.Response.Clear(); - Context.Response.StatusCode = 401; - } - - else if (FormsAuthentication.IsEnabled && context.Response.StatusCode == 302 - && context.Request.IsAjaxRequest()) - { - context.Response.Clear(); - context.Response.StatusCode = 401; - } - } - - protected void Session_Start(object sender, EventArgs e) - { - Session[GlobalVars.ECN_VIEW_OPTION] = "Pending Approvals"; ; - } - - protected void Session_End(object sender, EventArgs e) - { - //FormsAuthentication.SignOut(); - try - { - Session[GlobalVars.SESSION_USERNAME] = ""; - Session[GlobalVars.SESSION_USERID] = ""; - Session[GlobalVars.IS_ADMIN] = ""; - - //LotTravelerDMO LotTravDMO = new LotTravelerDMO(); - //LotTravDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], -1); - } - - catch(Exception ex) - { - Functions.WriteEvent(@User.Identity.Name + "\r\n Session Closed - \r\n" + ex.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - } - - - } - - // This code is to allow hyperlinks from Office products to load the site without always forcing the user to log in - // It makes the browser reload the page so that the session cookies are sent properly - private static string MSUserAgentsRegex = @"[^\w](Word|Excel|PowerPoint|ms-office)([^\w]|\z)"; - protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e) - { - if (System.Text.RegularExpressions.Regex.IsMatch(Request.UserAgent, MSUserAgentsRegex)) - { - Response.Write(""); - Response.End(); - } - } - - void Application_Error(object sender, EventArgs e) - { - var ex = Server.GetLastError(); - - var exString = "Caught unhandled exception:\r\n"; - exString += String.Format("User: {0}\r\n", @User.Identity.Name); - Exception x = ex; - while (x != null) - { - exString += x.ToString(); - exString += "=====\r\n"; - x = x.InnerException; - } - - //Misc.Functions.WriteEvent(exString, System.Diagnostics.EventLogEntryType.Error); - - try - { - if (exString.Length > 500) - exString = exString.Substring(0, 500); - - EventLogDMO.Add(new Fab2ApprovalSystem.Models.WinEventLog() - { - UserID = @User.Identity.Name, - OperationType = "Error", - Comments = exString - }); - } - catch (Exception ex2) - { - Misc.Functions.WriteEvent("Failed to write error to event log in database: " + ex2.ToString(), System.Diagnostics.EventLogEntryType.Error); - } - } + GlobalVars.DBConnection = GlobalVars.DB_CONNECTION_STRING.ToUpper().Contains("TEST") ? "TEST" : GlobalVars.DB_CONNECTION_STRING.ToUpper().Contains("QUALITY") ? "QUALITY" : "PROD"; + GlobalVars.AppSettings = Models.AppSettings.LoadConfigurationManager(); } -} + + protected void Application_EndRequest() { + var context = new HttpContextWrapper(Context); + + //Do a direct 401 unauthorized + if (Context.Response.StatusCode == 301 && context.Request.IsAjaxRequest()) { + Context.Response.Clear(); + Context.Response.StatusCode = 401; + } else if (FormsAuthentication.IsEnabled && context.Response.StatusCode == 302 + && context.Request.IsAjaxRequest()) { + context.Response.Clear(); + context.Response.StatusCode = 401; + } + } + + protected void Session_Start(object sender, EventArgs e) { + Session[GlobalVars.ECN_VIEW_OPTION] = "Pending Approvals"; + } + + protected void Session_End(object sender, EventArgs e) { + //FormsAuthentication.SignOut(); + try { + Session[GlobalVars.SESSION_USERNAME] = ""; + Session[GlobalVars.SESSION_USERID] = ""; + Session[GlobalVars.IS_ADMIN] = ""; + } catch (Exception ex) { + Functions.WriteEvent(null, @User.Identity.Name + "\r\n Session Closed - \r\n" + ex.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + } + } + + // This code is to allow hyperlinks from Office products to load the site without always forcing the user to log in + // It makes the browser reload the page so that the session cookies are sent properly + private static string MSUserAgentsRegex = @"[^\w](Word|Excel|PowerPoint|ms-office)([^\w]|\z)"; + protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e) { + if (System.Text.RegularExpressions.Regex.IsMatch(Request.UserAgent, MSUserAgentsRegex)) { + Response.Write(""); + Response.End(); + } + } + + void Application_Error(object sender, EventArgs e) { + var ex = Server.GetLastError(); + + var exString = "Caught unhandled exception:\r\n"; + exString += String.Format("User: {0}\r\n", @User.Identity.Name); + Exception x = ex; + while (x != null) { + exString += x.ToString(); + exString += "=====\r\n"; + x = x.InnerException; + } + + try { + if (exString.Length > 500) + exString = exString.Substring(0, 500); + + EventLogDMO.Add(new Fab2ApprovalSystem.Models.WinEventLog() { + UserID = @User.Identity.Name, + OperationType = "Error", + Comments = exString + }); + } catch (Exception ex2) { + Misc.Functions.WriteEvent(null, "Failed to write error to event log in database: " + ex2.ToString(), System.Diagnostics.EventLogEntryType.Error); + } + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/JobSchedules/OOOTrainingReportJobSchedule.cs b/Fab2ApprovalSystem/JobSchedules/OOOTrainingReportJobSchedule.cs index 9040207..136f163 100644 --- a/Fab2ApprovalSystem/JobSchedules/OOOTrainingReportJobSchedule.cs +++ b/Fab2ApprovalSystem/JobSchedules/OOOTrainingReportJobSchedule.cs @@ -1,33 +1,28 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; using Fab2ApprovalSystem.Workers; -using Quartz.Impl; + using Quartz; +using Quartz.Impl; -namespace Fab2ApprovalSystem.JobSchedules -{ - public class OOOTrainingReportJobSchedule - { - public static void Start() - { - ISchedulerFactory schedulerFactory = new StdSchedulerFactory(); +namespace Fab2ApprovalSystem.JobSchedules; - IScheduler scheduler = schedulerFactory.GetScheduler().GetAwaiter().GetResult(); - scheduler.Start(); +public class OOOTrainingReportJobSchedule { - IJobDetail oooTrainingReportJob = JobBuilder.Create() - .WithIdentity("oooTrainingReportJob", "trainingReportGroup") - .Build(); + public static void Start() { + ISchedulerFactory schedulerFactory = new StdSchedulerFactory(); - ITrigger oooTrainingReportTrigger = TriggerBuilder.Create() - .WithIdentity("oooTrainingReportTrigger", "trainingReportGroup") - .WithCronSchedule("0 0 12 ? * 2 *") - .ForJob(oooTrainingReportJob) - .Build(); + IScheduler scheduler = schedulerFactory.GetScheduler().GetAwaiter().GetResult(); + scheduler.Start(); - scheduler.ScheduleJob(oooTrainingReportJob, oooTrainingReportTrigger); - } + IJobDetail oooTrainingReportJob = JobBuilder.Create() + .WithIdentity("oooTrainingReportJob", "trainingReportGroup") + .Build(); + + ITrigger oooTrainingReportTrigger = TriggerBuilder.Create() + .WithIdentity("oooTrainingReportTrigger", "trainingReportGroup") + .WithCronSchedule("0 0 12 ? * 2 *") + .ForJob(oooTrainingReportJob) + .Build(); + + scheduler.ScheduleJob(oooTrainingReportJob, oooTrainingReportTrigger); } -} +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Jobs/OOOTrainingReportJob.cs b/Fab2ApprovalSystem/Jobs/OOOTrainingReportJob.cs index 79047b4..9661e94 100644 --- a/Fab2ApprovalSystem/Jobs/OOOTrainingReportJob.cs +++ b/Fab2ApprovalSystem/Jobs/OOOTrainingReportJob.cs @@ -8,69 +8,61 @@ using Fab2ApprovalSystem.Utilities; using Quartz; -namespace Fab2ApprovalSystem.Workers -{ - public class OOOTrainingReportJob:IJob - { - UserAccountDMO userDMO = new UserAccountDMO(); - AdminDMO adminDMO = new AdminDMO(); - TrainingDMO trainingDMO = new TrainingDMO(); - ECN_DMO ecnDMO = new ECN_DMO(); - public EmailUtilities emailer = new EmailUtilities(); +namespace Fab2ApprovalSystem.Workers; - async Task IJob.Execute(IJobExecutionContext context) - { - await Task.Run(() => { +public class OOOTrainingReportJob : IJob { - string emailBody = "

Mesa Approval Open Training Assignments Report - OOO


"; - emailBody += "

The following contains open training assignments in the Mesa Approval system for out of office users."; - emailBody += " Please ensure they complete their training assignments promptly upon their return.


"; - emailBody += ""; - //Get all users set up to receive the training report email. - List trainingReportUsers = adminDMO.GetTrainingReportUsers(); - List emailList = new List(); - foreach (var user in trainingReportUsers) - { - string userEmail = userDMO.GetUserByID(user.UserId).Email; - emailList.Add(userEmail); - } - //emailList.Add("Chase.Tucker@infineon.com"); - //Get a list of open trainings - List openTrainings = trainingDMO.GetAllOpenTrainings(); + private readonly UserAccountDMO userDMO = new(); + private readonly AdminDMO adminDMO = new(); + private readonly TrainingDMO trainingDMO = new(); + private readonly ECN_DMO ecnDMO = new(); - foreach (Training training in openTrainings) - { - string trainingSection = ""; - int trainingSectionUserCount = 0; - string ecnTitle = ecnDMO.GetECN(training.ECN).Title; - trainingSection += "

" + training.ECN + " - " + ecnTitle + "

"; + async Task IJob.Execute(IJobExecutionContext context) { + await Task.Run(() => { + string emailBody = "

Mesa Approval Open Training Assignments Report - OOO


"; + emailBody += "

The following contains open training assignments in the Mesa Approval system for out of office users."; + emailBody += " Please ensure they complete their training assignments promptly upon their return.


"; + emailBody += ""; + //Get all users set up to receive the training report email. + List trainingReportUsers = adminDMO.GetTrainingReportUsers(); + List emailList = new(); + foreach (TrainingReportUser user in trainingReportUsers) { + string userEmail = userDMO.GetUserByID(user.UserId).Email; + emailList.Add(userEmail); + } + //emailList.Add("Chase.Tucker@infineon.com"); + //Get a list of open trainings + List openTrainings = trainingDMO.GetAllOpenTrainings(); - trainingSection += ""; - trainingSection += ""; - List openAssignments = trainingDMO.GetOpenAssignmentsByTrainingID(training.TrainingID); - foreach (TrainingAssignment assignment in openAssignments) - { + foreach (Training training in openTrainings) { + string trainingSection = ""; + int trainingSectionUserCount = 0; + string ecnTitle = ecnDMO.GetECN(training.ECN).Title; + trainingSection += "

" + training.ECN + " - " + ecnTitle + "

"; - if (userDMO.GetUserByID(assignment.UserID).OOO) - { - trainingSectionUserCount++; + trainingSection += "
NameDate Assigned
"; + trainingSection += ""; + List openAssignments = trainingDMO.GetOpenAssignmentsByTrainingID(training.TrainingID); + foreach (TrainingAssignment assignment in openAssignments) { + if (userDMO.GetUserByID(assignment.UserID).OOO) { + trainingSectionUserCount++; - DateTime? assignmentDate = assignment.DateAssigned; + DateTime? assignmentDate = assignment.DateAssigned; - string DateAssigned = assignmentDate.HasValue ? assignmentDate.Value.ToString("MM/dd/yyyy") : ""; + string DateAssigned = assignmentDate.HasValue ? assignmentDate.Value.ToString("MM/dd/yyyy") : ""; - trainingSection += ""; + trainingSection += ""; - trainingSection += ""; - } + trainingSection += ""; } - trainingSection += "
NameDate Assigned
" + assignment.FullName + "" + DateAssigned + "
" + assignment.FullName + "" + DateAssigned + "
"; - if (trainingSectionUserCount > 0) emailBody += trainingSection; } - string recipientEmail = ""; - List ccRecipients = emailList; - emailer.SendNotification("MesaFabApproval@infineon.com", ccRecipients, "Mesa Approval Open Training Report - OOO", emailBody, "Open Training Report - OOO"); - }); - } + trainingSection += ""; + if (trainingSectionUserCount > 0) + emailBody += trainingSection; + } + string recipientEmail = ""; + List ccRecipients = emailList; + EmailUtilities.SendNotification("MesaFabApproval@infineon.com", ccRecipients, "Open Training Report - OOO", emailBody); + }); } -} +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/Demohelper.cs b/Fab2ApprovalSystem/Misc/Demohelper.cs index 00f3d0b..3fdb261 100644 --- a/Fab2ApprovalSystem/Misc/Demohelper.cs +++ b/Fab2ApprovalSystem/Misc/Demohelper.cs @@ -1,39 +1,32 @@ -using Fab2ApprovalSystem.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using System.Collections.Generic; -namespace Fab2ApprovalSystem.Misc -{ - public class DemoHelper - { - public static List GetCountries() - { - return new List - { - "USA", "England", "Belguim", "France", "Italy" - }; - } +using Fab2ApprovalSystem.Models; - public List ListOfModels = new List(); +namespace Fab2ApprovalSystem.Misc; - private static DemoHelper m_dHelper = new DemoHelper(); - public static DemoHelper Instance - { - get { return m_dHelper; } - } - - private DemoHelper() - { - TestModel A1 = new TestModel(); - A1.Name = "Eran"; - A1.Countries = new List(); - A1.Countries.Add("England"); - A1.Countries.Add("Belguim"); - ListOfModels.Add(A1); - - } +public class DemoHelper { + public static List GetCountries() { + return new List + { + "USA", "England", "Belguim", "France", "Italy" + }; } + + public List ListOfModels = new(); + + private static readonly DemoHelper m_dHelper = new(); + public static DemoHelper Instance { + get { return m_dHelper; } + } + + private DemoHelper() { + TestModel A1 = new(); + A1.Name = "Eran"; + A1.Countries = new List(); + A1.Countries.Add("England"); + A1.Countries.Add("Belguim"); + ListOfModels.Add(A1); + } + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/Documentum.cs b/Fab2ApprovalSystem/Misc/Documentum.cs index f5676b8..91af94f 100644 --- a/Fab2ApprovalSystem/Misc/Documentum.cs +++ b/Fab2ApprovalSystem/Misc/Documentum.cs @@ -1,168 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +namespace Fab2ApprovalSystem.Misc; -//using DFClib.DfException; -//using DFCLib.DfId; -//using DFCLib.IDfId; -//using DFCLib.IDfList; -//using DFCLib.IDfLoginInfo; - -//using DFCLib.IDfClient; -//using DFCLib.IDfDocument; -//using DFCLib.IDfSession; -//using DFCLib.IDfSessionManager; - -//using DFCLib.DfClientX; -//using DFCLib.IDfClientX; -//using DFCLib.IDfFile; -//using DFCLib.IDfImportNode; -//using DFCLib.IDfImportOperation; - -namespace Fab2ApprovalSystem.Misc -{ - - - public class Documentum - { - - //public static void Process(string m_fileName) - //{ - // String username = "rkotian1"; - // String password = ""; - // String repoName = "globaldocudms"; - // String filename = m_fileName; // for example {"C:\\devprog\\ECN12345.zip"}; - // String destFldrId = "0c00359980061536"; - - // try - // { - // DFCLib.IDfSessionManager sessMgr = createSessionManager(); - // addIdentity(sessMgr, username, password, repoName); - // importFiles(sessMgr, repoName, filename, destFldrId); - // } - // catch (Exception ex) - // { - // //string s = ex.InnerException.ToString(); - // } - - - //} - - ///** - // * Imports a single file in the repository - // * - // */ - //private static void importFiles(DFCLib.IDfSessionManager sessMgr, String repoName, String filename, String destFldrId) - //{ - // DFCLib.IDfSession sess = null; - // try - // { - // DFCLib.IDfClientX clientX = new DFCLib.DfClientX(); - - // DFCLib.IDfImportOperation impOper = clientX.getImportOperation(); - - // //DFCLib.IDfId destId = new DfId(destFldrId); - // DFCLib.IDfId destId = clientX.getId(destFldrId); - - // //This will import all files to a single destination. - // //To import each file to a different destination - // //set call this method on the import node. - // //impOper.setDestinationFolderId(destId); - // DFCLib.IDfFile localFile = clientX.getFile(filename); - // DFCLib.IDfImportNode impNode = (DFCLib.IDfImportNode)impOper.add(localFile); - - // //You can set different destination ids here for each import node - // //This way files get imported to different destinations. - // impNode.setDestinationFolderId(destId); - - // //set custom object type. If not called dm_document is used. - // impNode.setDocbaseObjectType("dp_text"); - - // int randomName = ((int)(new Random().Next(int.MinValue, int.MaxValue) * 100)); - // //set custom object name. - // impNode.setNewObjectName(localFile.getName() + "" + randomName.ToString()); - // //The import operation determines the file format. - // //It is also possible to explicitly set the format. - // //impNode.setFormat(""); - - - - // sess = sessMgr.getSession(repoName); - // impOper.setSession(sess); - - // if (impOper.execute()) - // { - // Console.WriteLine("Import Operation Succeeded"); - // DFCLib.IDfList newObjLst = impOper.getNewObjects(); - // for (int i = 0; i < newObjLst.getCount(); i++) - // { - // DFCLib.IDfDocument newObj = (DFCLib.IDfDocument)newObjLst.get(i); - // //you can set any custom/standard attr values on the document now - // //newObj.setString("my_attr","someValue"); - // //newObj.save(); - // Console.WriteLine("Created Object: " + newObj.getObjectId()); - // } - // } - // else - // { - // Console.WriteLine("Import Operation Failed"); - // DFCLib.IDfList errList = impOper.getErrors(); - // for (int i = 0; i < errList.getCount(); i++) - // { - // DFCLib.IDfOperationError err = (DFCLib.IDfOperationError)errList.get(i); - // Console.WriteLine(err.getMessage()); - // } - // } - // } - // finally - // { - // if (sess != null) - // { - // sessMgr.release(sess); - // } - // } - - //} - - ///** - // * Creates a new session manager instance. The session manager does not have - // * any identities associated with it. - // * @return a new session manager object. - //*/ - //private static DFCLib.IDfSessionManager createSessionManager() - //{ - // DFCLib.IDfClientX clientX = new DFCLib.DfClientX(); - // DFCLib.IDfClient localClient = clientX.getLocalClient(); - // DFCLib.IDfSessionManager sessMgr = localClient.newSessionManager(); - // return sessMgr; - //} - - ///** - // * Adds a new identity to the session manager. - // * - // */ - //private static void addIdentity(DFCLib.IDfSessionManager sm, String username, - // String password, String repoName) - //{ - // DFCLib.IDfClientX clientX = new DFCLib.DfClientX(); - - // DFCLib.IDfLoginInfo li = clientX.getLoginInfo(); - // li.setUser(username); - // li.setPassword(password); - - // // check if session manager already has an identity. - // // if yes, remove it. - // if (sm.hasIdentity(repoName)) - // { - // sm.clearIdentity(repoName); - // } - - // sm.setIdentity(repoName, li); - //} - - - - - } -} \ No newline at end of file +public class Documentum { } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/EmailNotification.cs b/Fab2ApprovalSystem/Misc/EmailNotification.cs index 26ee095..01abf69 100644 --- a/Fab2ApprovalSystem/Misc/EmailNotification.cs +++ b/Fab2ApprovalSystem/Misc/EmailNotification.cs @@ -1,593 +1,504 @@ -using System; +#pragma warning disable CS8019 + +using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net.Mail; -using System.Web; -namespace Fab2ApprovalSystem.Misc { - public class EmailNotification { - #region Variabls - protected string _subject = null; - protected string _TemplatesPath = null; - #endregion +#pragma warning restore CS8019 - /// - /// Email subject - /// - public string EmailSubject { - set { _subject = value; } +namespace Fab2ApprovalSystem.Misc; + +public class EmailNotification { + + #region Variabls + protected string _subject = null; + protected string _TemplatesPath = null; + private readonly Models.AppSettings _AppSettings; + #endregion + + public EmailNotification(Models.AppSettings appSettings) => + _AppSettings = appSettings; + + /// + /// The Constructor Function + /// + /// Email Header Subject + /// Emails Files Templates + public EmailNotification(Models.AppSettings appSettings, string EmailHeaderSubject, string TemplatesPath) { + _AppSettings = appSettings; + _subject = EmailHeaderSubject; + _TemplatesPath = TemplatesPath; + } + + public EmailNotification(Models.AppSettings appSettings, string subject, string templatesPath, string emailSubject) : + this(appSettings, subject, templatesPath) => + EmailSubject = emailSubject; + + /// + /// Email subject + /// + public string EmailSubject { + set => _subject = value; + } + + /// + /// This function will read the content of a file name + /// + /// File Name + /// String: Containing the Entire content of the file + protected string ReadEmailFile(string FileName) { + string retVal = null; + try { + //setting the file name path + string path = _TemplatesPath + FileName; +#if !NET8 + FileInfo TheFile = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(path)); + + //check if the file exists in the location. + if (!TheFile.Exists) + throw new Exception("Could Not Find the file : " + FileName + " in the location " + _TemplatesPath); // throw an exception here. + + //start reading the file. i have used Encoding 1256 to support arabic text also. + StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(@path), System.Text.Encoding.GetEncoding(1256)); + retVal = sr.ReadToEnd(); // getting the entire text from the file. + sr.Close(); +#endif + } catch (Exception ex) { + throw new Exception("Error Reading File." + ex.Message); } + return retVal; + } - /// - /// This function will read the content of a file name - /// - /// File Name - /// String: Containing the Entire content of the file - protected string ReadEmailFile(string FileName) { - string retVal = null; - try { - //setting the file name path - string path = _TemplatesPath + FileName; - FileInfo TheFile = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(path)); - - //check if the file exists in the location. - if (!TheFile.Exists) - throw new Exception("Could Not Find the file : " + FileName + " in the location " + _TemplatesPath); // throw an exception here. - - //start reading the file. i have used Encoding 1256 to support arabic text also. - StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(@path), System.Text.Encoding.GetEncoding(1256)); - retVal = sr.ReadToEnd(); // getting the entire text from the file. - sr.Close(); - } catch (Exception ex) { - throw new Exception("Error Reading File." + ex.Message); - } - return retVal; - } - - /// - /// this function will send email. it will read the mail setting from the web.config - /// - /// Sender Email ID - /// Sender Name - /// Recepient Email ID - /// CC ids - /// Email Subject - /// Email Body + /// + /// this function will send email. it will read the mail setting from the web.config + /// + /// Sender Email ID + /// Sender Name + /// Recepient Email ID + /// CC ids + /// Email Subject + /// Email Body #pragma warning disable IDE0060 // Remove unused parameter - protected void SendEmail(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body) { - // creating email message - MailMessage msg = new MailMessage(); - msg.IsBodyHtml = true;// email body will allow html elements + protected void SendEmail(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body) { + // creating email message + MailMessage msg = new(); + msg.IsBodyHtml = true;// email body will allow html elements - // setting the Sender Email ID - //msg.From = new MailAddress(SenderEmail, SenderName); - msg.From = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval"); - msg.Sender = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval"); - // adding the Recepient Email ID - msg.To.Add(Recep); - //msg.To.Add("Jonathan.Ouellette@infineon.com"); - // add CC email ids if supplied. - if (!string.IsNullOrEmpty(cc)) - msg.CC.Add(cc); + // setting the Sender Email ID + //msg.From = new MailAddress(SenderEmail, SenderName); + msg.From = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval"); + msg.Sender = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval"); + // adding the Recepient Email ID + msg.To.Add(Recep); + //msg.To.Add("Jonathan.Ouellette@infineon.com"); + // add CC email ids if supplied. + if (!string.IsNullOrEmpty(cc)) + msg.CC.Add(cc); - //setting email subject and body - msg.Subject = email_title; - msg.Body = email_body; + //setting email subject and body + msg.Subject = email_title; + msg.Body = email_body; - //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section - SmtpClient SmtpMail = new SmtpClient("mailrelay-internal.infineon.com"); + //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section + SmtpClient SmtpMail = new("mailrelay-internal.infineon.com"); - // sending the message. - try { - SmtpMail.Send(msg); - } catch (Exception ex) { - Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", - ex.ToString()); - } - } -#pragma warning restore IDE0060 // Remove unused parameter - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - protected void SendEmailWithAttachment(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, string attachmentPath) { - // creating email message - MailMessage msg = new MailMessage(); - msg.IsBodyHtml = true;// email body will allow html elements - - // setting the Sender Email ID - msg.From = new MailAddress(SenderEmail, SenderName); - - // adding the Recepient Email ID - msg.To.Add(Recep); - - // add CC email ids if supplied. - if (!string.IsNullOrEmpty(cc)) - msg.CC.Add(cc); - - //setting email subject and body - msg.Subject = email_title; - msg.Body = email_body; - msg.Attachments.Add(new Attachment(attachmentPath)); - - //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section - SmtpClient SmtpMail = new SmtpClient(); -#if(!DEBUG) - // sending the message. + // sending the message. + try { SmtpMail.Send(msg); -#endif - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// -#pragma warning disable IDE0060 // Remove unused parameter - protected void SendEmail(string SenderEmail, string SenderName, List RecepientList, string cc, string email_title, string email_body) { - // creating email message - MailMessage msg = new MailMessage(); - msg.IsBodyHtml = true;// email body will allow html elements - - // setting the Sender Email ID - //msg.From = new MailAddress(SenderEmail, SenderName); - msg.From = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval"); - // adding the Recepient Email ID - foreach (string recepient in RecepientList) { - msg.To.Add(recepient); - } - - // add CC email ids if supplied. - if (!string.IsNullOrEmpty(cc)) - msg.CC.Add(cc); - - //setting email subject and body - msg.Subject = email_title; - msg.Body = email_body; - - //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section - SmtpClient SmtpMail = new SmtpClient(); - - // sending the message. - try { - SmtpMail.Send(msg); - } catch (Exception ex) { - Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", - ex.ToString()); - } - } -#pragma warning restore IDE0060 // Remove unused parameter - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - protected void SendEmailWithAttachment(string SenderEmail, string SenderName, List RecepientList, string cc, string email_title, string email_body, string attachmentPath) { - // creating email message - MailMessage msg = new MailMessage(); - msg.IsBodyHtml = true;// email body will allow html elements - - // setting the Sender Email ID - msg.From = new MailAddress(SenderEmail, SenderName); - - // adding the Recepient Email ID - foreach (string recepient in RecepientList) { - if (recepient != null) - msg.To.Add(recepient); - } - - // add CC email ids if supplied. - if (!string.IsNullOrEmpty(cc)) - msg.CC.Add(cc); - - //setting email subject and body - msg.Subject = email_title; - msg.Body = email_body; - msg.Attachments.Add(new Attachment(attachmentPath)); - - //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section - SmtpClient SmtpMail = new SmtpClient(); - - // sending the message. - SmtpMail.Send(msg); - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - protected void SendEmailWithAttachments(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, List attachments) { - // creating email message - MailMessage msg = new MailMessage(); - msg.IsBodyHtml = true;// email body will allow html elements - - // setting the Sender Email ID - msg.From = new MailAddress(SenderEmail, SenderName); - - // adding the Recepient Email ID - msg.To.Add(Recep); - - // add CC email ids if supplied. - if (!string.IsNullOrEmpty(cc)) - msg.CC.Add(cc); - - //setting email subject and body - msg.Subject = email_title; - msg.Body = email_body; - foreach (string attachment in attachments) { - msg.Attachments.Add(new Attachment(attachment)); - } - - //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section - SmtpClient SmtpMail = new SmtpClient(); -#if(!DEBUG) - // sending the message. - SmtpMail.Send(msg); -#endif - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - protected void SendEmailWithAttachments(string SenderEmail, string SenderName, List RecepientList, string cc, string email_title, string email_body, List attachments) { - // creating email message - MailMessage msg = new MailMessage(); - msg.IsBodyHtml = true;// email body will allow html elements - - // setting the Sender Email ID - msg.From = new MailAddress(SenderEmail, SenderName); - - // adding the Recepient Email ID - foreach (string recepient in RecepientList) { - if (recepient != null) - msg.To.Add(recepient); - } - - // add CC email ids if supplied. - if (!string.IsNullOrEmpty(cc)) - msg.CC.Add(cc); - - //setting email subject and body - msg.Subject = email_title; - msg.Body = email_body; - - foreach (string attachment in attachments) { - msg.Attachments.Add(new Attachment(attachment)); - } - - //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section - SmtpClient SmtpMail = new SmtpClient(); - - // sending the message. - SmtpMail.Send(msg); - } - - public EmailNotification() { - - } - - /// - /// The Constructor Function - /// - /// Email Header Subject - /// Emails Files Templates - public EmailNotification(string EmailHeaderSubject, string TemplatesPath) { - _subject = EmailHeaderSubject; - _TemplatesPath = TemplatesPath; - - } - - /// - /// This function will send the email notification by reading the email template and substitute the arguments - /// - /// Email Template File - /// Sender Email - /// Sender Name - /// Recepient Email ID - /// CC IDs - /// EMail Subject - /// Arguments - /// String: Return the body of the email to be send - public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, params string[] Args) { - string retVal = null; - - //reading the file - string FileContents = ReadEmailFile(EmailTemplateFile); - - string emailBody = FileContents; - - //setting formatting the string - retVal = string.Format(emailBody, Args); - - try { - //check if we are in debug mode or not. to send email - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { - SendEmail(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? Subject + " for: " + RecepientEmail : _subject), retVal); - } else { -#if(!DEBUG) - SendEmail(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal); -#endif - } - } catch (Exception ex) { - throw ex; - } - - return retVal; - } - - /// - /// This function will send the email notification by reading the email template and substitute the arguments along with the attachments - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, string attachmentPath, params string[] Args) { - string retVal = null; - - //reading the file - string FileContents = ReadEmailFile(EmailTemplateFile); - - string emailBody = FileContents; - - //setting formatting the string - retVal = string.Format(emailBody, Args); - - try { - //check if we are in debug mode or not. to send email - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { - SendEmailWithAttachment(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject + RecepientEmail : _subject), retVal, attachmentPath); - } else { -#if(!DEBUG) - SendEmailWithAttachment(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachmentPath); -#endif - } - } catch (Exception ex) { - throw ex; - } - - return retVal; - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, List RecepientEmail, string CC, string Subject, string attachmentPath, params string[] Args) { - string retVal = null; - - //reading the file - string FileContents = ReadEmailFile(EmailTemplateFile); - - string emailBody = FileContents; - - //setting formatting the string - retVal = string.Format(emailBody, Args); - - try { - //check if we are in debug mode or not. to send email - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { - foreach (string email in RecepientEmail) { - Subject += email + ";"; - } - - RecepientEmail.Clear(); - SendEmailWithAttachment(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject : _subject), retVal, attachmentPath); - } else { -#if (!DEBUG) - SendEmailWithAttachment(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachmentPath); -#endif - } - } catch (Exception ex) { - throw ex; - } - - return retVal; - } - - public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, List attachments, params string[] Args) { - string retVal = null; - - //reading the file - string FileContents = ReadEmailFile(EmailTemplateFile); - - string emailBody = FileContents; - - //setting formatting the string - retVal = string.Format(emailBody, Args); - - try { - //check if we are in debug mode or not. to send email - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { - SendEmailWithAttachments(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject + RecepientEmail : _subject), retVal, attachments); - } else { -#if(!DEBUG) - SendEmailWithAttachments(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachments); -#endif - } - } catch (Exception ex) { - throw ex; - } - - return retVal; - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, List RecepientEmail, string CC, string Subject, List attachments, params string[] Args) { - string retVal = null; - - //reading the file - string FileContents = ReadEmailFile(EmailTemplateFile); - - string emailBody = FileContents; - - //setting formatting the string - retVal = string.Format(emailBody, Args); - - try { - //check if we are in debug mode or not. to send email - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { - foreach (string email in RecepientEmail) { - Subject += email + ";"; - } - - RecepientEmail.Clear(); - SendEmailWithAttachments(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject : _subject), retVal, attachments); - } else { -#if (!DEBUG) - SendEmailWithAttachments(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachments); -#endif - } - } catch (Exception ex) { - throw ex; - } - - return retVal; - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, List RecepientEmail, string CC, string Subject, params string[] Args) { - string retVal = null; - - //reading the file - string FileContents = ReadEmailFile(EmailTemplateFile); - - string emailBody = FileContents; - - //setting formatting the string - retVal = string.Format(emailBody, Args); - - try { - //check if we are in debug mode or not. to send email - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { - foreach (string email in RecepientEmail) { - Subject += email + ";"; - } - RecepientEmail.Clear(); - SendEmail(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal); - } else { -#if (!DEBUG) - SendEmail(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal); -#endif - } - } catch (Exception ex) { - throw ex; - } - - return retVal; - } - - /// - /// - /// - /// - /// - /// - public void SendNotificationEmailToAdmin(string subject, string body, MailPriority importance) { - try { - System.Configuration.ConfigurationManager.RefreshSection("appSettings"); - - SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SMTP Server"]); - MailMessage msg = new MailMessage(); - - string toList = ConfigurationManager.AppSettings["Admin Notification Recepient"]; - msg.From = new MailAddress(ConfigurationManager.AppSettings["Notification Sender"]); ; - string[] recipients = toList.Split(','); - foreach (string recipient in recipients) - msg.To.Add(new MailAddress(recipient.Trim())); - - DateTime now = DateTime.Now; - - string temp = now.ToString() + " - " + body; - msg.Subject = subject; - msg.Body = temp; - msg.Priority = importance; - //#if(!DEBUG) - client.Send(msg); - //#endif - } catch (Exception ex) { - throw ex; - } - } - - public List GetTestRecipientsList() { - List r = new List(); - try { - string emails = ConfigurationManager.AppSettings["Test Email Recipients"]; - foreach (string s in emails.Split(';', ',')) { - if (!String.IsNullOrWhiteSpace(s)) - r.Add(s); - } - } catch { - r.Add("dhuang2@infineon.com"); - } - return r; + } catch (Exception ex) { + Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", + ex.ToString()); } } -} +#pragma warning restore IDE0060 // Remove unused parameter + + protected void SendEmailWithAttachment(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, string attachmentPath) { + // creating email message + MailMessage msg = new(); + msg.IsBodyHtml = true;// email body will allow html elements + + // setting the Sender Email ID + msg.From = new MailAddress(SenderEmail, SenderName); + + // adding the Recepient Email ID + msg.To.Add(Recep); + + // add CC email ids if supplied. + if (!string.IsNullOrEmpty(cc)) + msg.CC.Add(cc); + + //setting email subject and body + msg.Subject = email_title; + msg.Body = email_body; + msg.Attachments.Add(new Attachment(attachmentPath)); + + //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section + SmtpClient SmtpMail = new(); +#if(!DEBUG) + // sending the message. + SmtpMail.Send(msg); +#endif + } + +#pragma warning disable IDE0060 // Remove unused parameter + protected void SendEmail(string SenderEmail, string SenderName, List RecepientList, string cc, string email_title, string email_body) { + // creating email message + MailMessage msg = new(); + msg.IsBodyHtml = true;// email body will allow html elements + + // setting the Sender Email ID + //msg.From = new MailAddress(SenderEmail, SenderName); + msg.From = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval"); + // adding the Recepient Email ID + foreach (string recepient in RecepientList) { + msg.To.Add(recepient); + } + + // add CC email ids if supplied. + if (!string.IsNullOrEmpty(cc)) + msg.CC.Add(cc); + + //setting email subject and body + msg.Subject = email_title; + msg.Body = email_body; + + //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section + SmtpClient SmtpMail = new(); + + // sending the message. + try { + SmtpMail.Send(msg); + } catch (Exception ex) { + Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", + ex.ToString()); + } + } +#pragma warning restore IDE0060 // Remove unused parameter + + protected void SendEmailWithAttachment(string SenderEmail, string SenderName, List RecepientList, string cc, string email_title, string email_body, string attachmentPath) { + // creating email message + MailMessage msg = new(); + msg.IsBodyHtml = true;// email body will allow html elements + + // setting the Sender Email ID + msg.From = new MailAddress(SenderEmail, SenderName); + + // adding the Recepient Email ID + foreach (string recepient in RecepientList) { + if (recepient != null) + msg.To.Add(recepient); + } + + // add CC email ids if supplied. + if (!string.IsNullOrEmpty(cc)) + msg.CC.Add(cc); + + //setting email subject and body + msg.Subject = email_title; + msg.Body = email_body; + msg.Attachments.Add(new Attachment(attachmentPath)); + + //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section + SmtpClient SmtpMail = new(); + + // sending the message. + SmtpMail.Send(msg); + } + + protected void SendEmailWithAttachments(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, List attachments) { + // creating email message + MailMessage msg = new(); + msg.IsBodyHtml = true;// email body will allow html elements + + // setting the Sender Email ID + msg.From = new MailAddress(SenderEmail, SenderName); + + // adding the Recepient Email ID + msg.To.Add(Recep); + + // add CC email ids if supplied. + if (!string.IsNullOrEmpty(cc)) + msg.CC.Add(cc); + + //setting email subject and body + msg.Subject = email_title; + msg.Body = email_body; + foreach (string attachment in attachments) { + msg.Attachments.Add(new Attachment(attachment)); + } + + //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section + SmtpClient SmtpMail = new(); +#if(!DEBUG) + // sending the message. + SmtpMail.Send(msg); +#endif + } + + protected void SendEmailWithAttachments(string SenderEmail, string SenderName, List RecepientList, string cc, string email_title, string email_body, List attachments) { + // creating email message + MailMessage msg = new(); + msg.IsBodyHtml = true;// email body will allow html elements + + // setting the Sender Email ID + msg.From = new MailAddress(SenderEmail, SenderName); + + // adding the Recepient Email ID + foreach (string recepient in RecepientList) { + if (recepient != null) + msg.To.Add(recepient); + } + + // add CC email ids if supplied. + if (!string.IsNullOrEmpty(cc)) + msg.CC.Add(cc); + + //setting email subject and body + msg.Subject = email_title; + msg.Body = email_body; + + foreach (string attachment in attachments) { + msg.Attachments.Add(new Attachment(attachment)); + } + + //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section + SmtpClient SmtpMail = new(); + + // sending the message. + SmtpMail.Send(msg); + } + + /// + /// This function will send the email notification by reading the email template and substitute the arguments + /// + /// Email Template File + /// Sender Email + /// Sender Name + /// Recepient Email ID + /// CC IDs + /// EMail Subject + /// Arguments + /// String: Return the body of the email to be send + public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, params string[] Args) { + string retVal = null; + + //reading the file + string FileContents = ReadEmailFile(EmailTemplateFile); + + string emailBody = FileContents; + + //setting formatting the string + retVal = string.Format(emailBody, Args); + + try { + //check if we are in debug mode or not. to send email + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { + SendEmail(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? Subject + " for: " + RecepientEmail : _subject), retVal); + } else { +#if(!DEBUG) + SendEmail(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal); +#endif + } + } catch (Exception ex) { + throw; + } + + return retVal; + } + + /// + /// This function will send the email notification by reading the email template and substitute the arguments along with the attachments + /// + + public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, string attachmentPath, params string[] Args) { + string retVal = null; + + //reading the file + string FileContents = ReadEmailFile(EmailTemplateFile); + + string emailBody = FileContents; + + //setting formatting the string + retVal = string.Format(emailBody, Args); + + try { + //check if we are in debug mode or not. to send email + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { + SendEmailWithAttachment(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject + RecepientEmail : _subject), retVal, attachmentPath); + } else { +#if(!DEBUG) + SendEmailWithAttachment(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachmentPath); +#endif + } + } catch (Exception ex) { + throw; + } + + return retVal; + } + + public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, List RecepientEmail, string CC, string Subject, string attachmentPath, params string[] Args) { + string retVal = null; + + //reading the file + string FileContents = ReadEmailFile(EmailTemplateFile); + + string emailBody = FileContents; + + //setting formatting the string + retVal = string.Format(emailBody, Args); + + try { + //check if we are in debug mode or not. to send email + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { + foreach (string email in RecepientEmail) { + Subject += email + ";"; + } + + RecepientEmail.Clear(); + SendEmailWithAttachment(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject : _subject), retVal, attachmentPath); + } else { +#if (!DEBUG) + SendEmailWithAttachment(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachmentPath); +#endif + } + } catch (Exception ex) { + throw; + } + + return retVal; + } + + public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, List attachments, params string[] Args) { + string retVal = null; + + //reading the file + string FileContents = ReadEmailFile(EmailTemplateFile); + + string emailBody = FileContents; + + //setting formatting the string + retVal = string.Format(emailBody, Args); + + try { + //check if we are in debug mode or not. to send email + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { + SendEmailWithAttachments(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject + RecepientEmail : _subject), retVal, attachments); + } else { +#if(!DEBUG) + SendEmailWithAttachments(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachments); +#endif + } + } catch (Exception ex) { + throw; + } + + return retVal; + } + + public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, List RecepientEmail, string CC, string Subject, List attachments, params string[] Args) { + string retVal = null; + + //reading the file + string FileContents = ReadEmailFile(EmailTemplateFile); + + string emailBody = FileContents; + + //setting formatting the string + retVal = string.Format(emailBody, Args); + + try { + //check if we are in debug mode or not. to send email + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { + foreach (string email in RecepientEmail) { + Subject += email + ";"; + } + + RecepientEmail.Clear(); + SendEmailWithAttachments(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject : _subject), retVal, attachments); + } else { +#if (!DEBUG) + SendEmailWithAttachments(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachments); +#endif + } + } catch (Exception ex) { + throw; + } + + return retVal; + } + + public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, List RecepientEmail, string CC, string Subject, params string[] Args) { + string retVal = null; + + //reading the file + string FileContents = ReadEmailFile(EmailTemplateFile); + + string emailBody = FileContents; + + //setting formatting the string + retVal = string.Format(emailBody, Args); + + try { + //check if we are in debug mode or not. to send email + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { + foreach (string email in RecepientEmail) { + Subject += email + ";"; + } + RecepientEmail.Clear(); + SendEmail(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal); + } else { +#if (!DEBUG) + SendEmail(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal); +#endif + } + } catch (Exception ex) { + throw; + } + + return retVal; + } + + public void SendNotificationEmailToAdmin(string subject, string body, MailPriority importance) { + try { + SmtpClient client = new(_AppSettings.SMTPServer); + MailMessage msg = new(); + + string toList = _AppSettings.AdminNotificationRecepient; + msg.From = new MailAddress(_AppSettings.NotificationSender); + + string[] recipients = toList.Split(','); + foreach (string recipient in recipients) + msg.To.Add(new MailAddress(recipient.Trim())); + + DateTime now = DateTime.Now; + + string temp = now.ToString() + " - " + body; + msg.Subject = subject; + msg.Body = temp; + msg.Priority = importance; + //#if(!DEBUG) + client.Send(msg); + //#endif + } catch (Exception ex) { + throw; + } + } + + public List GetTestRecipientsList() { + List r = new(); + try { + string emails = _AppSettings.TestEmailRecipients; + foreach (string s in emails.Split(';', ',')) { + if (!string.IsNullOrWhiteSpace(s)) + r.Add(s); + } + } catch { + r.Add("dhuang2@infineon.com"); + } + return r; + } +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/ExcelData.cs b/Fab2ApprovalSystem/Misc/ExcelData.cs index 1431d93..f93a4bb 100644 --- a/Fab2ApprovalSystem/Misc/ExcelData.cs +++ b/Fab2ApprovalSystem/Misc/ExcelData.cs @@ -1,4 +1,7 @@ -using Excel; +#if !NET8 + +using Excel; + using System; using System.Collections.Generic; using System.Data; @@ -6,18 +9,15 @@ using System.IO; using System.Linq; using System.Web; -namespace Fab2ApprovalSystem.Misc -{ - public class ExcelData - { +namespace Fab2ApprovalSystem.Misc { + + public class ExcelData { string _path; - public ExcelData(string path) - { + public ExcelData(string path) { _path = path; } - public IExcelDataReader getExcelReader() - { + public IExcelDataReader getExcelReader() { // ExcelDataReader works with the binary Excel file, so it needs a FileStream // to get started. This is how we avoid dependencies on ACE or Interop: @@ -25,27 +25,21 @@ namespace Fab2ApprovalSystem.Misc // We return the interface, so that IExcelDataReader reader = null; - try - { - if (_path.EndsWith(".xls")) - { + try { + if (_path.EndsWith(".xls")) { reader = ExcelReaderFactory.CreateBinaryReader(stream); } - if (_path.EndsWith(".xlsx")) - { + if (_path.EndsWith(".xlsx")) { reader = ExcelReaderFactory.CreateOpenXmlReader(stream); } return reader; - } - catch (Exception) - { + } catch (Exception) { throw; } } - public class ExcelLotInfo - { + public class ExcelLotInfo { public string LotNo { get; set; } public string LotDispo { get; set; } } @@ -54,57 +48,44 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - public IEnumerable ReadData() - { + public IEnumerable ReadData() { var r = new List(); var excelData = new ExcelData(_path); var lots = excelData.getData().ToList(); int lotDispoColumnIndex = -1; - foreach (DataColumn col in lots[0].Table.Columns) - { - if (col.ColumnName.ToLower().Contains("dispo")) - { + foreach (DataColumn col in lots[0].Table.Columns) { + if (col.ColumnName.ToLower().Contains("dispo")) { lotDispoColumnIndex = col.Ordinal; break; } } - - foreach (var row in lots) - { + + foreach (var row in lots) { string temValue = row[0].ToString(); - if (temValue.Trim().Length > 0 && temValue.Trim().Length <= 10 ) - { - r.Add(new ExcelLotInfo() - { + if (temValue.Trim().Length > 0 && temValue.Trim().Length <= 10) { + r.Add(new ExcelLotInfo() { LotNo = row[0].ToString(), LotDispo = (lotDispoColumnIndex >= 0 ? row[lotDispoColumnIndex].ToString() : "") }); } - + } return r; } - - public IEnumerable ReadQDBFlagData() - { + public IEnumerable ReadQDBFlagData() { List s = new List(); // We return the interface, so that var excelData = new ExcelData(_path); //var albums = excelData.getData("Sheet1"); var lotNos = excelData.getData(); - foreach (var row in lotNos) - { + foreach (var row in lotNos) { string temValue = row[0].ToString(); - if (temValue.Trim().Length > 0 && temValue.Trim().Length == 9) - { - if (row[2].ToString().ToUpper() != "YES" && row[2].ToString().ToUpper() != "NO") - { + if (temValue.Trim().Length > 0 && temValue.Trim().Length == 9) { + if (row[2].ToString().ToUpper() != "YES" && row[2].ToString().ToUpper() != "NO") { throw new Exception("Invalid data in the file"); - } - else - { + } else { s.Add(row[0].ToString() + "~" + row[1] + "~" + row[2]); } } @@ -113,23 +94,12 @@ namespace Fab2ApprovalSystem.Misc return s; } - //public IEnumerable getData(string sheet, bool firstRowIsColumnNames = true) - //{ - // var reader = this.getExcelReader(); - // reader.IsFirstRowAsColumnNames = firstRowIsColumnNames; - // var workSheet = reader.AsDataSet().Tables[sheet]; - // var rows = from DataRow a in workSheet.Rows select a; - // return rows; - - //} - /// /// /// - /// + /// - public IEnumerable getData(bool firstRowIsColumnNames = true) - { + public IEnumerable getData(bool firstRowIsColumnNames = true) { var reader = this.getExcelReader(); reader.IsFirstRowAsColumnNames = firstRowIsColumnNames; var workSheet = reader.AsDataSet().Tables[0]; @@ -138,7 +108,7 @@ namespace Fab2ApprovalSystem.Misc } - - } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/FTPWrapper.cs b/Fab2ApprovalSystem/Misc/FTPWrapper.cs index 4c88502..3d5375f 100644 --- a/Fab2ApprovalSystem/Misc/FTPWrapper.cs +++ b/Fab2ApprovalSystem/Misc/FTPWrapper.cs @@ -1,59 +1,48 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.Misc -{ - class FTPWrapper - { - string m_OutputFile; - string m_DestinationFileName; - //Functions functions = new Functions(); - public FTPWrapper(string outputFile, string destinationFileName) - { - m_OutputFile = outputFile; - m_DestinationFileName = destinationFileName; +using Fab2ApprovalSystem.Models; +namespace Fab2ApprovalSystem.Misc; + +internal class FTPWrapper { + + private readonly string _OutputFile; + private readonly string _DestinationFileName; + private readonly AppSettings _AppSettings; + + public FTPWrapper(AppSettings appSettings, string outputFile, string destinationFileName) { + _OutputFile = outputFile; + _AppSettings = appSettings; + _DestinationFileName = destinationFileName; + } + + /// + /// + /// + public void FTPToSPN() { + FTP ftpLib = new(); + + //Connect to the FTP server + try { + ftpLib.Connect(_AppSettings.FTPServer, _AppSettings.FTPUser, _AppSettings.FTPPassword); + } catch (Exception ec) { + Functions.WriteEvent(_AppSettings, "Listener - ProcessFile(): FTP Connection Error " + _OutputFile + " - " + ec.Source + + ": " + ec.Message, System.Diagnostics.EventLogEntryType.Error); } - /// - /// - /// - public void FTPToSPN() - { - FTP ftpLib = new FTP(); - - //Connect to the FTP server - try - { - ftpLib.Connect(Functions.FTPServer(), Functions.FTPUser(), Functions.FTPPassword()); - } - catch (Exception ec) - { - Functions.WriteEvent("Listener - ProcessFile(): FTP Connection Error " + m_OutputFile + " - " + ec.Source + - ": " + ec.Message, System.Diagnostics.EventLogEntryType.Error); - } - - //Upload the file - try - { - int pct = 0; - ftpLib.OpenUpload(m_OutputFile, m_DestinationFileName); - while (ftpLib.DoUpload() > 0) - pct = (int)((ftpLib.BytesTotal * 100) / ftpLib.FileSize); - Functions.WriteEvent(m_OutputFile + " was sucessfully FTPed to SPN.", System.Diagnostics.EventLogEntryType.Information); - } - catch (Exception eu) - { - Functions.WriteEvent("MRB - FTPToSPN(): FTP Upload Error " + m_OutputFile + " - " + eu.Source + - ": " + eu.Message, System.Diagnostics.EventLogEntryType.Error); - throw new Exception(eu.Source + ": " + eu.Message); - } - - - + //Upload the file + try { + int pct = 0; + ftpLib.OpenUpload(_OutputFile, _DestinationFileName); + while (ftpLib.DoUpload() > 0) + pct = (int)((ftpLib.BytesTotal * 100) / ftpLib.FileSize); + Functions.WriteEvent(_AppSettings, _OutputFile + " was sucessfully FTPed to SPN.", System.Diagnostics.EventLogEntryType.Information); + } catch (Exception eu) { + Functions.WriteEvent(_AppSettings, "MRB - FTPToSPN(): FTP Upload Error " + _OutputFile + " - " + eu.Source + + ": " + eu.Message, System.Diagnostics.EventLogEntryType.Error); + throw new Exception(eu.Source + ": " + eu.Message); } } + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/Functions.cs b/Fab2ApprovalSystem/Misc/Functions.cs index c565e25..f13811c 100644 --- a/Fab2ApprovalSystem/Misc/Functions.cs +++ b/Fab2ApprovalSystem/Misc/Functions.cs @@ -1,261 +1,199 @@ +#pragma warning disable CS8019 + using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Web; + +#if !NET8 using System.Web.Security; +#endif + using System.IO; using System.Net.Mail; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; -namespace Fab2ApprovalSystem.Misc { - public static class Functions { - /// - /// Writes to the Application Event Log and sends an email notification if appropriate - /// - /// - /// - public static void WriteEvent(string logtext, System.Diagnostics.EventLogEntryType eventType) { - //#if(!DEBUG) - EmailNotification en = new EmailNotification(); - EventLog ev = new EventLog("Application"); - ev.Source = "Fab Approval System"; +#pragma warning restore CS8019 - try { - //Write to the Event Log - ev.WriteEntry(logtext, eventType); +using Fab2ApprovalSystem.Models; - ////Send an email notification if appropriate - ////Don't attempt to send an email if the error is pertaining to an email problem - if (!logtext.Contains("SendEmailNotification()")) { - //Only send email notifications for Error and Warning level events - if (eventType == System.Diagnostics.EventLogEntryType.Error) - en.SendNotificationEmailToAdmin(ev.Source + " - Error Notification", logtext, MailPriority.High); - //else if (eventType == System.Diagnostics.EventLogEntryType.Warning) - // SendEmailNotification(ErrorRecipient(), ev.Source + " Warning Event Logged", logtext, NORMAL_PRI); - } - } catch { - //throw; - } finally { - ev = null; +namespace Fab2ApprovalSystem.Misc; + +public static class Functions { + /// + /// Writes to the Application Event Log and sends an email notification if appropriate + /// + + public static void WriteEvent(AppSettings? appSettings, string logtext, EventLogEntryType eventType) { + //#if(!DEBUG) +#if !NET8 + EmailNotification? en = appSettings is null ? null : new EmailNotification(appSettings); +#endif + EventLog ev = new("Application"); + ev.Source = "Fab Approval System"; + + try { + //Write to the Event Log + ev.WriteEntry(logtext, eventType); + + ////Send an email notification if appropriate + ////Don't attempt to send an email if the error is pertaining to an email problem + if (!logtext.Contains("SendEmailNotification()")) { + //Only send email notifications for Error and Warning level events +#if !NET8 + if (appSettings is not null && eventType == System.Diagnostics.EventLogEntryType.Error) + en.SendNotificationEmailToAdmin(ev.Source + " - Error Notification", logtext, MailPriority.High); +#endif + //else if (eventType == System.Diagnostics.EventLogEntryType.Warning) + // SendEmailNotification(ErrorRecipient(), ev.Source + " Warning Event Logged", logtext, NORMAL_PRI); } - } - - /// - /// Returns the FTP Server Name - /// - /// - public static string FTPServer() { - ConfigurationManager.RefreshSection("appSettings"); - return ConfigurationManager.AppSettings["FTP Server"]; - } - - /// - /// Returns the FTP User Name - /// - /// - public static string FTPUser() { - ConfigurationManager.RefreshSection("appSettings"); - return ConfigurationManager.AppSettings["FTP User"]; - } - - /// - /// Returns the FTP Password - /// - /// - public static string FTPPassword() { - ConfigurationManager.RefreshSection("appSettings"); - return ConfigurationManager.AppSettings["FTP Password"]; - } - - /// - /// - /// - /// - public static string GetAttachmentFolder() { - ConfigurationManager.RefreshSection("appSettings"); - return ConfigurationManager.AppSettings["AttachmentFolder"]; - } - - /// - /// - /// - /// - /// - public static void CopyAttachments(int oldECNNumber, int newECNNumber) { - // The Name of the Upload component is "files" - string oldFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + oldECNNumber.ToString(); - string newFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + newECNNumber.ToString(); - - DirectoryInfo newdi = new DirectoryInfo(newFolderPath); - - if (!newdi.Exists) - newdi.Create(); - - FileInfo[] existingFiles = new DirectoryInfo(oldFolderPath).GetFiles(); - foreach (FileInfo file in existingFiles) { - if (!file.Name.Contains("ECNApprovalLog_" + oldECNNumber.ToString()) && !file.Name.Contains("ECNForm_" + oldECNNumber.ToString())) - //var fileName = Path.GetFileName(file.FullName); - file.CopyTo(Path.Combine(newFolderPath, file.Name)); - } - } - - /// - /// - /// - /// - /// - /// - public static bool NA_ADAuthenticate(string userID, string pwd) { - - string naContainer = ConfigurationManager.AppSettings["NAContainer"]; - string naDomain = ConfigurationManager.AppSettings["NADomain"]; - try { - PrincipalContext contextUser = new PrincipalContext(ContextType.Domain, - naDomain, - naContainer, - ContextOptions.Negotiate, userID, pwd); - - UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID); - if (null == up) - return false; - else - return true; - } catch { - return false; - } - } - - /// - /// - /// - /// - /// - /// - public static bool IFX_ADAuthenticate(string userID, string pwd) { - - string container = ConfigurationManager.AppSettings["IFXContainer"]; - string domain = ConfigurationManager.AppSettings["IFXDomain"]; - try { - PrincipalContext contextUser = new PrincipalContext(ContextType.Domain, - domain, - container, - ContextOptions.Negotiate, userID, pwd); - - UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID); - if (null == up) - return false; - else - return true; - } catch { - return false; - } - } - - public static string FTPSPNBatch() { - ConfigurationManager.RefreshSection("appSettings"); - return ConfigurationManager.AppSettings["FTPSPNBatchFileName"]; - } - - /// - /// - /// - /// - public static string FTPSPNBatch_Test() { - ConfigurationManager.RefreshSection("appSettings"); - return ConfigurationManager.AppSettings["FTPSPNBatchFileName_Test"]; - } - - /// - /// - /// - /// - /// - public static string CASectionMapper(GlobalVars.CASection casection) { - switch (casection) { - case GlobalVars.CASection.Main: - return "Main"; - - case GlobalVars.CASection.D1: - return "D1"; - - case GlobalVars.CASection.D2: - return "D2"; - - case GlobalVars.CASection.D3: - return "D3"; - - case GlobalVars.CASection.D4: - return "D4"; - - case GlobalVars.CASection.D5: - return "D5"; - - case GlobalVars.CASection.D6: - return "D6"; - - case GlobalVars.CASection.D7: - return "D7"; - - case GlobalVars.CASection.D8: - return "D8"; - case GlobalVars.CASection.CF: // CA Findings - return "CF"; - } - - return ""; - } - - public static string DocumentTypeMapper(GlobalVars.DocumentType docType) { - switch (docType) { - case GlobalVars.DocumentType.Audit: - return "Audit"; - case GlobalVars.DocumentType.ChangeControl: - return "ChangeControl"; - case GlobalVars.DocumentType.CorrectiveAction: - return "CorrectiveAction"; - case GlobalVars.DocumentType.ECN: - return "ECN"; - case GlobalVars.DocumentType.EECN: - return "EECN"; - case GlobalVars.DocumentType.LotDisposition: - return "LotDisposition"; - case GlobalVars.DocumentType.MRB: - return "MRB"; - case GlobalVars.DocumentType.TECNCancelledExpired: - return "TECNCancelledExpired"; - } - - return ""; - } - - /// - /// Converts the CA No to the C00000 format - /// - /// - /// - public static string ReturnCANoStringFormat(int caNo) { - string caNoString = ""; - if (caNo == 0) - return ""; - caNoString = "C" + caNo.ToString().PadLeft(5, '0'); - return caNoString; - } - - public static string ReturnAuditNoStringFormat(int auditNo) { - string auditNoString = ""; - if (auditNo == 0) - return ""; - auditNoString = "A" + auditNo.ToString().PadLeft(5, '0'); - return auditNoString; - } - - public static string ReturnPartsRequestNoStringFormat(int PRNumber) { - if (PRNumber == 0) - return ""; - return String.Format("PR{0:000000}", PRNumber); + } catch { + //throw; + } finally { + ev = null; } } -} + + public static void CopyAttachments(AppSettings appSettings, int oldECNNumber, int newECNNumber) { + // The Name of the Upload component is "files" + string oldFolderPath = appSettings.AttachmentFolder + "ECN\\" + oldECNNumber.ToString(); + string newFolderPath = appSettings.AttachmentFolder + "ECN\\" + newECNNumber.ToString(); + + DirectoryInfo newdi = new(newFolderPath); + + if (!newdi.Exists) + newdi.Create(); + + FileInfo[] existingFiles = new DirectoryInfo(oldFolderPath).GetFiles(); + foreach (FileInfo file in existingFiles) { + if (!file.Name.Contains("ECNApprovalLog_" + oldECNNumber.ToString()) && !file.Name.Contains("ECNForm_" + oldECNNumber.ToString())) + //var fileName = Path.GetFileName(file.FullName); + file.CopyTo(Path.Combine(newFolderPath, file.Name)); + } + } + + public static bool NA_ADAuthenticate(AppSettings appSettings, string userID, string pwd) { + string naContainer = appSettings.NAContainer; + string naDomain = appSettings.NADomain; + try { + PrincipalContext contextUser = new(ContextType.Domain, + naDomain, + naContainer, + ContextOptions.Negotiate, userID, pwd); + + UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID); + if (null == up) + return false; + else + return true; + } catch { + return false; + } + } + + public static bool IFX_ADAuthenticate(AppSettings appSettings, string userID, string pwd) { + string container = appSettings.IFXContainer; + string domain = appSettings.IFXDomain; + try { + PrincipalContext contextUser = new(ContextType.Domain, + domain, + container, + ContextOptions.Negotiate, userID, pwd); + + UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID); + if (null == up) + return false; + else + return true; + } catch { + return false; + } + } + + public static string CASectionMapper(GlobalVars.CASection casection) { + switch (casection) { + case GlobalVars.CASection.Main: + return "Main"; + + case GlobalVars.CASection.D1: + return "D1"; + + case GlobalVars.CASection.D2: + return "D2"; + + case GlobalVars.CASection.D3: + return "D3"; + + case GlobalVars.CASection.D4: + return "D4"; + + case GlobalVars.CASection.D5: + return "D5"; + + case GlobalVars.CASection.D6: + return "D6"; + + case GlobalVars.CASection.D7: + return "D7"; + + case GlobalVars.CASection.D8: + return "D8"; + case GlobalVars.CASection.CF: // CA Findings + return "CF"; + } + + return ""; + } + + public static string DocumentTypeMapper(GlobalVars.DocumentType docType) { + switch (docType) { + case GlobalVars.DocumentType.Audit: + return "Audit"; + case GlobalVars.DocumentType.ChangeControl: + return "ChangeControl"; + case GlobalVars.DocumentType.CorrectiveAction: + return "CorrectiveAction"; + case GlobalVars.DocumentType.ECN: + return "ECN"; + case GlobalVars.DocumentType.EECN: + return "EECN"; + case GlobalVars.DocumentType.LotDisposition: + return "LotDisposition"; + case GlobalVars.DocumentType.MRB: + return "MRB"; + case GlobalVars.DocumentType.TECNCancelledExpired: + return "TECNCancelledExpired"; + } + + return ""; + } + + /// + /// Converts the CA No to the C00000 format + /// + + public static string ReturnCANoStringFormat(int caNo) { + string caNoString = ""; + if (caNo == 0) + return ""; + caNoString = "C" + caNo.ToString().PadLeft(5, '0'); + return caNoString; + } + + public static string ReturnAuditNoStringFormat(int auditNo) { + string auditNoString = ""; + if (auditNo == 0) + return ""; + auditNoString = "A" + auditNo.ToString().PadLeft(5, '0'); + return auditNoString; + } + + public static string ReturnPartsRequestNoStringFormat(int PRNumber) { + if (PRNumber == 0) + return ""; + return string.Format("PR{0:000000}", PRNumber); + } +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/GlobalVars.cs b/Fab2ApprovalSystem/Misc/GlobalVars.cs index 84b1cd1..501e244 100644 --- a/Fab2ApprovalSystem/Misc/GlobalVars.cs +++ b/Fab2ApprovalSystem/Misc/GlobalVars.cs @@ -1,118 +1,101 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.Misc -{ - public class GlobalVars - { - - public int USER_ID; - public const string SESSION_USERNAME = "UserName"; - public const string ApplicationName = "LotDisposition"; - public const string SESSION_USERID = "UserID"; - public const string ECN_VIEW_OPTION = "ECN_ViewOption"; - public const string IS_ADMIN = "IsAdmin"; - public const string IS_MANAGER = "IsManager"; - public const string OOO = "OOO"; - public const string SUCCESS = "Success"; - public const string CAN_CREATE_PARTS_REQUEST = "CanCreatePartsRequest"; +namespace Fab2ApprovalSystem.Misc; - public static bool USER_ISADMIN = false; - public static bool IS_INFINEON_DOMAIN = false; - public static string hostURL = ""; - public static string DBConnection = "TEST"; - public static string DB_CONNECTION_STRING = ""; +#if !NET8 +public class GlobalVars { - public static string AttachmentUrl = ""; - public static string NDriveURL = ""; - public static string WSR_URL = ""; - public static string CA_BlankFormsLocation = ""; - public static string MesaTemplateFiles = "D:\\WebSites\\FabApprovalAttachments\\Template5Why"; + public int USER_ID; +#else +public static class GlobalVars { - //public static string DevWebSiteUrl = ""; - //public static string ProdWebSiteUrl = ""; + public static int USER_ID = 0; +#endif + public const string SESSION_USERNAME = "UserName"; + public const string ApplicationName = "LotDisposition"; + public const string SESSION_USERID = "UserID"; + public const string ECN_VIEW_OPTION = "ECN_ViewOption"; + public const string IS_ADMIN = "IsAdmin"; + public const string IS_MANAGER = "IsManager"; + public const string OOO = "OOO"; + public const string SUCCESS = "Success"; + public const string CAN_CREATE_PARTS_REQUEST = "CanCreatePartsRequest"; + public const string LOT_NO = "LotNo"; + public const string LOCATION = "Location"; - //public static string DevAttachmentUrl = ""; - //public static string ProdAttachmentUrl = ""; + public static AppSettings? AppSettings = null; + public static bool USER_ISADMIN = false; + public static bool IS_INFINEON_DOMAIN = false; + public static string hostURL = ""; + public static string DBConnection = "TEST"; + public static string DB_CONNECTION_STRING = ""; - public static string LOT_NO = "LotNo"; - public static string LOCATION = "Location"; - public static string SENDER_EMAIL = "MesaFabApproval@infineon.com"; - - - //public static List UserProfileDTO { get; set; } - public enum LotStatusOption - { - Release = 1, - Scrap, - NotAvailable, - M_Suffix, - Select_Wafers, - CloseToQDB, - SplitOffHold - - } - - - public enum ApprovalOption - { - Pending = 0, - Approved = 1, - Denied = 2, - Waiting = 3, //waiting on other approver to approve first - Skipped = 4, //set to this state if the original approval is no longer needed. - ReAssigned = 5, //set to this state if current approver got reassigned - Terminated = 6, //future use - Closed = 7, - Recalled = 8 - - } - - public enum WorkFLowStepNumber - { - Step1 = 1, - Step2, - Step3 - } - - public enum DocumentType - { - LotDisposition = 1, - MRB=2, - ECN=3, - EECN = 4, - TECNCancelledExpired = 5, - LotTraveler = 6, - ChangeControl = 7, - Audit = 8, - CorrectiveAction = 9, - PartsRequest = 10, - CorrectiveActionSection = 12 - } - - public enum TECNExpirationCancellation - { - Cancellation = 1, - Expiration = 2 - } - - public enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 }; - - - public enum NotificationType - { - WorkRequest = 1, - LotTraveler = 2 - } - - public enum CASection - { - Main, D1, D2, D3, D4, D5,D6, D7, D8, CF - } + public static string AttachmentUrl = ""; + public static string NDriveURL = ""; + public static string WSR_URL = ""; + public static string CA_BlankFormsLocation = ""; + public static string SENDER_EMAIL = "MesaFabApproval@infineon.com"; + public static string MesaTemplateFiles = "D:\\WebSites\\FabApprovalAttachments\\Template5Why"; + public enum LotStatusOption { + Release = 1, + Scrap, + NotAvailable, + M_Suffix, + Select_Wafers, + CloseToQDB, + SplitOffHold } -} + + public enum ApprovalOption { + Pending = 0, + Approved = 1, + Denied = 2, + Waiting = 3, //waiting on other approver to approve first + Skipped = 4, //set to this state if the original approval is no longer needed. + ReAssigned = 5, //set to this state if current approver got reassigned + Terminated = 6, //future use + Closed = 7, + Recalled = 8 + + } + + public enum WorkFLowStepNumber { + Step1 = 1, + Step2, + Step3 + } + + public enum DocumentType { + LotDisposition = 1, + MRB = 2, + ECN = 3, + EECN = 4, + TECNCancelledExpired = 5, + LotTraveler = 6, + ChangeControl = 7, + Audit = 8, + CorrectiveAction = 9, + PartsRequest = 10, + CorrectiveActionSection = 12 + } + + public enum TECNExpirationCancellation { + Cancellation = 1, + Expiration = 2 + } + + public enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 }; + + public enum NotificationType { + WorkRequest = 1, + LotTraveler = 2 + } + + public enum CASection { + Main, D1, D2, D3, D4, D5, D6, D7, D8, CF + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/LotNoTemplate.cs b/Fab2ApprovalSystem/Misc/LotNoTemplate.cs index 88f8cdb..107800b 100644 --- a/Fab2ApprovalSystem/Misc/LotNoTemplate.cs +++ b/Fab2ApprovalSystem/Misc/LotNoTemplate.cs @@ -1,12 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +namespace Fab2ApprovalSystem.Misc; + +public class LotNoTemplate { + + public string LotNo { get; set; } -namespace Fab2ApprovalSystem.Misc -{ - public class LotNoTemplate - { - public string LotNo { get; set; } - } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/SessionExpireFilterAttribute.cs b/Fab2ApprovalSystem/Misc/SessionExpireFilterAttribute.cs index 638c3f9..6e97b58 100644 --- a/Fab2ApprovalSystem/Misc/SessionExpireFilterAttribute.cs +++ b/Fab2ApprovalSystem/Misc/SessionExpireFilterAttribute.cs @@ -1,26 +1,22 @@ -using System; +#if !NET8 + +using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; +namespace Fab2ApprovalSystem.Misc { -namespace Fab2ApprovalSystem.Misc -{ - public class SessionExpireFilterAttribute : ActionFilterAttribute - { - public override void OnActionExecuting(ActionExecutingContext filterContext) - { + public class SessionExpireFilterAttribute : ActionFilterAttribute { + public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpSessionStateBase session = filterContext.HttpContext.Session; HttpContext ctx = HttpContext.Current; - // check if session is supported - - if (session[GlobalVars.SESSION_USERNAME] == null) - { + if (session[GlobalVars.SESSION_USERNAME] == null) { // check if a new session id was generated // this will force MVC to use the standard login redirect, enabling ReturnURL functionality @@ -30,10 +26,11 @@ namespace Fab2ApprovalSystem.Misc return; } - base.OnActionExecuting(filterContext); } } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/UserProfileDTO.cs b/Fab2ApprovalSystem/Misc/UserProfileDTO.cs index 46a9ae2..fde2b1c 100644 --- a/Fab2ApprovalSystem/Misc/UserProfileDTO.cs +++ b/Fab2ApprovalSystem/Misc/UserProfileDTO.cs @@ -1,27 +1,14 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.Misc -{ - //public class UserProfileDTO - //{ - // public int SysUserId { get; set; } - // public string UserName { get; set; } - // public string FullName { get; set; } - //} +namespace Fab2ApprovalSystem.Misc; - public static class CollectionExtensions - { - public static IEnumerable SetValue(this IEnumerable items, Action updateMethod) - { - foreach (T item in items) - { - updateMethod(item); - } - return items; +public static class CollectionExtensions { + + public static IEnumerable SetValue(this IEnumerable items, Action updateMethod) { + foreach (T item in items) { + updateMethod(item); } + return items; } - } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/Zipper.cs b/Fab2ApprovalSystem/Misc/Zipper.cs index 99c5ad3..3344ff3 100644 --- a/Fab2ApprovalSystem/Misc/Zipper.cs +++ b/Fab2ApprovalSystem/Misc/Zipper.cs @@ -1,99 +1,79 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using ICSharpCode.SharpZipLib.Core; -using ICSharpCode.SharpZipLib.Zip; using System.IO; +using ICSharpCode.SharpZipLib.Core; +using ICSharpCode.SharpZipLib.Zip; + +namespace Fab2ApprovalSystem.Misc; + +public class Zipper { -namespace Fab2ApprovalSystem.Misc -{ /// - /// + /// Compresses the files in the nominated folder, and creates a zip file on disk named as outPathname. /// - public class Zipper - { - - /// - /// Compresses the files in the nominated folder, and creates a zip file on disk named as outPathname. - /// - /// - /// - public void CreateZip(string outPathname, string folderName) { - // TODO Try and Catch block - Directory.CreateDirectory(Path.GetDirectoryName(outPathname)); + public void CreateZip(string outPathname, string folderName) { + // TODO Try and Catch block + Directory.CreateDirectory(Path.GetDirectoryName(outPathname)); - FileStream fsOut = File.Create(outPathname); - ZipOutputStream zipStream = new ZipOutputStream(fsOut); + FileStream fsOut = File.Create(outPathname); + ZipOutputStream zipStream = new(fsOut); - zipStream.SetLevel(3); //0-9, 9 being the highest level of compression + zipStream.SetLevel(3); //0-9, 9 being the highest level of compression - //zipStream.Password = password; // optional. Null is the same as not setting. Required if using AES. + //zipStream.Password = password; // optional. Null is the same as not setting. Required if using AES. - // This setting will strip the leading part of the folder path in the entries, to - // make the entries relative to the starting folder. - // To include the full path for each entry up to the drive root, assign folderOffset = 0. - int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1); + // This setting will strip the leading part of the folder path in the entries, to + // make the entries relative to the starting folder. + // To include the full path for each entry up to the drive root, assign folderOffset = 0. + int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1); - CompressFolder(folderName, zipStream, folderOffset); - - zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream - zipStream.Close(); - } - - /// - /// Recurses down the folder structure - /// - /// - /// - /// - private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset) - { - // TODO Try and Catch block - string[] files = Directory.GetFiles(path); - - foreach (string filename in files) - { - - FileInfo fi = new FileInfo(filename); - - string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder - entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction - ZipEntry newEntry = new ZipEntry(entryName); - newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity - - // Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256. - // A password on the ZipOutputStream is required if using AES. - // newEntry.AESKeySize = 256; - - // To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code, - // you need to do one of the following: Specify UseZip64.Off, or set the Size. - // If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either, - // but the zip will be in Zip64 format which not all utilities can understand. - // zipStream.UseZip64 = UseZip64.Off; - newEntry.Size = fi.Length; - - zipStream.PutNextEntry(newEntry); - - // Zip the file in buffered chunks - // the "using" will close the stream even if an exception occurs - byte[] buffer = new byte[4096]; - using (FileStream streamReader = File.OpenRead(filename)) - { - StreamUtils.Copy(streamReader, zipStream, buffer); - } - zipStream.CloseEntry(); - } - string[] folders = Directory.GetDirectories(path); - foreach (string folder in folders) - { - CompressFolder(folder, zipStream, folderOffset); - } - } - - + CompressFolder(folderName, zipStream, folderOffset); + zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream + zipStream.Close(); } -} + + /// + /// Recurses down the folder structure + /// + + private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset) { + // TODO Try and Catch block + string[] files = Directory.GetFiles(path); + + foreach (string filename in files) { + FileInfo fi = new(filename); + + string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder + entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction + ZipEntry newEntry = new(entryName); + newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity + + // Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256. + // A password on the ZipOutputStream is required if using AES. + // newEntry.AESKeySize = 256; + + // To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code, + // you need to do one of the following: Specify UseZip64.Off, or set the Size. + // If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either, + // but the zip will be in Zip64 format which not all utilities can understand. + // zipStream.UseZip64 = UseZip64.Off; + newEntry.Size = fi.Length; + + zipStream.PutNextEntry(newEntry); + + // Zip the file in buffered chunks + // the "using" will close the stream even if an exception occurs + byte[] buffer = new byte[4096]; + using (FileStream streamReader = File.OpenRead(filename)) { + StreamUtils.Copy(streamReader, zipStream, buffer); + } + zipStream.CloseEntry(); + } + string[] folders = Directory.GetDirectories(path); + foreach (string folder in folders) { + CompressFolder(folder, zipStream, folderOffset); + } + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/ftplib.cs b/Fab2ApprovalSystem/Misc/ftplib.cs index 4fb1a6d..d130a6d 100644 --- a/Fab2ApprovalSystem/Misc/ftplib.cs +++ b/Fab2ApprovalSystem/Misc/ftplib.cs @@ -1,238 +1,218 @@ using System; +using System.Collections; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; -using System.Collections; -namespace Fab2ApprovalSystem.Misc -{ - public class FTP +namespace Fab2ApprovalSystem.Misc; + +public class FTP { + #region Public Variables + + /// + /// IP address or hostname to connect to + /// + public string server; + + /// + /// Username to login as + /// + public string user; + + /// + /// Password for account + /// + public string pass; + + /// + /// Port number the FTP server is listening on + /// + public int port; + + /// + /// The timeout (miliseconds) for waiting on data to arrive + /// + public int timeout; + + #endregion + + #region Private Variables + + private string messages; // server messages + private string responseStr; // server response if the user wants it. + private bool passive_mode; // ####################################### + private long bytes_total; // upload/download info if the user wants it. + private long file_size; // gets set when an upload or download takes place + private Socket main_sock; + private IPEndPoint main_ipEndPoint; + private Socket listening_sock; + private Socket data_sock; + private IPEndPoint data_ipEndPoint; + private FileStream file; + private int response; + private string bucket; + + #endregion + + #region Constructors + /// + /// Constructor + /// + public FTP() { + server = null; + user = null; + pass = null; + port = 21; + passive_mode = true; // ####################################### + main_sock = null; + main_ipEndPoint = null; + listening_sock = null; + data_sock = null; + data_ipEndPoint = null; + file = null; + bucket = ""; + bytes_total = 0; + timeout = 10000; // 10 seconds + messages = ""; + } + /// + /// Constructor + /// + /// Server to connect to + /// Account to login as + /// Account password + public FTP(string server, string user, string pass) { + this.server = server; + this.user = user; + this.pass = pass; + port = 21; + passive_mode = true; // ####################################### + main_sock = null; + main_ipEndPoint = null; + listening_sock = null; + data_sock = null; + data_ipEndPoint = null; + file = null; + bucket = ""; + bytes_total = 0; + timeout = 10000; // 10 seconds + messages = ""; + } + /// + /// Constructor + /// + /// Server to connect to + /// Port server is listening on + /// Account to login as + /// Account password + public FTP(string server, int port, string user, string pass) { + this.server = server; + this.user = user; + this.pass = pass; + this.port = port; + passive_mode = true; // ####################################### + main_sock = null; + main_ipEndPoint = null; + listening_sock = null; + data_sock = null; + data_ipEndPoint = null; + file = null; + bucket = ""; + bytes_total = 0; + timeout = 10000; // 10 seconds + messages = ""; + } + + #endregion + + /// + /// Connection status to the server + /// + public bool IsConnected { + get { + if (main_sock != null) + return main_sock.Connected; + return false; + } + } + /// + /// Returns true if the message buffer has data in it + /// + public bool MessagesAvailable { + get { + if (messages.Length > 0) + return true; + return false; + } + } + /// + /// Server messages if any, buffer is cleared after you access this property + /// + public string Messages { + get { + string tmp = messages; + messages = ""; + return tmp; + } + } + /// + /// The response string from the last issued command + /// + public string ResponseString { + get { + return responseStr; + } + } + /// + /// The total number of bytes sent/recieved in a transfer + /// + public long BytesTotal // ####################################### { - #region Public Variables - - /// - /// IP address or hostname to connect to - /// - public string server; - /// - /// Username to login as - /// - public string user; - /// - /// Password for account - /// - public string pass; - /// - /// Port number the FTP server is listening on - /// - public int port; - /// - /// The timeout (miliseconds) for waiting on data to arrive - /// - public int timeout; - - #endregion - - #region Private Variables - - private string messages; // server messages - private string responseStr; // server response if the user wants it. - private bool passive_mode; // ####################################### - private long bytes_total; // upload/download info if the user wants it. - private long file_size; // gets set when an upload or download takes place - private Socket main_sock; - private IPEndPoint main_ipEndPoint; - private Socket listening_sock; - private Socket data_sock; - private IPEndPoint data_ipEndPoint; - private FileStream file; - private int response; - private string bucket; - - #endregion - - #region Constructors - /// - /// Constructor - /// - public FTP() - { - server = null; - user = null; - pass = null; - port = 21; - passive_mode = true; // ####################################### - main_sock = null; - main_ipEndPoint = null; - listening_sock = null; - data_sock = null; - data_ipEndPoint = null; - file = null; - bucket = ""; - bytes_total = 0; - timeout = 10000; // 10 seconds - messages = ""; + get { + return bytes_total; } - /// - /// Constructor - /// - /// Server to connect to - /// Account to login as - /// Account password - public FTP(string server, string user, string pass) - { - this.server = server; - this.user = user; - this.pass = pass; - port = 21; - passive_mode = true; // ####################################### - main_sock = null; - main_ipEndPoint = null; - listening_sock = null; - data_sock = null; - data_ipEndPoint = null; - file = null; - bucket = ""; - bytes_total = 0; - timeout = 10000; // 10 seconds - messages = ""; - } - /// - /// Constructor - /// - /// Server to connect to - /// Port server is listening on - /// Account to login as - /// Account password - public FTP(string server, int port, string user, string pass) - { - this.server = server; - this.user = user; - this.pass = pass; - this.port = port; - passive_mode = true; // ####################################### - main_sock = null; - main_ipEndPoint = null; - listening_sock = null; - data_sock = null; - data_ipEndPoint = null; - file = null; - bucket = ""; - bytes_total = 0; - timeout = 10000; // 10 seconds - messages = ""; + } + /// + /// The size of the file being downloaded/uploaded (Can possibly be 0 if no size is available) + /// + public long FileSize // ####################################### + { + get { + return file_size; } + } + /// + /// True: Passive mode [default] + /// False: Active Mode + /// + public bool PassiveMode // ####################################### + { + get => + passive_mode; + set => + passive_mode = value; + } - #endregion + private void Fail() { + Disconnect(); + throw new Exception(responseStr); + } - /// - /// Connection status to the server - /// - public bool IsConnected - { - get - { - if (main_sock != null) - return main_sock.Connected; - return false; - } - } - /// - /// Returns true if the message buffer has data in it - /// - public bool MessagesAvailable - { - get - { - if (messages.Length > 0) - return true; - return false; - } - } - /// - /// Server messages if any, buffer is cleared after you access this property - /// - public string Messages - { - get - { - string tmp = messages; - messages = ""; - return tmp; - } - } - /// - /// The response string from the last issued command - /// - public string ResponseString - { - get - { - return responseStr; - } - } - /// - /// The total number of bytes sent/recieved in a transfer - /// - public long BytesTotal // ####################################### - { - get - { - return bytes_total; - } - } - /// - /// The size of the file being downloaded/uploaded (Can possibly be 0 if no size is available) - /// - public long FileSize // ####################################### - { - get - { - return file_size; - } - } - /// - /// True: Passive mode [default] - /// False: Active Mode - /// - public bool PassiveMode // ####################################### - { - get - { - return passive_mode; - } - set - { - passive_mode = value; - } - } + private void SetBinaryMode(bool mode) { + if (mode) + SendCommand("TYPE I"); + else + SendCommand("TYPE A"); + ReadResponse(); + if (response != 200) + Fail(); + } - private void Fail() - { - Disconnect(); - throw new Exception(responseStr); - } - - - private void SetBinaryMode(bool mode) - { - if (mode) - SendCommand("TYPE I"); - else - SendCommand("TYPE A"); - - ReadResponse(); - if (response != 200) - Fail(); - } - - - private void SendCommand(string command) - { - Byte[] cmd = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray()); + private void SendCommand(string command) { + byte[] cmd = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray()); #if (FTP_DEBUG) if (command.Length > 3 && command.Substring(0, 4) == "PASS") @@ -241,970 +221,846 @@ namespace Fab2ApprovalSystem.Misc Console.WriteLine("\r" + command); #endif - main_sock.Send(cmd, cmd.Length, 0); - } + main_sock.Send(cmd, cmd.Length, 0); + } + private void FillBucket() { + byte[] bytes = new byte[512]; + long bytesgot; + int msecs_passed = 0; // ####################################### - private void FillBucket() - { - Byte[] bytes = new Byte[512]; - long bytesgot; - int msecs_passed = 0; // ####################################### - - while (main_sock.Available < 1) - { - System.Threading.Thread.Sleep(50); - msecs_passed += 50; - // this code is just a fail safe option - // so the code doesn't hang if there is - // no data comming. - if (msecs_passed > timeout) - { - Disconnect(); - throw new Exception("Timed out waiting on server to respond."); - } - } - - while (main_sock.Available > 0) - { - bytesgot = main_sock.Receive(bytes, 512, 0); - bucket += Encoding.ASCII.GetString(bytes, 0, (int)bytesgot); - // this may not be needed, gives any more data that hasn't arrived - // just yet a small chance to get there. - System.Threading.Thread.Sleep(50); + while (main_sock.Available < 1) { + System.Threading.Thread.Sleep(50); + msecs_passed += 50; + // this code is just a fail safe option + // so the code doesn't hang if there is + // no data comming. + if (msecs_passed > timeout) { + Disconnect(); + throw new Exception("Timed out waiting on server to respond."); } } + while (main_sock.Available > 0) { + bytesgot = main_sock.Receive(bytes, 512, 0); + bucket += Encoding.ASCII.GetString(bytes, 0, (int)bytesgot); + // this may not be needed, gives any more data that hasn't arrived + // just yet a small chance to get there. + System.Threading.Thread.Sleep(50); + } + } - private string GetLineFromBucket() - { - int i; - string buf = ""; + private string GetLineFromBucket() { + int i; + string buf = ""; - if ((i = bucket.IndexOf('\n')) < 0) - { - while (i < 0) - { - FillBucket(); - i = bucket.IndexOf('\n'); - } + if ((i = bucket.IndexOf('\n')) < 0) { + while (i < 0) { + FillBucket(); + i = bucket.IndexOf('\n'); } - - buf = bucket.Substring(0, i); - bucket = bucket.Substring(i + 1); - - return buf; } + buf = bucket.Substring(0, i); + bucket = bucket.Substring(i + 1); - // Any time a command is sent, use ReadResponse() to get the response - // from the server. The variable responseStr holds the entire string and - // the variable response holds the response number. - private void ReadResponse() - { - string buf; - messages = ""; + return buf; + } - while (true) - { - //buf = GetLineFromBucket(); - buf = GetLineFromBucket(); + // Any time a command is sent, use ReadResponse() to get the response + // from the server. The variable responseStr holds the entire string and + // the variable response holds the response number. + private void ReadResponse() { + string buf; + messages = ""; + + while (true) { + //buf = GetLineFromBucket(); + buf = GetLineFromBucket(); #if (FTP_DEBUG) Console.WriteLine(buf); #endif - // the server will respond with "000-Foo bar" on multi line responses - // "000 Foo bar" would be the last line it sent for that response. - // Better example: - // "000-This is a multiline response" - // "000-Foo bar" - // "000 This is the end of the response" - if (Regex.Match(buf, "^[0-9]+ ").Success) - { - responseStr = buf; - response = int.Parse(buf.Substring(0, 3)); - break; - } - else - messages += Regex.Replace(buf, "^[0-9]+-", "") + "\n"; - } + // the server will respond with "000-Foo bar" on multi line responses + // "000 Foo bar" would be the last line it sent for that response. + // Better example: + // "000-This is a multiline response" + // "000-Foo bar" + // "000 This is the end of the response" + if (Regex.Match(buf, "^[0-9]+ ").Success) { + responseStr = buf; + response = int.Parse(buf.Substring(0, 3)); + break; + } else + messages += Regex.Replace(buf, "^[0-9]+-", "") + "\n"; } + } - - // if you add code that needs a data socket, i.e. a PASV or PORT command required, - // call this function to do the dirty work. It sends the PASV or PORT command, - // parses out the port and ip info and opens the appropriate data socket - // for you. The socket variable is private Socket data_socket. Once you - // are done with it, be sure to call CloseDataSocket() - private void OpenDataSocket() + // if you add code that needs a data socket, i.e. a PASV or PORT command required, + // call this function to do the dirty work. It sends the PASV or PORT command, + // parses out the port and ip info and opens the appropriate data socket + // for you. The socket variable is private Socket data_socket. Once you + // are done with it, be sure to call CloseDataSocket() + private void OpenDataSocket() { + if (passive_mode) // ####################################### { - if (passive_mode) // ####################################### - { - string[] pasv; - string server; - int port; + string[] pasv; + string server; + int port; - Connect(); - SendCommand("PASV"); - ReadResponse(); - if (response != 227) - Fail(); + Connect(); + SendCommand("PASV"); + ReadResponse(); + if (response != 227) + Fail(); - try - { - int i1, i2; + try { + int i1, i2; - i1 = responseStr.IndexOf('(') + 1; - i2 = responseStr.IndexOf(')') - i1; - pasv = responseStr.Substring(i1, i2).Split(','); - } - catch (Exception) - { - Disconnect(); - throw new Exception("Malformed PASV response: " + responseStr); - } + i1 = responseStr.IndexOf('(') + 1; + i2 = responseStr.IndexOf(')') - i1; + pasv = responseStr.Substring(i1, i2).Split(','); + } catch (Exception) { + Disconnect(); + throw new Exception("Malformed PASV response: " + responseStr); + } - if (pasv.Length < 6) - { - Disconnect(); - throw new Exception("Malformed PASV response: " + responseStr); - } + if (pasv.Length < 6) { + Disconnect(); + throw new Exception("Malformed PASV response: " + responseStr); + } - server = String.Format("{0}.{1}.{2}.{3}", pasv[0], pasv[1], pasv[2], pasv[3]); - port = (int.Parse(pasv[4]) << 8) + int.Parse(pasv[5]); + server = string.Format("{0}.{1}.{2}.{3}", pasv[0], pasv[1], pasv[2], pasv[3]); + port = (int.Parse(pasv[4]) << 8) + int.Parse(pasv[5]); - try - { + try { #if (FTP_DEBUG) Console.WriteLine("Data socket: {0}:{1}", server, port); #endif - CloseDataSocket(); + CloseDataSocket(); #if (FTP_DEBUG) Console.WriteLine("Creating socket..."); #endif - data_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + data_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); #if (FTP_DEBUG) Console.WriteLine("Resolving host"); #endif - data_ipEndPoint = new IPEndPoint(Dns.GetHostByName(server).AddressList[0], port); - + data_ipEndPoint = new IPEndPoint(Dns.GetHostByName(server).AddressList[0], port); #if (FTP_DEBUG) Console.WriteLine("Connecting.."); #endif - data_sock.Connect(data_ipEndPoint); + data_sock.Connect(data_ipEndPoint); #if (FTP_DEBUG) Console.WriteLine("Connected."); #endif - } - catch (Exception ex) - { - throw new Exception("Failed to connect for data transfer: " + ex.Message); - } + } catch (Exception ex) { + throw new Exception("Failed to connect for data transfer: " + ex.Message); } - else // ####################################### - { - Connect(); + } else // ####################################### + { + Connect(); - try - { + try { #if (FTP_DEBUG) Console.WriteLine("Data socket (active mode)"); #endif - CloseDataSocket(); + CloseDataSocket(); #if (FTP_DEBUG) Console.WriteLine("Creating listening socket..."); #endif - listening_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + listening_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); #if (FTP_DEBUG) Console.WriteLine("Binding it to local address/port"); #endif - // for the PORT command we need to send our IP address; let's extract it - // from the LocalEndPoint of the main socket, that's already connected - string sLocAddr = main_sock.LocalEndPoint.ToString(); - int ix = sLocAddr.IndexOf(':'); - if (ix < 0) - { - throw new Exception("Failed to parse the local address: " + sLocAddr); - } - string sIPAddr = sLocAddr.Substring(0, ix); - // let the system automatically assign a port number (setting port = 0) - System.Net.IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(sIPAddr), 0); + // for the PORT command we need to send our IP address; let's extract it + // from the LocalEndPoint of the main socket, that's already connected + string sLocAddr = main_sock.LocalEndPoint.ToString(); + int ix = sLocAddr.IndexOf(':'); + if (ix < 0) { + throw new Exception("Failed to parse the local address: " + sLocAddr); + } + string sIPAddr = sLocAddr.Substring(0, ix); + // let the system automatically assign a port number (setting port = 0) + IPEndPoint localEP = new(IPAddress.Parse(sIPAddr), 0); - listening_sock.Bind(localEP); - sLocAddr = listening_sock.LocalEndPoint.ToString(); - ix = sLocAddr.IndexOf(':'); - if (ix < 0) - { - throw new Exception("Failed to parse the local address: " + sLocAddr); - } - int nPort = int.Parse(sLocAddr.Substring(ix + 1)); + listening_sock.Bind(localEP); + sLocAddr = listening_sock.LocalEndPoint.ToString(); + ix = sLocAddr.IndexOf(':'); + if (ix < 0) { + throw new Exception("Failed to parse the local address: " + sLocAddr); + } + int nPort = int.Parse(sLocAddr.Substring(ix + 1)); #if (FTP_DEBUG) Console.WriteLine("Listening on {0}:{1}", sIPAddr, nPort); #endif - // start to listen for a connection request from the host (note that - // Listen is not blocking) and send the PORT command - listening_sock.Listen(1); - string sPortCmd = string.Format("PORT {0},{1},{2}", - sIPAddr.Replace('.', ','), - nPort / 256, nPort % 256); - SendCommand(sPortCmd); - ReadResponse(); - if (response != 200) - Fail(); - } - catch (Exception ex) - { - throw new Exception("Failed to connect for data transfer: " + ex.Message); - } - } - } - - - private void ConnectDataSocket() // ####################################### - { - if (data_sock != null) // already connected (always so if passive mode) - return; - - try - { -#if (FTP_DEBUG) - Console.WriteLine("Accepting the data connection."); -#endif - data_sock = listening_sock.Accept(); // Accept is blocking - listening_sock.Close(); - listening_sock = null; - - if (data_sock == null) - { - throw new Exception("Winsock error: " + - Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error())); - } -#if (FTP_DEBUG) - Console.WriteLine("Connected."); -#endif - } - catch (Exception ex) - { + // start to listen for a connection request from the host (note that + // Listen is not blocking) and send the PORT command + listening_sock.Listen(1); + string sPortCmd = string.Format("PORT {0},{1},{2}", + sIPAddr.Replace('.', ','), + nPort / 256, nPort % 256); + SendCommand(sPortCmd); + ReadResponse(); + if (response != 200) + Fail(); + } catch (Exception ex) { throw new Exception("Failed to connect for data transfer: " + ex.Message); } } + } + private void ConnectDataSocket() // ####################################### + { + if (data_sock != null) // already connected (always so if passive mode) + return; - private void CloseDataSocket() - { + try { +#if (FTP_DEBUG) + Console.WriteLine("Accepting the data connection."); +#endif + data_sock = listening_sock.Accept(); // Accept is blocking + listening_sock.Close(); + listening_sock = null; + + if (data_sock == null) { + throw new Exception("Winsock error: " + + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error())); + } +#if (FTP_DEBUG) + Console.WriteLine("Connected."); +#endif + } catch (Exception ex) { + throw new Exception("Failed to connect for data transfer: " + ex.Message); + } + } + + private void CloseDataSocket() { #if (FTP_DEBUG) Console.WriteLine("Attempting to close data channel socket..."); #endif - if (data_sock != null) - { - if (data_sock.Connected) - { + if (data_sock != null) { + if (data_sock.Connected) { #if (FTP_DEBUG) Console.WriteLine("Closing data channel socket!"); #endif - data_sock.Close(); + data_sock.Close(); #if (FTP_DEBUG) Console.WriteLine("Data channel socket closed!"); #endif + } + data_sock = null; + } + + data_ipEndPoint = null; + } + /// + /// Closes all connections to the ftp server + /// + public void Disconnect() { + CloseDataSocket(); + + if (main_sock != null) { + if (main_sock.Connected) { + SendCommand("QUIT"); + main_sock.Close(); + } + main_sock = null; + } + + if (file != null) + file.Close(); + + main_ipEndPoint = null; + file = null; + } + /// + /// Connect to a ftp server + /// + /// IP or hostname of the server to connect to + /// Port number the server is listening on + /// Account name to login as + /// Password for the account specified + public void Connect(string server, int port, string user, string pass) { + this.server = server; + this.user = user; + this.pass = pass; + this.port = port; + + Connect(); + } + /// + /// Connect to a ftp server + /// + /// IP or hostname of the server to connect to + /// Account name to login as + /// Password for the account specified + public void Connect(string server, string user, string pass) { + this.server = server; + this.user = user; + this.pass = pass; + + Connect(); + } + /// + /// Connect to an ftp server + /// + public void Connect() { + if (server == null) + throw new Exception("No server has been set."); + if (user == null) + throw new Exception("No username has been set."); + + if (main_sock != null) + if (main_sock.Connected) + return; + + main_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + main_ipEndPoint = new IPEndPoint(Dns.GetHostByName(server).AddressList[0], port); + + try { + main_sock.Connect(main_ipEndPoint); + } catch (Exception ex) { + throw new Exception(ex.Message); + } + + ReadResponse(); + if (response != 220) + Fail(); + + SendCommand("USER " + user); + ReadResponse(); + + switch (response) { + case 331: + if (pass == null) { + Disconnect(); + throw new Exception("No password has been set."); } - data_sock = null; - } - - data_ipEndPoint = null; - } - /// - /// Closes all connections to the ftp server - /// - public void Disconnect() - { - CloseDataSocket(); - - if (main_sock != null) - { - if (main_sock.Connected) - { - SendCommand("QUIT"); - main_sock.Close(); - } - main_sock = null; - } - - if (file != null) - file.Close(); - - main_ipEndPoint = null; - file = null; - } - /// - /// Connect to a ftp server - /// - /// IP or hostname of the server to connect to - /// Port number the server is listening on - /// Account name to login as - /// Password for the account specified - public void Connect(string server, int port, string user, string pass) - { - this.server = server; - this.user = user; - this.pass = pass; - this.port = port; - - Connect(); - } - /// - /// Connect to a ftp server - /// - /// IP or hostname of the server to connect to - /// Account name to login as - /// Password for the account specified - public void Connect(string server, string user, string pass) - { - this.server = server; - this.user = user; - this.pass = pass; - - Connect(); - } - /// - /// Connect to an ftp server - /// - public void Connect() - { - if (server == null) - throw new Exception("No server has been set."); - if (user == null) - throw new Exception("No username has been set."); - - if (main_sock != null) - if (main_sock.Connected) - return; - - main_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - main_ipEndPoint = new IPEndPoint(Dns.GetHostByName(server).AddressList[0], port); - - try - { - main_sock.Connect(main_ipEndPoint); - } - catch (Exception ex) - { - throw new Exception(ex.Message); - } - - ReadResponse(); - if (response != 220) - Fail(); - - SendCommand("USER " + user); - ReadResponse(); - - switch (response) - { - case 331: - if (pass == null) - { - Disconnect(); - throw new Exception("No password has been set."); - } - SendCommand("PASS " + pass); - ReadResponse(); - if (response != 230) - Fail(); - break; - case 230: - break; - } - - return; - } - /// - /// Retrieves a list of files from the ftp server - /// - /// An ArrayList of files - public ArrayList List() - { - Byte[] bytes = new Byte[512]; - string file_list = ""; - long bytesgot = 0; - int msecs_passed = 0; - ArrayList list = new ArrayList(); - - Connect(); - OpenDataSocket(); - SendCommand("LIST"); - ReadResponse(); - - //FILIPE MADUREIRA. - //Added response 125 - switch (response) - { - case 125: - case 150: - break; - default: - CloseDataSocket(); - throw new Exception(responseStr); - } - ConnectDataSocket(); // ####################################### - - while (data_sock.Available < 1) - { - System.Threading.Thread.Sleep(50); - msecs_passed += 50; - // this code is just a fail safe option - // so the code doesn't hang if there is - // no data comming. - if (msecs_passed > (timeout / 10)) - { - //CloseDataSocket(); - //throw new Exception("Timed out waiting on server to respond."); - - //FILIPE MADUREIRA. - //If there are no files to list it gives timeout. - //So I wait less time and if no data is received, means that there are no files - break;//Maybe there are no files - } - } - - while (data_sock.Available > 0) - { - bytesgot = data_sock.Receive(bytes, bytes.Length, 0); - file_list += Encoding.ASCII.GetString(bytes, 0, (int)bytesgot); - System.Threading.Thread.Sleep(50); // *shrug*, sometimes there is data comming but it isn't there yet. - } - - CloseDataSocket(); - - ReadResponse(); - if (response != 226) - throw new Exception(responseStr); - - foreach (string f in file_list.Split('\n')) - { - if (f.Length > 0 && !Regex.Match(f, "^total").Success) - list.Add(f.Substring(0, f.Length - 1)); - } - - return list; - } - /// - /// Gets a file list only - /// - /// ArrayList of files only - public ArrayList ListFiles() - { - ArrayList list = new ArrayList(); - - foreach (string f in List()) - { - //FILIPE MADUREIRA - //In Windows servers it is identified by - if ((f.Length > 0)) - { - if ((f[0] != 'd') && (f.ToUpper().IndexOf("") < 0)) - list.Add(f); - } - } - - return list; - } - /// - /// Gets a directory list only - /// - /// ArrayList of directories only - public ArrayList ListDirectories() - { - ArrayList list = new ArrayList(); - - foreach (string f in List()) - { - //FILIPE MADUREIRA - //In Windows servers it is identified by - if (f.Length > 0) - { - if ((f[0] == 'd') || (f.ToUpper().IndexOf("") >= 0)) - list.Add(f); - } - } - - return list; - } - /// - /// Returns the 'Raw' DateInformation in ftp format. (YYYYMMDDhhmmss). Use GetFileDate to return a DateTime object as a better option. - /// - /// Remote FileName to Query - /// Returns the 'Raw' DateInformation in ftp format - public string GetFileDateRaw(string fileName) - { - Connect(); - - SendCommand("MDTM " + fileName); - ReadResponse(); - if (response != 213) - { -#if (FTP_DEBUG) - Console.Write("\r" + responseStr); -#endif - throw new Exception(responseStr); - } - - return (this.responseStr.Substring(4)); - } - /// - /// GetFileDate will query the ftp server for the date of the remote file. - /// - /// Remote FileName to Query - /// DateTime of the Input FileName - public DateTime GetFileDate(string fileName) - { - return ConvertFTPDateToDateTime(GetFileDateRaw(fileName)); - } - - private DateTime ConvertFTPDateToDateTime(string input) - { - if (input.Length < 14) - throw new ArgumentException("Input Value for ConvertFTPDateToDateTime method was too short."); - - //YYYYMMDDhhmmss": - int year = Convert.ToInt16(input.Substring(0, 4)); - int month = Convert.ToInt16(input.Substring(4, 2)); - int day = Convert.ToInt16(input.Substring(6, 2)); - int hour = Convert.ToInt16(input.Substring(8, 2)); - int min = Convert.ToInt16(input.Substring(10, 2)); - int sec = Convert.ToInt16(input.Substring(12, 2)); - - return new DateTime(year, month, day, hour, min, sec); - } - /// - /// Get the working directory on the ftp server - /// - /// The working directory - public string GetWorkingDirectory() - { - //PWD - print working directory - Connect(); - SendCommand("PWD"); - ReadResponse(); - - if (response != 257) - throw new Exception(responseStr); - - string pwd; - try - { - pwd = responseStr.Substring(responseStr.IndexOf("\"", 0) + 1);//5); - pwd = pwd.Substring(0, pwd.LastIndexOf("\"")); - pwd = pwd.Replace("\"\"", "\""); // directories with quotes in the name come out as "" from the server - } - catch (Exception ex) - { - throw new Exception("Uhandled PWD response: " + ex.Message); - } - - return pwd; - } - /// - /// Change to another directory on the ftp server - /// - /// Directory to change to - public void ChangeDir(string path) - { - Connect(); - SendCommand("CWD " + path); - ReadResponse(); - if (response != 250) - { -#if (FTP_DEBUG) - Console.Write("\r" + responseStr); -#endif - throw new Exception(responseStr); - } - } - /// - /// Create a directory on the ftp server - /// - /// Directory to create - public void MakeDir(string dir) - { - Connect(); - SendCommand("MKD " + dir); - ReadResponse(); - - switch (response) - { - case 257: - case 250: - break; - default: -#if (FTP_DEBUG) - Console.Write("\r" + responseStr); -#endif - throw new Exception(responseStr); - } - } - /// - /// Remove a directory from the ftp server - /// - /// Name of directory to remove - public void RemoveDir(string dir) - { - Connect(); - SendCommand("RMD " + dir); - ReadResponse(); - if (response != 250) - { -#if (FTP_DEBUG) - Console.Write("\r" + responseStr); -#endif - throw new Exception(responseStr); - } - } - /// - /// Remove a file from the ftp server - /// - /// Name of the file to delete - public void RemoveFile(string filename) - { - Connect(); - SendCommand("DELE " + filename); - ReadResponse(); - if (response != 250) - { -#if (FTP_DEBUG) - Console.Write("\r" + responseStr); -#endif - throw new Exception(responseStr); - } - } - /// - /// Rename a file on the ftp server - /// - /// Old file name - /// New file name - public void RenameFile(string oldfilename, string newfilename) // ####################################### - { - Connect(); - SendCommand("RNFR " + oldfilename); - ReadResponse(); - if (response != 350) - { -#if (FTP_DEBUG) - Console.Write("\r" + responseStr); -#endif - throw new Exception(responseStr); - } - else - { - SendCommand("RNTO " + newfilename); + SendCommand("PASS " + pass); ReadResponse(); - if (response != 250) - { + if (response != 230) + Fail(); + break; + case 230: + break; + } + + return; + } + /// + /// Retrieves a list of files from the ftp server + /// + /// An ArrayList of files + public ArrayList List() { + byte[] bytes = new byte[512]; + string file_list = ""; + long bytesgot = 0; + int msecs_passed = 0; + ArrayList list = new(); + + Connect(); + OpenDataSocket(); + SendCommand("LIST"); + ReadResponse(); + + //FILIPE MADUREIRA. + //Added response 125 + switch (response) { + case 125: + case 150: + break; + default: + CloseDataSocket(); + throw new Exception(responseStr); + } + ConnectDataSocket(); // ####################################### + + while (data_sock.Available < 1) { + System.Threading.Thread.Sleep(50); + msecs_passed += 50; + // this code is just a fail safe option + // so the code doesn't hang if there is + // no data comming. + if (msecs_passed > (timeout / 10)) { + //CloseDataSocket(); + //throw new Exception("Timed out waiting on server to respond."); + + //FILIPE MADUREIRA. + //If there are no files to list it gives timeout. + //So I wait less time and if no data is received, means that there are no files + break;//Maybe there are no files + } + } + + while (data_sock.Available > 0) { + bytesgot = data_sock.Receive(bytes, bytes.Length, 0); + file_list += Encoding.ASCII.GetString(bytes, 0, (int)bytesgot); + System.Threading.Thread.Sleep(50); // *shrug*, sometimes there is data comming but it isn't there yet. + } + + CloseDataSocket(); + + ReadResponse(); + if (response != 226) + throw new Exception(responseStr); + + foreach (string f in file_list.Split('\n')) { + if (f.Length > 0 && !Regex.Match(f, "^total").Success) + list.Add(f.Substring(0, f.Length - 1)); + } + + return list; + } + /// + /// Gets a file list only + /// + /// ArrayList of files only + public ArrayList ListFiles() { + ArrayList list = new(); + + foreach (string f in List()) { + //FILIPE MADUREIRA + //In Windows servers it is identified by + if ((f.Length > 0)) { + if ((f[0] != 'd') && (f.ToUpper().IndexOf("") < 0)) + list.Add(f); + } + } + + return list; + } + /// + /// Gets a directory list only + /// + /// ArrayList of directories only + public ArrayList ListDirectories() { + ArrayList list = new(); + + foreach (string f in List()) { + //FILIPE MADUREIRA + //In Windows servers it is identified by + if (f.Length > 0) { + if ((f[0] == 'd') || (f.ToUpper().IndexOf("") >= 0)) + list.Add(f); + } + } + + return list; + } + /// + /// Returns the 'Raw' DateInformation in ftp format. (YYYYMMDDhhmmss). Use GetFileDate to return a DateTime object as a better option. + /// + /// Remote FileName to Query + /// Returns the 'Raw' DateInformation in ftp format + public string GetFileDateRaw(string fileName) { + Connect(); + + SendCommand("MDTM " + fileName); + ReadResponse(); + if (response != 213) { +#if (FTP_DEBUG) + Console.Write("\r" + responseStr); +#endif + throw new Exception(responseStr); + } + + return (responseStr.Substring(4)); + } + /// + /// GetFileDate will query the ftp server for the date of the remote file. + /// + /// Remote FileName to Query + /// DateTime of the Input FileName + public DateTime GetFileDate(string fileName) => + ConvertFTPDateToDateTime(GetFileDateRaw(fileName)); + + private DateTime ConvertFTPDateToDateTime(string input) { + if (input.Length < 14) + throw new ArgumentException("Input Value for ConvertFTPDateToDateTime method was too short."); + + //YYYYMMDDhhmmss": + int year = Convert.ToInt16(input.Substring(0, 4)); + int month = Convert.ToInt16(input.Substring(4, 2)); + int day = Convert.ToInt16(input.Substring(6, 2)); + int hour = Convert.ToInt16(input.Substring(8, 2)); + int min = Convert.ToInt16(input.Substring(10, 2)); + int sec = Convert.ToInt16(input.Substring(12, 2)); + + return new DateTime(year, month, day, hour, min, sec); + } + /// + /// Get the working directory on the ftp server + /// + /// The working directory + public string GetWorkingDirectory() { + //PWD - print working directory + Connect(); + SendCommand("PWD"); + ReadResponse(); + + if (response != 257) + throw new Exception(responseStr); + + string pwd; + try { + pwd = responseStr.Substring(responseStr.IndexOf("\"", 0) + 1);//5); + pwd = pwd.Substring(0, pwd.LastIndexOf("\"")); + pwd = pwd.Replace("\"\"", "\""); // directories with quotes in the name come out as "" from the server + } catch (Exception ex) { + throw new Exception("Uhandled PWD response: " + ex.Message); + } + + return pwd; + } + /// + /// Change to another directory on the ftp server + /// + /// Directory to change to + public void ChangeDir(string path) { + Connect(); + SendCommand("CWD " + path); + ReadResponse(); + if (response != 250) { +#if (FTP_DEBUG) + Console.Write("\r" + responseStr); +#endif + throw new Exception(responseStr); + } + } + /// + /// Create a directory on the ftp server + /// + /// Directory to create + public void MakeDir(string dir) { + Connect(); + SendCommand("MKD " + dir); + ReadResponse(); + + switch (response) { + case 257: + case 250: + break; + default: +#if (FTP_DEBUG) + Console.Write("\r" + responseStr); +#endif + throw new Exception(responseStr); + } + } + /// + /// Remove a directory from the ftp server + /// + /// Name of directory to remove + public void RemoveDir(string dir) { + Connect(); + SendCommand("RMD " + dir); + ReadResponse(); + if (response != 250) { +#if (FTP_DEBUG) + Console.Write("\r" + responseStr); +#endif + throw new Exception(responseStr); + } + } + /// + /// Remove a file from the ftp server + /// + /// Name of the file to delete + public void RemoveFile(string filename) { + Connect(); + SendCommand("DELE " + filename); + ReadResponse(); + if (response != 250) { +#if (FTP_DEBUG) + Console.Write("\r" + responseStr); +#endif + throw new Exception(responseStr); + } + } + /// + /// Rename a file on the ftp server + /// + /// Old file name + /// New file name + public void RenameFile(string oldfilename, string newfilename) // ####################################### + { + Connect(); + SendCommand("RNFR " + oldfilename); + ReadResponse(); + if (response != 350) { +#if (FTP_DEBUG) + Console.Write("\r" + responseStr); +#endif + throw new Exception(responseStr); + } else { + SendCommand("RNTO " + newfilename); + ReadResponse(); + if (response != 250) { #if (FTP_DEBUG) Console.Write("\r" + responseStr); #endif - throw new Exception(responseStr); - } + throw new Exception(responseStr); } } - /// - /// Get the size of a file (Provided the ftp server supports it) - /// - /// Name of file - /// The size of the file specified by filename - public long GetFileSize(string filename) - { - Connect(); - SendCommand("SIZE " + filename); - ReadResponse(); - if (response != 213) - { + } + /// + /// Get the size of a file (Provided the ftp server supports it) + /// + /// Name of file + /// The size of the file specified by filename + public long GetFileSize(string filename) { + Connect(); + SendCommand("SIZE " + filename); + ReadResponse(); + if (response != 213) { #if (FTP_DEBUG) Console.Write("\r" + responseStr); #endif + throw new Exception(responseStr); + } + + return long.Parse(responseStr.Substring(4)); + } + /// + /// Open an upload with no resume if it already exists + /// + /// File to upload + public void OpenUpload(string filename) => + OpenUpload(filename, filename, false); + + /// + /// Open an upload with no resume if it already exists + /// + /// Local file to upload (Can include path to file) + /// Filename to store file as on ftp server + public void OpenUpload(string filename, string remotefilename) => + OpenUpload(filename, remotefilename, false); + + /// + /// Open an upload with resume support + /// + /// Local file to upload (Can include path to file) + /// Attempt resume if exists + public void OpenUpload(string filename, bool resume) => + OpenUpload(filename, filename, resume); + + /// + /// Open an upload with resume support + /// + /// Local file to upload (Can include path to file) + /// Filename to store file as on ftp server + /// Attempt resume if exists + public void OpenUpload(string filename, string remote_filename, bool resume) { + Connect(); + SetBinaryMode(true); + OpenDataSocket(); + + bytes_total = 0; + + try { + file = new FileStream(filename, FileMode.Open); + } catch (Exception ex) { + file = null; + throw new Exception(ex.Message); + } + + file_size = file.Length; + + if (resume) { + long size = GetFileSize(remote_filename); + SendCommand("REST " + size); + ReadResponse(); + if (response == 350) + file.Seek(size, SeekOrigin.Begin); + } + + SendCommand("STOR " + remote_filename); + ReadResponse(); + + switch (response) { + case 125: + case 150: + break; + default: + file.Close(); + file = null; throw new Exception(responseStr); - } + } + ConnectDataSocket(); // ####################################### - return Int64.Parse(responseStr.Substring(4)); - } - /// - /// Open an upload with no resume if it already exists - /// - /// File to upload - public void OpenUpload(string filename) - { - OpenUpload(filename, filename, false); - } - /// - /// Open an upload with no resume if it already exists - /// - /// Local file to upload (Can include path to file) - /// Filename to store file as on ftp server - public void OpenUpload(string filename, string remotefilename) - { - OpenUpload(filename, remotefilename, false); - } - /// - /// Open an upload with resume support - /// - /// Local file to upload (Can include path to file) - /// Attempt resume if exists - public void OpenUpload(string filename, bool resume) - { - OpenUpload(filename, filename, resume); - } - /// - /// Open an upload with resume support - /// - /// Local file to upload (Can include path to file) - /// Filename to store file as on ftp server - /// Attempt resume if exists - public void OpenUpload(string filename, string remote_filename, bool resume) - { - Connect(); - SetBinaryMode(true); - OpenDataSocket(); + return; + } + /// + /// Download a file with no resume + /// + /// Remote file name + public void OpenDownload(string filename) => + OpenDownload(filename, filename, false); - bytes_total = 0; + /// + /// Download a file with optional resume + /// + /// Remote file name + /// Attempt resume if file exists + public void OpenDownload(string filename, bool resume) => + OpenDownload(filename, filename, resume); - try - { - file = new FileStream(filename, FileMode.Open); - } - catch (Exception ex) - { + /// + /// Download a file with no attempt to resume + /// + /// Remote filename + /// Local filename (Can include path to file) + public void OpenDownload(string filename, string localfilename) => + OpenDownload(filename, localfilename, false); + + /// + /// Open a file for download + /// + /// The name of the file on the FTP server + /// The name of the file to save as (Can include path to file) + /// Attempt resume if file exists + public void OpenDownload(string remote_filename, string local_filename, bool resume) { + Connect(); + SetBinaryMode(true); + + bytes_total = 0; + + try { + file_size = GetFileSize(remote_filename); + } catch { + file_size = 0; + } + + if (resume && File.Exists(local_filename)) { + try { + file = new FileStream(local_filename, FileMode.Open); + } catch (Exception ex) { file = null; throw new Exception(ex.Message); } - file_size = file.Length; - - if (resume) - { - long size = GetFileSize(remote_filename); - SendCommand("REST " + size); - ReadResponse(); - if (response == 350) - file.Seek(size, SeekOrigin.Begin); - } - - SendCommand("STOR " + remote_filename); + SendCommand("REST " + file.Length); ReadResponse(); - - switch (response) - { - case 125: - case 150: - break; - default: - file.Close(); - file = null; - throw new Exception(responseStr); + if (response != 350) + throw new Exception(responseStr); + file.Seek(file.Length, SeekOrigin.Begin); + bytes_total = file.Length; + } else { + try { + file = new FileStream(local_filename, FileMode.Create); + } catch (Exception ex) { + file = null; + throw new Exception(ex.Message); } - ConnectDataSocket(); // ####################################### - - return; } - /// - /// Download a file with no resume - /// - /// Remote file name - public void OpenDownload(string filename) - { - OpenDownload(filename, filename, false); - } - /// - /// Download a file with optional resume - /// - /// Remote file name - /// Attempt resume if file exists - public void OpenDownload(string filename, bool resume) - { - OpenDownload(filename, filename, resume); - } - /// - /// Download a file with no attempt to resume - /// - /// Remote filename - /// Local filename (Can include path to file) - public void OpenDownload(string filename, string localfilename) - { - OpenDownload(filename, localfilename, false); - } - /// - /// Open a file for download - /// - /// The name of the file on the FTP server - /// The name of the file to save as (Can include path to file) - /// Attempt resume if file exists - public void OpenDownload(string remote_filename, string local_filename, bool resume) - { - Connect(); - SetBinaryMode(true); - bytes_total = 0; + OpenDataSocket(); + SendCommand("RETR " + remote_filename); + ReadResponse(); - try - { - file_size = GetFileSize(remote_filename); - } - catch - { - file_size = 0; - } - - if (resume && File.Exists(local_filename)) - { - try - { - file = new FileStream(local_filename, FileMode.Open); - } - catch (Exception ex) - { - file = null; - throw new Exception(ex.Message); - } - - SendCommand("REST " + file.Length); - ReadResponse(); - if (response != 350) - throw new Exception(responseStr); - file.Seek(file.Length, SeekOrigin.Begin); - bytes_total = file.Length; - } - else - { - try - { - file = new FileStream(local_filename, FileMode.Create); - } - catch (Exception ex) - { - file = null; - throw new Exception(ex.Message); - } - } - - OpenDataSocket(); - SendCommand("RETR " + remote_filename); - ReadResponse(); - - switch (response) - { - case 125: - case 150: - break; - default: - file.Close(); - file = null; - throw new Exception(responseStr); - } - ConnectDataSocket(); // ####################################### - - return; - } - /// - /// Upload the file, to be used in a loop until file is completely uploaded - /// - /// Bytes sent - public long DoUpload() - { - Byte[] bytes = new Byte[512]; - long bytes_got; - - try - { - bytes_got = file.Read(bytes, 0, bytes.Length); - bytes_total += bytes_got; - data_sock.Send(bytes, (int)bytes_got, 0); - - if (bytes_got <= 0) - { - // the upload is complete or an error occured - file.Close(); - file = null; - - CloseDataSocket(); - ReadResponse(); - switch (response) - { - case 226: - case 250: - break; - default: - throw new Exception(responseStr); - } - - SetBinaryMode(false); - } - } - catch (Exception ex) - { + switch (response) { + case 125: + case 150: + break; + default: file.Close(); file = null; + throw new Exception(responseStr); + } + ConnectDataSocket(); // ####################################### + + return; + } + /// + /// Upload the file, to be used in a loop until file is completely uploaded + /// + /// Bytes sent + public long DoUpload() { + byte[] bytes = new byte[512]; + long bytes_got; + + try { + bytes_got = file.Read(bytes, 0, bytes.Length); + bytes_total += bytes_got; + data_sock.Send(bytes, (int)bytes_got, 0); + + if (bytes_got <= 0) { + // the upload is complete or an error occured + file.Close(); + file = null; + CloseDataSocket(); ReadResponse(); - SetBinaryMode(false); - throw ex; - } - - return bytes_got; - } - /// - /// Download a file, to be used in a loop until the file is completely downloaded - /// - /// Number of bytes recieved - public long DoDownload() - { - Byte[] bytes = new Byte[512]; - long bytes_got; - - try - { - bytes_got = data_sock.Receive(bytes, bytes.Length, 0); - - if (bytes_got <= 0) - { - // the download is done or an error occured - CloseDataSocket(); - file.Close(); - file = null; - - ReadResponse(); - switch (response) - { - case 226: - case 250: - break; - default: - throw new Exception(responseStr); - } - - SetBinaryMode(false); - - return bytes_got; + switch (response) { + case 226: + case 250: + break; + default: + throw new Exception(responseStr); } - file.Write(bytes, 0, (int)bytes_got); - bytes_total += bytes_got; + SetBinaryMode(false); } - catch (Exception ex) - { + } catch (Exception ex) { + file.Close(); + file = null; + CloseDataSocket(); + ReadResponse(); + SetBinaryMode(false); + throw; + } + + return bytes_got; + } + /// + /// Download a file, to be used in a loop until the file is completely downloaded + /// + /// Number of bytes recieved + public long DoDownload() { + byte[] bytes = new byte[512]; + long bytes_got; + + try { + bytes_got = data_sock.Receive(bytes, bytes.Length, 0); + + if (bytes_got <= 0) { + // the download is done or an error occured CloseDataSocket(); file.Close(); file = null; + ReadResponse(); + switch (response) { + case 226: + case 250: + break; + default: + throw new Exception(responseStr); + } + SetBinaryMode(false); - throw ex; + + return bytes_got; } - return bytes_got; + file.Write(bytes, 0, (int)bytes_got); + bytes_total += bytes_got; + } catch (Exception ex) { + CloseDataSocket(); + file.Close(); + file = null; + ReadResponse(); + SetBinaryMode(false); + throw; } + + return bytes_got; } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/AccountViewModels.cs b/Fab2ApprovalSystem/Models/AccountViewModels.cs index 5b5d0ba..477d516 100644 --- a/Fab2ApprovalSystem/Models/AccountViewModels.cs +++ b/Fab2ApprovalSystem/Models/AccountViewModels.cs @@ -1,118 +1,48 @@ using System; using System.ComponentModel.DataAnnotations; -namespace Fab2ApprovalSystem.Models -{ - public class LoginModel - { - [Key] - public int UserID { get; set; } +namespace Fab2ApprovalSystem.Models; - [Required] - [Display(Name = "Login ID")] - public string LoginID { get; set; } +public class LoginModel { + [Key] + public int UserID { get; set; } - //[Required] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; set; } + [Required] + [Display(Name = "Login ID")] + public string LoginID { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } + //[Required] + [DataType(DataType.Password)] + [Display(Name = "Password")] + public string Password { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string FullName { get; set; } + public bool IsAdmin { get; set; } + public bool IsManager { get; set; } + public bool IsActive { get; set; } + public DateTime? LastLogin { get; set; } + public bool OOO { get; set; } + public DateTime? OOOStartDate { get; set; } + public DateTime? OOOExpirationDate { get; set; } + public int DelegatedTo { get; set; } + public string Email { get; set; } - public string FullName { get; set; } + [Display(Name = "Delegated To")] + public string DelegatedToFullName { get; set; } - public bool IsAdmin { get; set; } - public bool IsManager { get; set; } - public bool IsActive { get; set; } - public DateTime? LastLogin { get; set; } - - public bool OOO { get; set; } - - public DateTime? OOOStartDate { get; set; } - public DateTime? OOOExpirationDate { get; set; } - - public int DelegatedTo { get; set; } - - public string Email { get; set; } - - [Display(Name="Delegated To")] - public string DelegatedToFullName { get; set; } - - [Display(Name = "OOO Action")] - public virtual string OOOStatusWithUserID - { - get - { - return UserID.ToString() + "~" + (OOO ? "1" : "0") + "~" + FullName; - } + [Display(Name = "OOO Action")] + public virtual string OOOStatusWithUserID { + get { + return UserID.ToString() + "~" + (OOO ? "1" : "0") + "~" + FullName; } - } - public class UserProfile - { - public int UserId { get; set; } - public string FullName { get; set; } - } - - - //public class ExternalLoginConfirmationViewModel - //{ - // [Required] - // [Display(Name = "User name")] - // public string UserName { get; set; } - //} - - //public class ManageUserViewModel - //{ - // [Required] - // [DataType(DataType.Password)] - // [Display(Name = "Current password")] - // public string OldPassword { get; set; } - - // [Required] - // [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] - // [DataType(DataType.Password)] - // [Display(Name = "New password")] - // public string NewPassword { get; set; } - - // [DataType(DataType.Password)] - // [Display(Name = "Confirm new password")] - // [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] - // public string ConfirmPassword { get; set; } - //} - - //public class LoginViewModel - //{ - // [Required] - // [Display(Name = "User name")] - // public string UserName { get; set; } - - // [Required] - // [DataType(DataType.Password)] - // [Display(Name = "Password")] - // public string Password { get; set; } - - // [Display(Name = "Remember me?")] - // public bool RememberMe { get; set; } - //} - - //public class RegisterViewModel - //{ - // [Required] - // [Display(Name = "User name")] - // public string UserName { get; set; } - - // [Required] - // [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] - // [DataType(DataType.Password)] - // [Display(Name = "Password")] - // public string Password { get; set; } - - // [DataType(DataType.Password)] - // [Display(Name = "Confirm password")] - // [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] - // public string ConfirmPassword { get; set; } - //} } + +public class UserProfile { + + public int UserId { get; set; } + public string FullName { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/AdminModels.cs b/Fab2ApprovalSystem/Models/AdminModels.cs index c74ba70..b531589 100644 --- a/Fab2ApprovalSystem/Models/AdminModels.cs +++ b/Fab2ApprovalSystem/Models/AdminModels.cs @@ -1,73 +1,42 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Web; - -namespace Fab2ApprovalSystem.Models -{ - //public class DocumentType - //{ - //} - - public class WorkFlow - { - - } - - - public class Role - { - public int RoleID { get; set; } - public string RoleName { get; set; } - public List SubRoles { get; set; } - - public Role() - { - SubRoles = new List(); - } - - } - - public class WorkFlowSteps - { - } - - - - public class SubRole - { - public int SubRoleID { get; set; } - public string SubRoleCategoryItem { get; set; } - public int RoleID { get; set; } - public bool Inactive { get; set; } - } - - - public class UserSubRole - { - - } - - public class ParentChildModel - { - public int id { get; set; } - public int parentid { get; set; } - public string text { get; set; } - public string value { get; set; } - - public List Children = new List(); - - } - //public class TrainingGroup - //{ - // public int TrainingGroupID { get; set; } - // public string TrainingGroupName { get; set; } - //} - - +namespace Fab2ApprovalSystem.Models; +public class WorkFlow { } +public class Role { + public int RoleID { get; set; } + public string RoleName { get; set; } + public List SubRoles { get; set; } + public Role() => SubRoles = new List(); + +} + +public class WorkFlowSteps { +} + +public class SubRole { + + public int SubRoleID { get; set; } + public string SubRoleCategoryItem { get; set; } + public int RoleID { get; set; } + public bool Inactive { get; set; } + +} + +public class UserSubRole { + +} + +public class ParentChildModel { + + public int id { get; set; } + public int parentid { get; set; } + public string text { get; set; } + public string value { get; set; } + public List Children = new(); + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/AllUserModel.cs b/Fab2ApprovalSystem/Models/AllUserModel.cs index 0a68779..fdd8012 100644 --- a/Fab2ApprovalSystem/Models/AllUserModel.cs +++ b/Fab2ApprovalSystem/Models/AllUserModel.cs @@ -1,16 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +namespace Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.Models -{ - public class AllUserModel - { - public string UserName { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string Email { get; set; } - public string DisplayName { get; set; } - } -} +public class AllUserModel { + + public string UserName { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string Email { get; set; } + public string DisplayName { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/AppSettings.cs b/Fab2ApprovalSystem/Models/AppSettings.cs new file mode 100644 index 0000000..70a5969 --- /dev/null +++ b/Fab2ApprovalSystem/Models/AppSettings.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; + +namespace Fab2ApprovalSystem.Models; + +public class AppSettings { + + internal AppSettings(string adminNotificationRecepient, + string? apiBaseUrl, + string attachmentFolder, + string? attachmentUrl, + string caBlankFormsLocation, + string? company, + string dBConnection, + string dbConnectionString, + string ftpPassword, + string ftpServer, + string ftpUser, + string holdFlagDirectory, + string hostURL, + string ifxContainer, + string ifxDomain, + bool isInfineonDomain, + string lotTempPipeLine, + string mesaTemplateFiles, + string naContainer, + string naDomain, + string nDriveURL, + string notificationSender, + string senderEmail, + string? smtpServer, + string spnMRBHoldFlagFTPLogDirectory, + string testEmailRecipients, + string urls, + int userId, + bool userIsAdmin, + string wsrURL, + string? workingDirectoryName) { + AdminNotificationRecepient = adminNotificationRecepient; + ApiBaseUrl = apiBaseUrl; + AttachmentFolder = attachmentFolder; + AttachmentUrl = attachmentUrl; + CABlankFormsLocation = caBlankFormsLocation; + Company = company; + DBConnection = dBConnection; + DBConnectionString = dbConnectionString; + FTPPassword = ftpPassword; + FTPServer = ftpServer; + FTPUser = ftpUser; + HoldFlagDirectory = holdFlagDirectory; + HostURL = hostURL; + IFXContainer = ifxContainer; + IFXDomain = ifxDomain; + IsInfineonDomain = isInfineonDomain; + LotTempPipeLine = lotTempPipeLine; + MesaTemplateFiles = mesaTemplateFiles; + NAContainer = naContainer; + NADomain = naDomain; + NDriveURL = nDriveURL; + NotificationSender = notificationSender; + SenderEmail = senderEmail; + SMTPServer = smtpServer; + SPNMRBHoldFlagFTPLogDirectory = spnMRBHoldFlagFTPLogDirectory; + TestEmailRecipients = testEmailRecipients; + URLs = urls; + UserId = userId; + UserIsAdmin = userIsAdmin; + WSR_URL = wsrURL; + WorkingDirectoryName = workingDirectoryName; + } + + public string AdminNotificationRecepient { get; } + public string? ApiBaseUrl { get; } + public string AttachmentFolder { get; } + public string? AttachmentUrl { get; } + public string CABlankFormsLocation { get; } + public string? Company { get; } + public string DBConnection { get; } + public string DBConnectionString { get; } + public string FTPPassword { get; } + public string FTPServer { get; } + public string FTPUser { get; } + public string HoldFlagDirectory { get; } + public string HostURL { get; } + public string IFXContainer { get; } + public string IFXDomain { get; } + public bool IsInfineonDomain { get; } + public string LotTempPipeLine { get; } + public string MesaTemplateFiles { get; } + public string NAContainer { get; } + public string NADomain { get; } + public string NDriveURL { get; } + public string NotificationSender { get; } + public string SenderEmail { get; } + public string? SMTPServer { get; } + public string SPNMRBHoldFlagFTPLogDirectory { get; } + public string TestEmailRecipients { get; } + public string URLs { get; } + public int UserId { get; } + public bool UserIsAdmin { get; } + public string WSR_URL { get; } + public string? WorkingDirectoryName { get; } + +#if NET8 + + public static AppSettings Get(Microsoft.Extensions.Configuration.IConfigurationRoot configurationRoot) { + AppSettings? result; + try { +#pragma warning disable IL3050, IL2026 + result = Microsoft.Extensions.Configuration.ConfigurationBinder.Get(configurationRoot) ?? throw new Exception(); +#pragma warning restore IL3050, IL2026 + } catch (Exception) { + List paths = []; + foreach (Microsoft.Extensions.Configuration.IConfigurationProvider configurationProvider in configurationRoot.Providers) { + if (configurationProvider is not Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider jsonConfigurationProvider) + continue; + if (jsonConfigurationProvider.Source.FileProvider is not Microsoft.Extensions.FileProviders.PhysicalFileProvider physicalFileProvider) + continue; + paths.Add(physicalFileProvider.Root); + } + + throw new NotSupportedException($"Not found!{Environment.NewLine}{string.Join(Environment.NewLine, paths.Distinct())}"); + } + + return result; + } + +#endif + + internal static AppSettings LoadConfigurationManager() { + AppSettings result; + int userId = 0; + string adminNotificationRecepient = ConfigurationManager.ConnectionStrings["Admin Notification Recepient"].ToString(); + string attachmentFolder = ConfigurationManager.ConnectionStrings["AttachmentFolder"].ToString(); + string ftpPassword = ConfigurationManager.ConnectionStrings["FTP Password"].ToString(); + string ftpServer = ConfigurationManager.ConnectionStrings["FTP Server"].ToString(); + string ftpUser = ConfigurationManager.ConnectionStrings["FTP User"].ToString(); + string holdFlagDirectory = ConfigurationManager.ConnectionStrings["HoldFlagDirectory"].ToString(); + string ifxContainer = ConfigurationManager.ConnectionStrings["IFXContainer"].ToString(); + string ifxDomain = ConfigurationManager.ConnectionStrings["IFXDomain"].ToString(); + string lotTempPipeLine = ConfigurationManager.ConnectionStrings["LotTempPipeLine"].ToString(); + string naContainer = ConfigurationManager.ConnectionStrings["NAContainer"].ToString(); + string naDomain = ConfigurationManager.ConnectionStrings["NADomain"].ToString(); + string notificationSender = ConfigurationManager.ConnectionStrings["Notification Sender"].ToString(); + string spnMRBHoldFlagFTPLogDirectory = ConfigurationManager.ConnectionStrings["SPNMRBHoldFlagFTPLogDirectory"].ToString(); + string testEmailRecipients = ConfigurationManager.ConnectionStrings["Test Email Recipients"].ToString(); + string? apiBaseUrl = ConfigurationManager.ConnectionStrings["FabApprovalApiBaseUrl"]?.ToString(); + string? attachmentUrl = ConfigurationManager.ConnectionStrings["AttachmentUrl"]?.ToString(); + string? company = ConfigurationManager.ConnectionStrings["Company"]?.ToString(); + string? smtpServer = ConfigurationManager.ConnectionStrings["SMTP Server"]?.ToString(); + string? urls = ConfigurationManager.ConnectionStrings["URLs"]?.ToString(); + string? workingDirectoryName = ConfigurationManager.ConnectionStrings["WorkingDirectoryName"]?.ToString(); + result = new(adminNotificationRecepient: adminNotificationRecepient, + apiBaseUrl: apiBaseUrl, + attachmentFolder: attachmentFolder, + attachmentUrl: attachmentUrl, + caBlankFormsLocation: Misc.GlobalVars.CA_BlankFormsLocation, + company: company, + dBConnection: Misc.GlobalVars.DBConnection, + dbConnectionString: Misc.GlobalVars.DB_CONNECTION_STRING, + ftpPassword: ftpPassword, + ftpServer: ftpServer, + ftpUser: ftpUser, + holdFlagDirectory: holdFlagDirectory, + hostURL: Misc.GlobalVars.hostURL, + ifxContainer: ifxContainer, + ifxDomain: ifxDomain, + isInfineonDomain: Misc.GlobalVars.IS_INFINEON_DOMAIN, + lotTempPipeLine: lotTempPipeLine, + mesaTemplateFiles: Misc.GlobalVars.MesaTemplateFiles, + naContainer: naContainer, + naDomain: naDomain, + nDriveURL: Misc.GlobalVars.NDriveURL, + notificationSender: notificationSender, + senderEmail: Misc.GlobalVars.SENDER_EMAIL, + smtpServer: smtpServer, + spnMRBHoldFlagFTPLogDirectory: spnMRBHoldFlagFTPLogDirectory, + testEmailRecipients: testEmailRecipients, + urls: urls, + userId: userId, + userIsAdmin: Misc.GlobalVars.USER_ISADMIN, + wsrURL: Misc.GlobalVars.WSR_URL, + workingDirectoryName: workingDirectoryName); + return result; + } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/ApprovalLog.cs b/Fab2ApprovalSystem/Models/ApprovalLog.cs index 2d64f65..82de097 100644 --- a/Fab2ApprovalSystem/Models/ApprovalLog.cs +++ b/Fab2ApprovalSystem/Models/ApprovalLog.cs @@ -1,20 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +namespace Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.Models -{ - public class ApprovalLog - { +public class ApprovalLog { - public int ApprovalLogID; - public int IssueID; - public int UserID; - public string OperationType; - public int SubRoleID; - public string OperationLog; - public int DocumentTypeID; + public int ApprovalLogID; + public int IssueID; + public int UserID; + public string OperationType; + public int SubRoleID; + public string OperationLog; + public int DocumentTypeID; - } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/ApprovalLogHistory.cs b/Fab2ApprovalSystem/Models/ApprovalLogHistory.cs index 0f23c9f..a7e7231 100644 --- a/Fab2ApprovalSystem/Models/ApprovalLogHistory.cs +++ b/Fab2ApprovalSystem/Models/ApprovalLogHistory.cs @@ -1,21 +1,16 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.ComponentModel.DataAnnotations; -namespace Fab2ApprovalSystem.Models -{ - public class ApprovalLogHistory - { - public int ApprovalLogID { get; set; } - public string FullName { get; set; } - public string Operation { get; set; } - public string SubRole { get; set; } +namespace Fab2ApprovalSystem.Models; - //[Display(Name = "Operation Time")] - public DateTime OperationTime { get; set; } - public string Comments { get; set; } +public class ApprovalLogHistory { - } -} + public int ApprovalLogID { get; set; } + public string FullName { get; set; } + public string Operation { get; set; } + public string SubRole { get; set; } + + //[Display(Name = "Operation Time")] + public DateTime OperationTime { get; set; } + public string Comments { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/ApproveListModel.cs b/Fab2ApprovalSystem/Models/ApproveListModel.cs index ec10217..2c1e8c5 100644 --- a/Fab2ApprovalSystem/Models/ApproveListModel.cs +++ b/Fab2ApprovalSystem/Models/ApproveListModel.cs @@ -1,22 +1,18 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.Models -{ - public class ApproveListModel - { - public int ApprovalKey { get; set; } - public int IssueID { get; set; } - public string AssignedName { get; set; } - public string AssignedEmail { get; set; } - public string AssignedFullName { get; set; } - public DateTime LastNotification { get; set; } - public DateTime AssignedDate { get; set; } - public DateTime RoleAssignedDate { get; set; } - public string DocType { get; set; } - public string Title { get; set; } +namespace Fab2ApprovalSystem.Models; - } -} +public class ApproveListModel { + + public int ApprovalKey { get; set; } + public int IssueID { get; set; } + public string AssignedName { get; set; } + public string AssignedEmail { get; set; } + public string AssignedFullName { get; set; } + public DateTime LastNotification { get; set; } + public DateTime AssignedDate { get; set; } + public DateTime RoleAssignedDate { get; set; } + public string DocType { get; set; } + public string Title { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/AuditModels.cs b/Fab2ApprovalSystem/Models/AuditModels.cs new file mode 100644 index 0000000..8707239 --- /dev/null +++ b/Fab2ApprovalSystem/Models/AuditModels.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; + +namespace Fab2ApprovalSystem.Models; + +public class AuditEdit { + + public Audit Audit { get; set; } + public IEnumerable AuditAreaList { get; set; } + public List AuditeeNames { get; set; } + public List AuditFindingCategoryList { get; set; } + public IEnumerable AuditorList { get; set; } + public IEnumerable AuditTypeList { get; set; } + public IEnumerable CANoList { get; set; } + public string Is8DQA { get; set; } + public bool IsAdmin { get; set; } + public bool IsSubmitter { get; set; } + public List MesaUsers { get; set; } + public IEnumerable UserList { get; set; } + public bool RedirectToAction { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/AuthAttempt.cs b/Fab2ApprovalSystem/Models/AuthAttempt.cs index 005f48e..aba1ed1 100644 --- a/Fab2ApprovalSystem/Models/AuthAttempt.cs +++ b/Fab2ApprovalSystem/Models/AuthAttempt.cs @@ -1,7 +1,9 @@ -namespace Fab2ApprovalSystem.Models { - public class AuthAttempt { - public string LoginID { get; set; } - public string Password { get; set; } = ""; - public AuthTokens AuthTokens { get; set; } - } -} +namespace Fab2ApprovalSystem.Models; + +public class AuthAttempt { + + public string LoginID { get; set; } + public string Password { get; set; } = ""; + public AuthTokens AuthTokens { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/AuthTokens.cs b/Fab2ApprovalSystem/Models/AuthTokens.cs index 969eb98..250b6ce 100644 --- a/Fab2ApprovalSystem/Models/AuthTokens.cs +++ b/Fab2ApprovalSystem/Models/AuthTokens.cs @@ -1,6 +1,8 @@ -namespace Fab2ApprovalSystem.Models { - public class AuthTokens { - public string JwtToken { get; set; } - public string RefreshToken { get; set; } - } -} +namespace Fab2ApprovalSystem.Models; + +public class AuthTokens { + + public string JwtToken { get; set; } + public string RefreshToken { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/ChangeControlModel.cs b/Fab2ApprovalSystem/Models/ChangeControlModel.cs index 7bbe860..9031cd9 100644 --- a/Fab2ApprovalSystem/Models/ChangeControlModel.cs +++ b/Fab2ApprovalSystem/Models/ChangeControlModel.cs @@ -1,376 +1,321 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.Models -{ - /// - /// - /// - public class CCChangeControl - { - public int PlanNumber { get; set; } - public int OwnerID { get; set; } - public byte CurrentStep { get; set; } - public int Status { get; set; } +namespace Fab2ApprovalSystem.Models; - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? ClosedDate { get; set; } +public class CCChangeControl { - public int ChangeLevel { get; set; } - public string Notes { get; set; } - public int IsITAR { get; set; } - public int IsMedical { get; set; } - public int IsRadHard { get; set; } - public int IsAutomotive { get; set; } - public string Title { get; set; } - public string PartNumbers { get; set; } - public string ToolTypes { get; set; } - public bool RecordLockIndicator { get; set; } - public int RecordLockedBy { get; set; } - public bool RecordLocked { get; set; } - public DateTime RecordLockedDate { get; set; } - public string ReasonForChange { get; set; } - public string ChangeDescription { get; set; } - public DateTime LastUpdateDate { get; set; } - public int PCR1ID { get; set; } - public int PCR2ID { get; set; } - public int PCR3ID {get;set;} - public string PlanTitle { get; set; } + public int PlanNumber { get; set; } + public int OwnerID { get; set; } + public byte CurrentStep { get; set; } + public int Status { get; set; } - } + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? ClosedDate { get; set; } + public int ChangeLevel { get; set; } + public string Notes { get; set; } + public int IsITAR { get; set; } + public int IsMedical { get; set; } + public int IsRadHard { get; set; } + public int IsAutomotive { get; set; } + public string Title { get; set; } + public string PartNumbers { get; set; } + public string ToolTypes { get; set; } + public bool RecordLockIndicator { get; set; } + public int RecordLockedBy { get; set; } + public bool RecordLocked { get; set; } + public DateTime RecordLockedDate { get; set; } + public string ReasonForChange { get; set; } + public string ChangeDescription { get; set; } + public DateTime LastUpdateDate { get; set; } + public int PCR1ID { get; set; } + public int PCR2ID { get; set; } + public int PCR3ID { get; set; } + public string PlanTitle { get; set; } +} - /// - /// - /// - public class CCAttachment - { - public int ID { get; set; } - public string FileGUID { get; set; } - public string FileName { get; set; } - public int UploadedByID { get; set; } - public string UploadedByName { get; set; } - public DateTime? UploadDateTime { get; set; } - public string Title { get; set; } - public string RequirementsNotes { get; set; } - public string Comments { get; set; } - public int PlanNumber { get; set; } +public class CCAttachment { - } + public int ID { get; set; } + public string FileGUID { get; set; } + public string FileName { get; set; } + public int UploadedByID { get; set; } + public string UploadedByName { get; set; } + public DateTime? UploadDateTime { get; set; } + public string Title { get; set; } + public string RequirementsNotes { get; set; } + public string Comments { get; set; } + public int PlanNumber { get; set; } +} - /// - /// - /// - public class CCGeneration - { - public int GenerationID { get; set; } - public string Generation { get; set; } - } +public class CCGeneration { + public int GenerationID { get; set; } + public string Generation { get; set; } - /// - /// - /// - public class CCLogistics - { - public int LogisticsID { get; set; } - public string Logistics { get; set; } - } +} +public class CCLogistics { + public int LogisticsID { get; set; } + public string Logistics { get; set; } - /// - /// - /// - public class CCProcess - { - public int ProcessID { get; set; } - public string Process { get; set; } - } +} - /// - /// - /// - //public class CCToolType - //{ - // public int ToolTypeID { get; set; } - // public string ToolType { get; set; } - //} +public class CCProcess { - public class CCPartNumber - { - public string PartNumberID { get; set; } - public string PartNumber { get; set; } - } + public int ProcessID { get; set; } + public string Process { get; set; } +} + +public class CCPartNumber { + + public string PartNumberID { get; set; } + public string PartNumber { get; set; } + +} #region Meeting - /// - /// - /// - public class CCMeeting - { - public int MeetingID { get; set; } - public List PCRValueIDs { get; set; } - public string PCRValueIDsDisplay { get - { - if(PCRValueIDs.Count < 1) - { - return ""; - } - return string.Join(",", PCRValueIDs); - } } - public int PlanNumber { get; set; } - public byte CurrentStep { get; set; } - public string Title {get;set;} - public int? ChangeLevel - { - get;set; - } - public string PCRB { get; set; } - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? MeetingDate { get; set; } - public int Decision { get; set; } - public string Notes { get; set; } - public int Status { get; set; } +public class CCMeeting { - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? ClosedDate { get; set;} - - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? CancelledDate { get; set; } - public bool RecordLockIndicator { get; set; } - public int RecordLockedBy { get; set; } - public DateTime RecordLockedDate { get; set; } - public DateTime LastUpdateDate { get; set; } - public string RecordLockByName { get; set; } - public bool PCRBClosed { get; set; } - - - public CCMeeting() - { - PCRValueIDs = new List(); + public int MeetingID { get; set; } + public List PCRValueIDs { get; set; } + public string PCRValueIDsDisplay { + get { + if (PCRValueIDs.Count < 1) { + return ""; + } + return string.Join(",", PCRValueIDs); } } - public class CCPCRB - { - public int PCRBID { get; set; } - public int PlanNumber { get; set; } - public string PCRB { get; set; } - public DateTime Date { get; set; } - public int Decision { get; set; } - public string Notes { get; set; } + public int PlanNumber { get; set; } + public byte CurrentStep { get; set; } + public string Title { get; set; } + public int? ChangeLevel { + get; set; } - /// - /// - /// - public class CCMeetingAttendee - { - public int ID { get; set; } - public int MeetingID { get; set; } - public string AttendeeName { get; set; } - public string JobTitle { get; set; } - public string Location { get; set; } - public int AttendeeID { get; set; } + public string PCRB { get; set; } + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? MeetingDate { get; set; } + public int Decision { get; set; } + public string Notes { get; set; } + public int Status { get; set; } - } - public class CCPCRBAttendee - { - public int ID { get; set; } - public int PCRBID { get; set; } - public string AttendeeName { get; set; } - public string JobTitle { get; set; } - public string Location { get; set; } - public bool Approved { get; set; } - public int AttendeeID { get; set; } + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? ClosedDate { get; set; } - } - /// - /// / - /// - public class CCMeetingAttachment - { - public int ID { get; set; } - public string FileGUID { get; set; } - public string FileName { get; set; } - public int UploadedByID { get; set; } - public string UploadedByName { get; set; } - public DateTime UploadDateTime { get; set; } - public string Title { get; set; } - public int MeetingID { get; set; } - } - - /// - /// - /// - public class CCDecisionSummary - { - public int ID { get; set; } - public int MeetingID { get; set; } - public string DecisionNotes { get; set; } - public string ECNLinks { get; set; } - public string LotDispoLinks { get; set; } - } - - /// - /// - /// - public class CCDecisionSummaryLink - { - public string Link { get; set; } - } - - - /// - /// - /// - public class CCMeetingActionItem - { - public int ID { get; set; } - public int MeetingID { get; set; } - public string ActionItemName { get; set; } - public string ResponsiblePerson { get; set; } - public string Gating { get; set; } - public DateTime? DueDate { get; set; } - public string ResponsibleID { get; set; } - - - } - public class CCPCRBActionItem - { - public int ID { get; set; } - public int PCRBID { get; set; } - public string ActionItemName { get; set; } - public string ResponsiblePerson { get; set; } - public string Gating { get; set; } - public DateTime? DueDate { get; set; } - public string ResponsibleID { get; set; } - - } - public class CCPCRBActionItemAll - { - [Key] - public int ID { get; set; } - - public int MeetingID { get; set; } - public string ActionItemName { get; set; } - public string ResponsiblePerson { get; set; } - public string Gating { get; set; } - public DateTime? DueDate { get; set; } - public string PCRB { get; set; } - public string Updates { get; set; } - public bool ClosedStatus { get; set; } - public DateTime? ClosedDate { get; set; } - public int ClosedBy { get; set; } - public string FileGUID { get; set; } - public string FileName { get; set; } - public int UploadedByID { get; set; } - public string UploadedByName { get; set; } - public DateTime UploadDateTime { get; set; } - - - - } - - /// - /// - /// - public class CCMeetingActionItemAll - { - [Key] - public int ID { get; set; } - - public int MeetingID { get; set; } - public string ActionItemName { get; set; } - public string ResponsiblePerson { get; set; } - public string Gating { get; set; } - public DateTime? DueDate { get; set; } - public string PCRB { get; set; } - public string Updates { get; set; } - public bool ClosedStatus { get; set; } - public DateTime? ClosedDate { get; set; } - public int ClosedBy { get; set; } - public string FileGUID { get; set; } - public string FileName { get; set; } - public int UploadedByID { get; set; } - public string UploadedByName { get; set; } - public DateTime UploadDateTime { get; set; } - - - - } - - /// - /// - /// - public class MeetingList - { - public int MeetingID { get; set; } - public string MeetingInfo{ get; set; } - } - - - public class MeetingDecisionSummaryList - { - public string PCRB { get; set; } - public DateTime? MeetingDate { get; set; } - public string DecisionNotes { get; set; } - public string ECNLinks { get; set; } - public string LotDispoLinks { get; set; } - } - - - public class UserList - { - public int AttendeeID { set; get; } - public string AttendeeName { get; set; } - } - - public class ActionItemResponsible - { - public string ResponsibleID { set; get; } - public string ResponsibleName { get; set; } - } - - - public class SiteList - { - public string SiteID { set; get; } - public string SiteName { get; set; } - } - - - - public class ChangeControlList - { - public string IssueID { get; set; } - public string Title { get; set; } - public string MesaIdTitle { get; set; } - public string Owner { get; set; } - public string ChangeLevel { get; set; } - public DateTime? StartDate { get; set; } - public DateTime? StatusDate { get; set; } - public string PCRBStatus { get; set; } - public string Generations { get; set; } - public string Logistics { get; set; } - public string Processes { get; set; } - public string ToolTypes { get; set; } - public string ActionItemResponsibility { get; set; } - } - - public class PCRValue - { - public string PCRValueID { set; get; } - public string PCRValueName { get; set; } - } - -#endregion + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? CancelledDate { get; set; } + public bool RecordLockIndicator { get; set; } + public int RecordLockedBy { get; set; } + public DateTime RecordLockedDate { get; set; } + public DateTime LastUpdateDate { get; set; } + public string RecordLockByName { get; set; } + public bool PCRBClosed { get; set; } + public CCMeeting() => + PCRValueIDs = new List(); } + +public class CCPCRB { + + public int PCRBID { get; set; } + public int PlanNumber { get; set; } + public string PCRB { get; set; } + public DateTime Date { get; set; } + public int Decision { get; set; } + public string Notes { get; set; } + +} + +public class CCMeetingAttendee { + + public int ID { get; set; } + public int MeetingID { get; set; } + public string AttendeeName { get; set; } + public string JobTitle { get; set; } + public string Location { get; set; } + public int AttendeeID { get; set; } + +} + +public class CCPCRBAttendee { + + public int ID { get; set; } + public int PCRBID { get; set; } + public string AttendeeName { get; set; } + public string JobTitle { get; set; } + public string Location { get; set; } + public bool Approved { get; set; } + public int AttendeeID { get; set; } + +} +/// +/// / +/// +public class CCMeetingAttachment { + + public int ID { get; set; } + public string FileGUID { get; set; } + public string FileName { get; set; } + public int UploadedByID { get; set; } + public string UploadedByName { get; set; } + public DateTime UploadDateTime { get; set; } + public string Title { get; set; } + public int MeetingID { get; set; } + +} + +public class CCDecisionSummary { + + public int ID { get; set; } + public int MeetingID { get; set; } + public string DecisionNotes { get; set; } + public string ECNLinks { get; set; } + public string LotDispoLinks { get; set; } + +} + +public class CCDecisionSummaryLink { + + public string Link { get; set; } + +} + +public class CCMeetingActionItem { + + public int ID { get; set; } + public int MeetingID { get; set; } + public string ActionItemName { get; set; } + public string ResponsiblePerson { get; set; } + public string Gating { get; set; } + public DateTime? DueDate { get; set; } + public string ResponsibleID { get; set; } + +} + +public class CCPCRBActionItem { + + public int ID { get; set; } + public int PCRBID { get; set; } + public string ActionItemName { get; set; } + public string ResponsiblePerson { get; set; } + public string Gating { get; set; } + public DateTime? DueDate { get; set; } + public string ResponsibleID { get; set; } + +} + +public class CCPCRBActionItemAll { + [Key] + public int ID { get; set; } + public int MeetingID { get; set; } + public string ActionItemName { get; set; } + public string ResponsiblePerson { get; set; } + public string Gating { get; set; } + public DateTime? DueDate { get; set; } + public string PCRB { get; set; } + public string Updates { get; set; } + public bool ClosedStatus { get; set; } + public DateTime? ClosedDate { get; set; } + public int ClosedBy { get; set; } + public string FileGUID { get; set; } + public string FileName { get; set; } + public int UploadedByID { get; set; } + public string UploadedByName { get; set; } + public DateTime UploadDateTime { get; set; } + +} + +public class CCMeetingActionItemAll { + [Key] + public int ID { get; set; } + public int MeetingID { get; set; } + public string ActionItemName { get; set; } + public string ResponsiblePerson { get; set; } + public string Gating { get; set; } + public DateTime? DueDate { get; set; } + public string PCRB { get; set; } + public string Updates { get; set; } + public bool ClosedStatus { get; set; } + public DateTime? ClosedDate { get; set; } + public int ClosedBy { get; set; } + public string FileGUID { get; set; } + public string FileName { get; set; } + public int UploadedByID { get; set; } + public string UploadedByName { get; set; } + public DateTime UploadDateTime { get; set; } + +} + +public class MeetingList { + + public int MeetingID { get; set; } + public string MeetingInfo { get; set; } + +} + +public class MeetingDecisionSummaryList { + + public string PCRB { get; set; } + public DateTime? MeetingDate { get; set; } + public string DecisionNotes { get; set; } + public string ECNLinks { get; set; } + public string LotDispoLinks { get; set; } + +} + +public class UserList { + + public int AttendeeID { set; get; } + public string AttendeeName { get; set; } + +} + +public class ActionItemResponsible { + + public string ResponsibleID { set; get; } + public string ResponsibleName { get; set; } + +} + +public class SiteList { + + public string SiteID { set; get; } + public string SiteName { get; set; } + +} + +public class ChangeControlList { + + public string IssueID { get; set; } + public string Title { get; set; } + public string MesaIdTitle { get; set; } + public string Owner { get; set; } + public string ChangeLevel { get; set; } + public DateTime? StartDate { get; set; } + public DateTime? StatusDate { get; set; } + public string PCRBStatus { get; set; } + public string Generations { get; set; } + public string Logistics { get; set; } + public string Processes { get; set; } + public string ToolTypes { get; set; } + public string ActionItemResponsibility { get; set; } + +} + +public class PCRValue { + + public string PCRValueID { set; get; } + public string PCRValueName { get; set; } + +} + +#endregion \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/Common.cs b/Fab2ApprovalSystem/Models/Common.cs index 3b416c6..db3022e 100644 --- a/Fab2ApprovalSystem/Models/Common.cs +++ b/Fab2ApprovalSystem/Models/Common.cs @@ -1,218 +1,202 @@ -using System; +#pragma warning disable CS8019 + +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; -using System.Web; + using Fab2ApprovalSystem.ViewModels; + +#if !NET8 using System.Web.Mvc; +#endif + using System.Text.RegularExpressions; -namespace Fab2ApprovalSystem.Models -{ - public class CredentialsStorage - { - public string UserName { get; set; } - public string Password { get; set; } +#pragma warning restore CS8019 + +namespace Fab2ApprovalSystem.Models; + +public class CredentialsStorage { + + public string UserName { get; set; } + public string Password { get; set; } + +} + +public class Lot { + + public int LotID { get; set; } + [Display(Name = "Wafer Lot#")] + public string LotNumber { get; set; } + public string ParentLotNumber { set; get; } + public int MRBNumber { get; set; } + public string MRBDispoType { get; set; } + public bool GoodToSubmit { get; set; } + public string SubmitErrorMessage { get; set; } + // Lot Disposition Issue Number + public int IssueID { get; set; } + public string IssueIDWithoutMRB { get; set; } + public string DieLotNumber { get; set; } + public string Description { get; set; } + [Display(Name = "New PN#")] + public string NewPartNo { get; set; } + [Display(Name = "WIP PN#")] + public string WipPartNo { get; set; } + [Display(Name = "Die PN#")] + public string DiePartNo { get; set; } + [Display(Name = "Device Type")] + public string ProductFamily { get; set; } + public string Gen { get; set; } + public string Channel { get; set; } + public string Hexsize { get; set; } + public double Voltage { get; set; } + public int WaferCount { get; set; } + public int ReleaseCount { get; set; } + public int ScrapCount { get; set; } + public int DieCount { get; set; } + public string Location { get; set; } + public double TotalCost { get; set; } + public int LotStatusOptionID { get; set; } + public string LotStatusOptionName { get; set; } + public double WaferCost { get; set; } + public double DieCost { get; set; } + + [UIHint("LotStatusOptionTemplate")] + [Display(Name = "Lot Status")] + public LotStatusOptionViewModel LotStatusOption { get; set; } + public ScrapLot ScrapLotWafer { get; set; } + + [Display(Name = "Lot Dispos")] + public string OtherLotDispos { get; set; } + + //MRB Lot + //[CustomDispoTypeValidationAttribute(ErrorMessage = "The values can only either A or B or C or D")] + public char? DispoType { get; set; } + [Display(Name = "Lot Dispos")] + public string LotDispositionsLinkedToLot { get; set; } + + [Display(Name = "MRBs")] + public string MRBsLinkedToLot { get; set; } + public string Status { get; set; } + public int OpenIssueWithExistingLots { get; set; } + public string QualityCode { get; set; } + + [Display(Name = "Source Lot#")] + public string SourceLot { get; set; } + public string SourceAction { get; set; } + public DateTime? SourceActionTime { get; set; } + public DateTime? SPNTransmitTime { get; set; } + public string SPNTransmitMsg { get; set; } + [Display(Name = "MRBs")] + public string OtherMRBs { get; set; } + public Lot() { + LotStatusOption = new LotStatusOptionViewModel(); + ScrapLotWafer = new ScrapLot(); } - public class Lot - { - public int LotID { get; set; } - [Display(Name = "Wafer Lot#")] - public string LotNumber { get; set; } - // public string ParentLotNumber { set; get { return LotNumber.Length >= 7 ? LotNumber.Substring(0, 7) : LotNumber; } } - public string ParentLotNumber { set; get; } + public bool IsDirty { get; set; } - public int MRBNumber { get; set; } - public string MRBDispoType { get; set; } - public bool GoodToSubmit { get; set; } - public string SubmitErrorMessage { get; set; } - // Lot Disposition Issue Number - public int IssueID { get; set; } - public string IssueIDWithoutMRB { get; set; } - public string DieLotNumber { get; set; } - public string Description { get; set; } - [Display(Name = "New PN#")] - public string NewPartNo { get; set; } - [Display(Name = "WIP PN#")] - public string WipPartNo { get; set; } - [Display(Name = "Die PN#")] - public string DiePartNo { get; set; } - [Display(Name = "Device Type")] - public string ProductFamily { get; set; } - public string Gen { get; set; } - public string Channel { get; set; } - public string Hexsize { get; set; } - public double Voltage { get; set; } - public int WaferCount { get; set; } - public int ReleaseCount { get; set; } - public int ScrapCount { get; set; } - public int DieCount { get; set; } - public string Location { get; set; } - public double TotalCost { get; set; } - public int LotStatusOptionID { get; set; } - public string LotStatusOptionName { get; set; } - public double WaferCost { get; set; } - public double DieCost { get; set; } +} - [UIHint("LotStatusOptionTemplate")] - [Display(Name = "Lot Status")] - public LotStatusOptionViewModel LotStatusOption { get; set; } +public class MRBHoldFlagReport { - public ScrapLot ScrapLotWafer { get; set; } + public string LotNo { get; set; } + public string TransactionType { get; set; } + public string PartNo { get; set; } + public string CurrentLocation { get; set; } + public string CurrentOperation { get; set; } + public int StartQty { get; set; } + public int CurrentQty { get; set; } + public string LotStatus { get; set; } + public string OperStatus { get; set; } + public string Successful { get; set; } + public string Comment { get; set; } + public string PriorMRBHoldLocation { get; set; } + public string PriorMRBHoldOperation { get; set; } + public string PriorMRB_DispoType { get; set; } + public string CurrentMRBHoldLocation { get; set; } + public string CurrentMRBHoldOperation { get; set; } + public string CurrentMRB_DispoType { get; set; } + public string MRB_DispoType { get; set; } + public DateTime TransactionDateTime { get; set; } + public string MRBLocation { get; set; } + public string MRBOperation { get; set; } + public bool Reprocess { get; set; } + public bool HasErrors { get; set; } - [Display(Name = "Lot Dispos")] - public string OtherLotDispos { get; set; } +} - //MRB Lot - //[CustomDispoTypeValidationAttribute(ErrorMessage = "The values can only either A or B or C or D")] - public char? DispoType { get; set; } - [Display(Name = "Lot Dispos")] - public string LotDispositionsLinkedToLot { get; set; } +public class MRBLotsTobeSentToSPN { - [Display(Name = "MRBs")] - public string MRBsLinkedToLot { get; set; } + public string LotNumber { get; set; } + public int MRBNumber { get; set; } + public char? DispoType { get; set; } + public char AddRemoveChangeMRBFlag { get; set; } + public bool IsDirty { get; set; } + public bool SentToSPN { get; set; } + public DateTime MRBLotLastSentToSPNDatetime { get; set; } - public string Status { get; set; } +} - public int OpenIssueWithExistingLots { get; set; } - public string QualityCode { get; set; } - - [Display(Name = "Source Lot#")] - public string SourceLot { get; set; } - public string SourceAction { get; set; } - public DateTime? SourceActionTime { get; set; } - public DateTime? SPNTransmitTime { get; set; } - public string SPNTransmitMsg { get; set; } - [Display(Name = "MRBs")] - public string OtherMRBs { get; set; } - - public Lot() - { - LotStatusOption = new LotStatusOptionViewModel(); - ScrapLotWafer = new ScrapLot(); - +#if !NET8 +[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] +public class CustomDispoTypeValidationAttribute : ValidationAttribute, IClientValidatable { + public override bool IsValid(object value) { + char tem = (char)value; + var productName = tem.ToString(); + if (!string.IsNullOrEmpty(productName)) { + return Regex.IsMatch(productName, "^[A,B,C,D]"); } - - public bool IsDirty { get; set; } - + return true; } - public class MRBHoldFlagReport - { - public string LotNo { get; set; } - public string TransactionType { get; set; } - - public string PartNo { get; set; } - public string CurrentLocation { get; set; } - public string CurrentOperation { get; set; } - public int StartQty { get; set; } - public int CurrentQty { get; set; } - public string LotStatus { get; set; } - public string OperStatus { get; set; } - public string Successful { get; set; } - public string Comment { get; set; } - - public string PriorMRBHoldLocation { get; set; } - public string PriorMRBHoldOperation { get; set; } - public string PriorMRB_DispoType { get; set; } - - public string CurrentMRBHoldLocation { get; set; } - public string CurrentMRBHoldOperation { get; set; } - public string CurrentMRB_DispoType { get; set; } - - - public string MRB_DispoType { get; set; } - public DateTime TransactionDateTime { get; set; } - public string MRBLocation { get; set; } - public string MRBOperation { get; set; } - - public bool Reprocess { get; set; } - - public bool HasErrors { get; set; } - - + public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { + yield return new ModelClientValidationRule { + ErrorMessage = ErrorMessage, + ValidationType = "dispotypevalidation" + }; } +} +#endif - public class MRBLotsTobeSentToSPN - { - public string LotNumber { get; set; } - public int MRBNumber { get; set; } - public char? DispoType { get; set; } - public char AddRemoveChangeMRBFlag { get; set; } - public bool IsDirty { get; set; } - public bool SentToSPN { get; set; } - public DateTime MRBLotLastSentToSPNDatetime { get; set; } - - } +public class Department { - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] - public class CustomDispoTypeValidationAttribute : ValidationAttribute, IClientValidatable - { - public override bool IsValid(object value) - { - char tem = (char)value; - var productName = tem.ToString(); - if (!string.IsNullOrEmpty(productName)) - { - return Regex.IsMatch(productName, "^[A,B,C,D]"); - } - return true; - } + public int DepartmentID { get; set; } + public string DepartmentName { get; set; } - public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) - { - yield return new ModelClientValidationRule - { - ErrorMessage = ErrorMessage, - ValidationType = "dispotypevalidation" - }; - } - } +} - /// - /// - /// - public class Department - { - //public int LotDispoDepartmentID { get; set; } - //public int IssueID { get; set; } - public int DepartmentID { get; set; } - public string DepartmentName { get; set; } - } +public class AffectedModule { - /// - /// - /// - public class AffectedModule - { - public int ModuleID { get; set; } - public string ModuleName { get; set; } + public int ModuleID { get; set; } + public string ModuleName { get; set; } - } +} - public class WIPPart - { - public string WIPPartData { get; set; } - public string PartNumber { get; set; } - public string SiliconPartNumber { get; set; } - public string ProcessFlow { get; set; } - } +public class WIPPart { - public class ProductFamilies - { - public int ProductFamilyID { get; set; } - public string ProductFamily { get; set; } - } + public string WIPPartData { get; set; } + public string PartNumber { get; set; } + public string SiliconPartNumber { get; set; } + public string ProcessFlow { get; set; } - public class LotSplitAnalysisResult - { - public int ID { get; set; } - public string ParentLotNo { get; set; } - public string LotNo { get; set; } - public DateTime ActionTime { get; set; } - public string ActionType { get; set; } - public bool? IsAffected { get; set; } - } +} + +public class ProductFamilies { + + public int ProductFamilyID { get; set; } + public string ProductFamily { get; set; } + +} + +public class LotSplitAnalysisResult { + + public int ID { get; set; } + public string ParentLotNo { get; set; } + public string LotNo { get; set; } + public DateTime ActionTime { get; set; } + public string ActionType { get; set; } + public bool? IsAffected { get; set; } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/ECNModel.cs b/Fab2ApprovalSystem/Models/ECNModel.cs index 0c5575c..76a66b9 100644 --- a/Fab2ApprovalSystem/Models/ECNModel.cs +++ b/Fab2ApprovalSystem/Models/ECNModel.cs @@ -1,239 +1,208 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Linq; using System.Reflection; -using System.Web; -namespace Fab2ApprovalSystem.Models -{ - public class ECN :System.Object - { - public string Title { get; set; } - public int ECNNumber {get;set;} +namespace Fab2ApprovalSystem.Models; - [DataType(DataType.Date)] - public DateTime IssueDate {get;set;} +public class ECN : object { - - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? SubmitedDate { get; set; } + public string Title { get; set; } + public int ECNNumber { get; set; } - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? CloseDate { get; set; } + [DataType(DataType.Date)] + public DateTime IssueDate { get; set; } - public int OriginatorID { get; set; } - public string OriginatorName { get; set; } - // important!!make sure the id of the control matches the name of the field in the model it is being binded to, - // in order to get the selected items from the control - public List DepartmentIDs { get; set; } - - public List ModuleIDs { get; set; } - public List AreaIDs { get; set; } - public List TechnologyIDs { get; set; } - public List AcknowledgementByIDs { get; set; } - public List TrainingByIDs { get; set; } + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? SubmitedDate { get; set; } - public bool IsECN { get; set; } - public bool IsTECN { get; set; } - public bool IsEmergencyTECN { get; set; } + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? CloseDate { get; set; } + public int OriginatorID { get; set; } + public string OriginatorName { get; set; } + // important!!make sure the id of the control matches the name of the field in the model it is being binded to, + // in order to get the selected items from the control + public List DepartmentIDs { get; set; } + public List ModuleIDs { get; set; } + public List AreaIDs { get; set; } + public List TechnologyIDs { get; set; } + public List AcknowledgementByIDs { get; set; } + public List TrainingByIDs { get; set; } + public bool IsECN { get; set; } + public bool IsTECN { get; set; } + public bool IsEmergencyTECN { get; set; } - [DataType(DataType.Date)] - //[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? ExpirationDate { get; set; } + [DataType(DataType.Date)] + //[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? ExpirationDate { get; set; } - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? ExtensionDate { get; set; } + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? ExtensionDate { get; set; } - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? CancellationDate { get; set; } - - public bool AcknowledgementRequired { get; set; } - public bool TrainingRequired { get; set; } - public int? AreaID { get; set; } - public int? TechnologyID { get; set; } - public bool PCRBRequired { get; set; } - public string PCRBNumber { get; set; } - public bool TestProgramChangeRequired { get; set; } - public bool SPCChangeRequired { get; set; } - public bool NewPartFlowRequired { get; set; } - public bool SPNChangeRequired { get; set; } - public string ImplementationDetails { get; set; } - public int ImpactOnEnvironment { get; set; } - public string ImpactOnEnvironmentDescription { get; set; } - public int ImpactOnCapacity { get; set; } - public string ImpactOnCapacityDescription { get; set; } - public bool IsMA { get; set; } - public bool IsRH { get; set; } - public bool IsAU { get; set; } - public bool IsIndustrial { get; set; } - public int MaterialConsumptionChangeRequired { get; set; } - public string MaterialConsumptionChangeDescription { get; set; } - public string ReasonForChange { get; set; } - public string DescriptionOfChange { get; set; } - public bool NotAFlowChange { get; set; } - public bool AttachECN_TECNToLots { get; set; } - public bool SPNFlowChangeAtSingleStep { get; set; } - public bool SPNFlowChangeAtMultipleSteps { get; set; } - public byte CurrentStep{ get; set; } - public bool TECNExtensionState { get; set; } - public bool Cancelled { get; set; } - - public bool CancellationApproved { get; set; } - public bool CancellationInProgress { get; set; } - public DateTime? CancellationApprovalDate { get; set; } - public bool ExpirationProcessed {get;set;} - public bool ExpirationInProgress { get; set; } - public DateTime? ExpirationProcessedlDate { get; set; } - public bool ReSubmitted { get; set; } - public bool Converted { get; set; } - public string ConvertedToType { get; set; } - public int? ConvertedToNumber { get; set; } - public int? ConvertedFromNumber { get; set; } - public int WorkFlowNumber { get; set; } - public bool LockedForConversion { get; set; } - public bool ConversionRejected { get; set; } - public bool ConversionApprovalInProgress { get; set; } - public bool RecordLockIndicator { get; set; } - public int RecordLockedBy { get; set; } - public string RecordLockByName { get; set; } - public DateTime? RecordLockedDate { get; set; } - public int LastUpdatedBy { get; set; } - public DateTime? LastUpdateDate { get; set; } - public DateTime LastUpdateTimeStamp { get; set; } - - public int? CategoryID { get; set; } - - public bool FIChangeRequired { get; set; } - public string NumberOfLotsAffected { get; set; } - public bool? RecipeChange { get; set; } - public List ProductFamilyIDs { get; set; } - - public bool Deleted { get; set; } - public bool IsDocEC { get; set; } - public bool MetrologyChangeRequired { get; set; } - public ECN() - { - DepartmentIDs = new List(); - ModuleIDs = new List(); - AreaIDs = new List(); - TechnologyIDs = new List(); - AcknowledgementByIDs = new List(); - TrainingByIDs = new List(); - ProductFamilyIDs = new List(); - } - - - - public override bool Equals(System.Object obj) - { - // If parameter is null return false. - if (obj == null) - { - return false; - } - - // If parameter cannot be cast to Point return false. - ECN p = obj as ECN; - if ((System.Object)p == null) - { - return false; - } - - // Return true if the fields match: - return (IsECN == p.IsECN) && (IsEmergencyTECN == p.IsEmergencyTECN); - } - - /// - /// - /// - /// - /// - public bool Equals(ECN p) - { - // If parameter is null return false: - if ((object)p == null) - { - return false; - } - - - foreach (PropertyInfo pi in p.GetType().GetProperties()) - { - foreach(PropertyInfo px in this.GetType().GetProperties()) - { - if (pi.Name.ToLower() == px.Name.ToLower()) - { - if (pi.GetValue(p).Equals(px.GetValue(this))) - break; - else - return false; - } - } - - } + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? CancellationDate { get; set; } + public bool AcknowledgementRequired { get; set; } + public bool TrainingRequired { get; set; } + public int? AreaID { get; set; } + public int? TechnologyID { get; set; } + public bool PCRBRequired { get; set; } + public string PCRBNumber { get; set; } + public bool TestProgramChangeRequired { get; set; } + public bool SPCChangeRequired { get; set; } + public bool NewPartFlowRequired { get; set; } + public bool SPNChangeRequired { get; set; } + public string ImplementationDetails { get; set; } + public int ImpactOnEnvironment { get; set; } + public string ImpactOnEnvironmentDescription { get; set; } + public int ImpactOnCapacity { get; set; } + public string ImpactOnCapacityDescription { get; set; } + public bool IsMA { get; set; } + public bool IsRH { get; set; } + public bool IsAU { get; set; } + public bool IsIndustrial { get; set; } + public int MaterialConsumptionChangeRequired { get; set; } + public string MaterialConsumptionChangeDescription { get; set; } + public string ReasonForChange { get; set; } + public string DescriptionOfChange { get; set; } + public bool NotAFlowChange { get; set; } + public bool AttachECN_TECNToLots { get; set; } + public bool SPNFlowChangeAtSingleStep { get; set; } + public bool SPNFlowChangeAtMultipleSteps { get; set; } + public byte CurrentStep { get; set; } + public bool TECNExtensionState { get; set; } + public bool Cancelled { get; set; } + public bool CancellationApproved { get; set; } + public bool CancellationInProgress { get; set; } + public DateTime? CancellationApprovalDate { get; set; } + public bool ExpirationProcessed { get; set; } + public bool ExpirationInProgress { get; set; } + public DateTime? ExpirationProcessedlDate { get; set; } + public bool ReSubmitted { get; set; } + public bool Converted { get; set; } + public string ConvertedToType { get; set; } + public int? ConvertedToNumber { get; set; } + public int? ConvertedFromNumber { get; set; } + public int WorkFlowNumber { get; set; } + public bool LockedForConversion { get; set; } + public bool ConversionRejected { get; set; } + public bool ConversionApprovalInProgress { get; set; } + public bool RecordLockIndicator { get; set; } + public int RecordLockedBy { get; set; } + public string RecordLockByName { get; set; } + public DateTime? RecordLockedDate { get; set; } + public int LastUpdatedBy { get; set; } + public DateTime? LastUpdateDate { get; set; } + public DateTime LastUpdateTimeStamp { get; set; } + public int? CategoryID { get; set; } + public bool FIChangeRequired { get; set; } + public string NumberOfLotsAffected { get; set; } + public bool? RecipeChange { get; set; } + public List ProductFamilyIDs { get; set; } + public bool Deleted { get; set; } + public bool IsDocEC { get; set; } + public bool MetrologyChangeRequired { get; set; } + public ECN() { + DepartmentIDs = new List(); + ModuleIDs = new List(); + AreaIDs = new List(); + TechnologyIDs = new List(); + AcknowledgementByIDs = new List(); + TrainingByIDs = new List(); + ProductFamilyIDs = new List(); + } + public override bool Equals(object obj) { + // If parameter is null return false. + if (obj == null) { return false; - // Return true if the fields match: - //return (IsECN == p.IsECN) && (IsEmergencyTECN == p.IsEmergencyTECN); + } + + // If parameter cannot be cast to Point return false. + ECN p = obj as ECN; + if (p == null) { + return false; + } + + // Return true if the fields match: + return (IsECN == p.IsECN) && (IsEmergencyTECN == p.IsEmergencyTECN); + } + + public bool Equals(ECN p) { + // If parameter is null return false: + if (p == null) { + return false; + } + + foreach (PropertyInfo pi in p.GetType().GetProperties()) { + foreach (PropertyInfo px in GetType().GetProperties()) { + if (pi.Name.ToLower() == px.Name.ToLower()) { + if (pi.GetValue(p).Equals(px.GetValue(this))) + break; + else + return false; + } + } } - - } - - - public class ECNAffectedDeparmtent - { - //public int LotDispoDepartmentID { get; set; } - //public int IssueID { get; set; } - public int DepartmentID { get; set; } - public string DepartmentName { get; set; } - } - - public class ECNAffectedModule - { - public int ModuleID { get; set; } - public string ModuleName { get; set; } - - } - - public class ECNCategory - { - public int CategoryID { get; set; } - public string CategoryName { get; set; } - } - - public class ECNAttachment - { - public int AttachmentID { set; get; } - public int ECNNumber { get; set; } - public string FileName { get; set; } - public int UserID { get; set; } - // extrafield - public string FullName { get; set; } - public string UploadDate { get; set; } - public string Path { get; set; } - - } - - public class ECNArea - { - public int AreaID { set; get; } - public string Area { get; set; } - } - - public class ECNTechnology - { - public int TechnologyID { get; set; } - public string Technology { get; set; } - } - - - public class ECNAcknowledgementTrainingBy - { - public int AcknowledgementTrainingByID { get; set; } - public string AcknowledgementTrainingBy { get; set; } + return false; + // Return true if the fields match: + //return (IsECN == p.IsECN) && (IsEmergencyTECN == p.IsEmergencyTECN); } } + +public class ECNAffectedDeparmtent { + + public int DepartmentID { get; set; } + public string DepartmentName { get; set; } + +} + +public class ECNAffectedModule { + + public int ModuleID { get; set; } + public string ModuleName { get; set; } + +} + +public class ECNCategory { + + public int CategoryID { get; set; } + public string CategoryName { get; set; } + +} + +public class ECNAttachment { + + public int AttachmentID { set; get; } + public int ECNNumber { get; set; } + public string FileName { get; set; } + public int UserID { get; set; } + // extrafield + public string FullName { get; set; } + public string UploadDate { get; set; } + public string Path { get; set; } + +} + +public class ECNArea { + + public int AreaID { set; get; } + public string Area { get; set; } + +} + +public class ECNTechnology { + + public int TechnologyID { get; set; } + public string Technology { get; set; } + +} + +public class ECNAcknowledgementTrainingBy { + + public int AcknowledgementTrainingByID { get; set; } + public string AcknowledgementTrainingBy { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/ECNTypeChangeLog.cs b/Fab2ApprovalSystem/Models/ECNTypeChangeLog.cs index 8f65e26..edbbb95 100644 --- a/Fab2ApprovalSystem/Models/ECNTypeChangeLog.cs +++ b/Fab2ApprovalSystem/Models/ECNTypeChangeLog.cs @@ -1,17 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +namespace Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.Models -{ - public class ECNTypeChangeLog - { - public int ECNNumber; - public int UserID; - public string ECNTypeFrom; - public string ECNTypeTo; +public class ECNTypeChangeLog { + public int ECNNumber; + public int UserID; + public string ECNTypeFrom; + public string ECNTypeTo; - } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/EightDModel.cs b/Fab2ApprovalSystem/Models/EightDModel.cs index f12e401..8b27289 100644 --- a/Fab2ApprovalSystem/Models/EightDModel.cs +++ b/Fab2ApprovalSystem/Models/EightDModel.cs @@ -1,464 +1,408 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.Models -{ - public class AuditList - { - public string AuditNo { get; set; } - public string AuditTitle { get; set; } - public string AuditType { get; set; } - public string Auditors { get; set; } - public string PendingCAFindingsAIOwners { get; set; } - public string PendingCAOwners { get; set; } - public DateTime? AuditDate { get; set; } - public string FindingCategories { get; set; } - public string AuditedAreas { get; set; } - public string CADisp { get; set; } - public string CorrectiveActions { get; set; } - public string AuditScore { get; set; } - public string AuditStatus { get; set; } +namespace Fab2ApprovalSystem.Models; + +public class AuditList { + + public string AuditNo { get; set; } + public string AuditTitle { get; set; } + public string AuditType { get; set; } + public string Auditors { get; set; } + public string PendingCAFindingsAIOwners { get; set; } + public string PendingCAOwners { get; set; } + public DateTime? AuditDate { get; set; } + public string FindingCategories { get; set; } + public string AuditedAreas { get; set; } + public string CADisp { get; set; } + public string CorrectiveActions { get; set; } + public string AuditScore { get; set; } + public string AuditStatus { get; set; } + +} + +public class Audit { + + public int AuditNo { set; get; } + public int OriginatorID { get; set; } + public string OriginatorName { get; set; } + public string AuditTitle { get; set; } + public int AuditScore { get; set; } + public DateTime? AuditDate { get; set; } + public string AuditFindingCategories { get; set; } + public int AuditStatus { get; set; } + public string NoOfMajorNonConformities { get; set; } + public string NoOfMinorNonConformities { get; set; } + public string NoOf5SFindings { get; set; } + public string NoOfOFIFindings { get; set; } + public string Auditees { get; set; } + public List AuditorIDs { get; set; } + public List AuditTypeIDs { get; set; } + public List AuditedAreaIDs { get; set; } + public List AuditedStandardIDs { get; set; } + public bool RecordLockIndicator { get; set; } + public int RecordLockedBy { get; set; } + public bool RecordLocked { get; set; } + public DateTime RecordLockedDate { get; set; } + public DateTime LastUpdateDate { get; set; } + public CAFindings CAFindings { get; set; } + public Audit() { + AuditorIDs = new List(); + AuditTypeIDs = new List(); + AuditedAreaIDs = new List(); + CAFindings = new CAFindings(); } +} +public class Auditees { + private string UserName { get; set; } - public class Audit - { - public int AuditNo { set; get; } - public int OriginatorID { get; set; } - public string OriginatorName { get; set; } - public string AuditTitle { get; set; } - //public int AuditTypeID { get; set; } - public int AuditScore { get; set; } - public DateTime? AuditDate { get; set; } - //public int Auditors { get; set; } // List of Auditors - public string AuditFindingCategories { get; set; } - public int AuditStatus { get; set; } - //public int AuditedAreaID { get; set; } - public string NoOfMajorNonConformities { get; set; } - public string NoOfMinorNonConformities { get; set; } - public string NoOf5SFindings { get; set; } - public string NoOfOFIFindings { get; set; } - public string Auditees { get; set; } - public List AuditorIDs { get; set; } - public List AuditTypeIDs { get; set; } - public List AuditedAreaIDs { get; set; } - public List AuditedStandardIDs { get; set; } - public bool RecordLockIndicator { get; set; } - public int RecordLockedBy { get; set; } - public bool RecordLocked { get; set; } - public DateTime RecordLockedDate { get; set; } - public DateTime LastUpdateDate { get; set; } - public CAFindings CAFindings { get; set; } - public Audit() - { - AuditorIDs = new List(); - AuditTypeIDs = new List(); - AuditedAreaIDs = new List(); - CAFindings = new CAFindings(); - } - } - public class Auditees - { - string UserName { get; set; } - } +} - public class AuditType - { - public int AuditTypeID { get; set; } - public string AuditTypeName { get; set; } - } +public class AuditType { - public class Auditor - { - public int AuditorID { get; set; } - public string AuditorName { get; set; } - } + public int AuditTypeID { get; set; } + public string AuditTypeName { get; set; } - /// - /// - /// +} - public class AuditedArea - { - public int AuditedAreaID { get; set; } - public string AuditedAreaName { get; set; } - } +public class Auditor { - /// - /// - /// - public class AuditFindings - { - public int ID { get; set; } - public int AuditNo { get; set; } - public string Findings { get; set; } - public string ViolatedClause { get; set; } - public string FindingType { get; set; } - public string AuditFindingCategoryID { get; set; } - public string FindingCategories { get; set; } - public int CANo { get; set; } - public string CANoDisp { get; set; } - public string CAStatus { get; set; } - public int CAOwnerID { get; set; } - public string CAOwner { get; set; } - public DateTime AssignedDate { get; set; } - public string Title { get; set; } + public int AuditorID { get; set; } + public string AuditorName { get; set; } - } +} - /// - /// - /// - public class AuditFindingCategory - { - public int AuditFindingCategoryID { get; set; } - public string AuditFindingCategoryName { get; set; } - } +/// +/// +/// +public class AuditedArea { - public class AuditReportAttachment - { - public int ID { get; set; } - public string FileGUID { get; set; } - public string FileName { get; set; } - public int UploadedByID { get; set; } - public int? CAFindingsID { get; set; } - public string UploadedByName { get; set; } - public DateTime? UploadDateTime { get; set; } - public string Title { get; set; } - public string RequirementsNotes { get; set; } - public string Comments { get; set; } - public int AuditNo { get; set; } + public int AuditedAreaID { get; set; } + public string AuditedAreaName { get; set; } - } +} +public class AuditFindings { - - /// - /// - /// - public class CorrectiveAction - { - public int CANo { get; set; } - public string CANoDisp { get; set; } - public int AuditNo { get; set; } - public int RequestorID { get; set; } - public string RequestorName { get; set; } - public string CATitle { get; set; } - public bool D0Completed { get; set; } - public DateTime? D0CompleteDate { get; set; } - public bool D0Approved { get; set; } - public DateTime? D0ApprovedDate { get; set; } - public bool TriggerApproval { get; set; } - public bool TriggerSectionApproval { get; set; } - public string SectionApproval { get; set; } - public DateTime? IssueDate { get; set; } - public string CAType { get; set; } - public bool IsCACompleted { get; set; } - public DateTime CACompletedDate { get; set; } - public int ApprovalStatus { get; set; } - public int WorkFlowNumber { get; set; } - public byte CurrentStep { get; set; } - public int D1AssigneeID { get; set; } - public int CurrentD1AssigneeID { get; set; } - public string D1AssigneeName { get; set; } - public int CASourceID { get; set; } - public string CASource { get; set; } - public int ModuleID { get; set; } - public int Status { get; set; } - public string StatusName { get; set; } - public string Stage { get; set; } - public int QAID { get; set; } - public string PendingApprovers { get; set; } - public string PendingAIOwners { get; set; } - public string Tools { get; set; } - public string RelatedMRB { get; set; } - public int RelatedAudit { get; set; } - public string D2ProblemDescription { get; set; } - public List RiskAssessmentAreaIDs { get; set; } - public List ModuleIDs { get; set; } - public string D3RiskAssessmentNotes { get; set; } - public bool D3Completed { get; set; } - public DateTime? D3CompleteDate { get; set; } - public bool D3Approved { get; set; } - public DateTime? D3ApprovedDate { get; set; } - public DateTime? D3DueDate { get; set; } - public string D4RootCause1 { get; set; } - public string D4RootCause2 { get; set; } - public string D4RootCause3 { get; set; } - public string D4RootCause4 { get; set; } - public DateTime? D4CompleteDate { get; set; } - public bool D4Completed { get; set; } - public bool D4Approved { get; set; } - public DateTime? D4ApprovedDate { get; set; } - public DateTime? D5CompleteDate { get; set; } - public bool D5Completed { get; set; } - public DateTime? D6ValidatedDate { get; set; } - public bool D6Validated { get; set; } - public DateTime? D7CompleteDate { get; set; } - public bool D7Completed { get; set; } - public bool D5Approved { get; set; } - public DateTime? D5ApprovedDate { get; set; } - public DateTime? D5D7DueDate { get; set; } - public DateTime? D8DueDate { get; set; } - public DateTime? D8CompletedDate { get; set; } - public bool D8Completed { get; set; } - public DateTime? D8ApprovedDate { get; set; } - public bool D8Approved { get; set; } - public string D8TeamRecognition { get; set; } - public string D8LessonsLearned { get; set; } - public string TeamMembers { get; set; } - public DateTime? ApprovedDate { get; set; } - public bool RecordLockIndicator { get; set; } - public int RecordLockedBy { get; set; } - public string RecordLockByName { get; set; } - public bool RecordLocked { get; set; } - public DateTime RecordLockedDate { get; set; } - public DateTime LastUpdateDate { get; set; } - public List TeamMemberIDs { get; set; } - public D5D6CorrectivetAction D5D6CorrectivetAction { get; set; } - public D7PreventiveAction D7PreventiveAction { get; set; } - public string D0Comments { get; set; } - public int TeamCaptainID { get; set; } - public string TeamCaptainName { get; set; } - public int CASponsorID { get; set; } - public string CASponsorName { get; set; } - public string CustomerName { get; set; } - public string CustomerPartNo { get; set; } - public string IFXPartNo { get; set; } - public int PartQty { get; set; } - public string InvoiceNo { get; set; } - public string PurchaseOrderNo { get; set; } - public string SalesOrderNo { get; set; } - public double DollarImpact { get; set; } - public string BackgroundInfo { get; set; } - public string Analysis { get; set; } - public string VisualVerification { get; set; } - public string InterimContainmentAction { get; set; } - public string ICAVerificationResults { get; set; } - public string ICAValidationActivities { get; set; } - public string RootCauseVerification { get; set; } - public string EscapePoint { get; set; } - public DateTime? NextDueDate { get; set; } - public DateTime? FollowUpDate { get; set; } - public bool CASubmitted { get; set; } + public int ID { get; set; } + public int AuditNo { get; set; } + public string Findings { get; set; } + public string ViolatedClause { get; set; } + public string FindingType { get; set; } + public string AuditFindingCategoryID { get; set; } + public string FindingCategories { get; set; } + public int CANo { get; set; } + public string CANoDisp { get; set; } + public string CAStatus { get; set; } + public int CAOwnerID { get; set; } + public string CAOwner { get; set; } + public DateTime AssignedDate { get; set; } + public string Title { get; set; } - public DateTime? ClosedDate { get; set; } +} - public CorrectiveAction() - { - TeamMemberIDs = new List(); - ModuleIDs = new List(); - RiskAssessmentAreaIDs = new List(); - D5D6CorrectivetAction = new D5D6CorrectivetAction(); - D7PreventiveAction = new D7PreventiveAction(); - - } - - } +public class AuditFindingCategory { - /// - /// - /// - public class CASource - { - public int CASourceID { get; set; } - public string CASourceName { get; set; } - } + public int AuditFindingCategoryID { get; set; } + public string AuditFindingCategoryName { get; set; } +} - /// - /// - /// - public class CAUserList - { - public int UserID { get; set; } - public string UserName { get; set; } - } +public class AuditReportAttachment { + public int ID { get; set; } + public string FileGUID { get; set; } + public string FileName { get; set; } + public int UploadedByID { get; set; } + public int? CAFindingsID { get; set; } + public string UploadedByName { get; set; } + public DateTime? UploadDateTime { get; set; } + public string Title { get; set; } + public string RequirementsNotes { get; set; } + public string Comments { get; set; } + public int AuditNo { get; set; } - /// - /// - /// - public class CAModule - { - public int ModuleID { get; set; } - public string ModuleName { get; set; } - } +} +public class CorrectiveAction { - /// - /// - /// - public class CA_Attachment - { - public int ID { get; set; } - public string FileGUID { get; set; } - public string FileName { get; set; } - public string FileExtension { get; set; } - public string Section { get; set; } - public int UploadedByID { get; set; } - public string UploadedByName { get; set; } - public DateTime? UploadDateTime { get; set; } - public string Title { get; set; } - public string RequirementsNotes { get; set; } - public string Comments { get; set; } - public int? CANo { get; set; } - public int? D5D6CAID { get; set; } - public int? D7PAID { get; set; } - public int? CAFindingsID { get; set; } - } - - - /// - /// - /// - public class D3ContainmentAction - { - public int ID { get; set; } - public int CANo { get; set; } - public string Section { get; set; } - public string ContainmentAction { get; set; } - public string Result { get; set; } - public string ECNLinks { get; set; } - public int ResponsibilityOwnerID { get; set; } - public int CurrentResponsibilityOwnerID { get; set; } - public string ResponsibilityOwnerName { get; set; } - public DateTime? ECD { get; set; } - public DateTime? ImplementedDate { get; set; } - public DateTime AssignedDate { get; set; } - - - } - - - /// - /// - /// - public class RiskAssessmentArea - { - public int RiskAssessmentAreaID { get; set; } - public string RiskAssessmentAreaName { get; set; } - } - - - /// - /// - /// - public class D5D6CorrectivetAction - { - public int ID { get; set; } - public int CANo { get; set; } - public string CorrectiveAction { get; set; } - public string CARequired { get; set; } - public string Result { get; set; } - public string ECNLinks { get; set; } - public string AttachmentLinks { get; set; } - public int ResponsibilityOwnerID { get; set; } - public int CurrentResponsibilityOwnerID { get; set; } - public string ResponsibilityOwnerName { get; set; } - public DateTime? ECD { get; set; } - public DateTime? ImplementedDate { get; set; } - public bool IsImplemented { get; set; } - public string ImprovementID { get; set; } - public string Improvement { get; set; } - public CA_Attachment CA_Attachment { get; set; } - public DateTime AssignedDate { get; set; } - public bool Approved { get; set; } - - public D5D6CorrectivetAction() - { - CA_Attachment = new CA_Attachment(); - } - public string ActionType { get; set; } - - } - - - /// - /// - /// - public class D5D6Improvement - { - public int D5D6ImprovementID { get; set; } - public string D5D6ImprovementName { get; set; } - } - - /// - /// - /// - public class D7PreventiveAction - { - public int ID { get; set; } - public int CANo { get; set; } - public string PreventiveAction { get; set; } - public string Result { get; set; } - public string ECNLinks { get; set; } - public string AttachmentLinks { get; set; } - public int ResponsibilityOwnerID { get; set; } - public int CurrentResponsibilityOwnerID { get; set; } - public string ResponsibilityOwnerName { get; set; } - public DateTime? ECD { get; set; } - public DateTime? ImplementedDate { get; set; } - public CA_Attachment CA_Attachment { get; set; } - public DateTime AssignedDate { get; set; } - - public D7PreventiveAction() - { - CA_Attachment = new CA_Attachment(); - } - - } - - public class CAFindings - { - public int ID { get; set; } - public int AuditNo { get; set; } - public string CAFinding { get; set; } - public string CorrectiveAction { get; set; } - public string Result { get; set; } - public string AttachmentLinks { get; set; } - public int? CurrentResponsibilityOwnerID { get; set; } - public int? ResponsibilityOwnerID { get; set; } - public string ResponsibilityOwnerName { get; set; } - public DateTime? ECD { get; set; } - public DateTime? ImplementedDate { get; set; } - public AuditReportAttachment Audit_Attachment { get; set; } - public DateTime AssignedDate { get; set; } - - public CAFindings() - { - Audit_Attachment = new AuditReportAttachment(); - } - - } - public class CASectionApproval - { - public string DSection { get; set; } - public string Fullname { get; set; } - public string ApprovalStatus { get; set; } - public DateTime? DateAssigned { get; set; } - public DateTime? DateCompleted { get; set; } - public string Comments { get; set; } - } - - /// - /// - /// - public class CANoList - { - public int CANo { get; set; } - public string CANoDisp { get; set; } - } - - public class CAD3D5D7Due - { - public int CANo { get; set; } - public DateTime DueDate { get; set; } - public string ItemDue { get; set; } - public string ExpiryType { get; set; } + public int CANo { get; set; } + public string CANoDisp { get; set; } + public int AuditNo { get; set; } + public int RequestorID { get; set; } + public string RequestorName { get; set; } + public string CATitle { get; set; } + public bool D0Completed { get; set; } + public DateTime? D0CompleteDate { get; set; } + public bool D0Approved { get; set; } + public DateTime? D0ApprovedDate { get; set; } + public bool TriggerApproval { get; set; } + public bool TriggerSectionApproval { get; set; } + public string SectionApproval { get; set; } + public DateTime? IssueDate { get; set; } + public string CAType { get; set; } + public bool IsCACompleted { get; set; } + public DateTime CACompletedDate { get; set; } + public int ApprovalStatus { get; set; } + public int WorkFlowNumber { get; set; } + public byte CurrentStep { get; set; } + public int D1AssigneeID { get; set; } + public int CurrentD1AssigneeID { get; set; } + public string D1AssigneeName { get; set; } + public int CASourceID { get; set; } + public string CASource { get; set; } + public int ModuleID { get; set; } + public int Status { get; set; } + public string StatusName { get; set; } + public string Stage { get; set; } + public int QAID { get; set; } + public string PendingApprovers { get; set; } + public string PendingAIOwners { get; set; } + public string Tools { get; set; } + public string RelatedMRB { get; set; } + public int RelatedAudit { get; set; } + public string D2ProblemDescription { get; set; } + public List RiskAssessmentAreaIDs { get; set; } + public List ModuleIDs { get; set; } + public string D3RiskAssessmentNotes { get; set; } + public bool D3Completed { get; set; } + public DateTime? D3CompleteDate { get; set; } + public bool D3Approved { get; set; } + public DateTime? D3ApprovedDate { get; set; } + public DateTime? D3DueDate { get; set; } + public string D4RootCause1 { get; set; } + public string D4RootCause2 { get; set; } + public string D4RootCause3 { get; set; } + public string D4RootCause4 { get; set; } + public DateTime? D4CompleteDate { get; set; } + public bool D4Completed { get; set; } + public bool D4Approved { get; set; } + public DateTime? D4ApprovedDate { get; set; } + public DateTime? D5CompleteDate { get; set; } + public bool D5Completed { get; set; } + public DateTime? D6ValidatedDate { get; set; } + public bool D6Validated { get; set; } + public DateTime? D7CompleteDate { get; set; } + public bool D7Completed { get; set; } + public bool D5Approved { get; set; } + public DateTime? D5ApprovedDate { get; set; } + public DateTime? D5D7DueDate { get; set; } + public DateTime? D8DueDate { get; set; } + public DateTime? D8CompletedDate { get; set; } + public bool D8Completed { get; set; } + public DateTime? D8ApprovedDate { get; set; } + public bool D8Approved { get; set; } + public string D8TeamRecognition { get; set; } + public string D8LessonsLearned { get; set; } + public string TeamMembers { get; set; } + public DateTime? ApprovedDate { get; set; } + public bool RecordLockIndicator { get; set; } + public int RecordLockedBy { get; set; } + public string RecordLockByName { get; set; } + public bool RecordLocked { get; set; } + public DateTime RecordLockedDate { get; set; } + public DateTime LastUpdateDate { get; set; } + public List TeamMemberIDs { get; set; } + public D5D6CorrectivetAction D5D6CorrectivetAction { get; set; } + public D7PreventiveAction D7PreventiveAction { get; set; } + public string D0Comments { get; set; } + public int TeamCaptainID { get; set; } + public string TeamCaptainName { get; set; } + public int CASponsorID { get; set; } + public string CASponsorName { get; set; } + public string CustomerName { get; set; } + public string CustomerPartNo { get; set; } + public string IFXPartNo { get; set; } + public int PartQty { get; set; } + public string InvoiceNo { get; set; } + public string PurchaseOrderNo { get; set; } + public string SalesOrderNo { get; set; } + public double DollarImpact { get; set; } + public string BackgroundInfo { get; set; } + public string Analysis { get; set; } + public string VisualVerification { get; set; } + public string InterimContainmentAction { get; set; } + public string ICAVerificationResults { get; set; } + public string ICAValidationActivities { get; set; } + public string RootCauseVerification { get; set; } + public string EscapePoint { get; set; } + public DateTime? NextDueDate { get; set; } + public DateTime? FollowUpDate { get; set; } + public bool CASubmitted { get; set; } + public DateTime? ClosedDate { get; set; } + public CorrectiveAction() { + TeamMemberIDs = new List(); + ModuleIDs = new List(); + RiskAssessmentAreaIDs = new List(); + D5D6CorrectivetAction = new D5D6CorrectivetAction(); + D7PreventiveAction = new D7PreventiveAction(); } } + +public class CASource { + + public int CASourceID { get; set; } + public string CASourceName { get; set; } + +} + +public class CAUserList { + + public int UserID { get; set; } + public string UserName { get; set; } + +} + +public class CAModule { + + public int ModuleID { get; set; } + public string ModuleName { get; set; } + +} + +public class CA_Attachment { + + public int ID { get; set; } + public string FileGUID { get; set; } + public string FileName { get; set; } + public string FileExtension { get; set; } + public string Section { get; set; } + public int UploadedByID { get; set; } + public string UploadedByName { get; set; } + public DateTime? UploadDateTime { get; set; } + public string Title { get; set; } + public string RequirementsNotes { get; set; } + public string Comments { get; set; } + public int? CANo { get; set; } + public int? D5D6CAID { get; set; } + public int? D7PAID { get; set; } + public int? CAFindingsID { get; set; } + +} + +public class D3ContainmentAction { + + public int ID { get; set; } + public int CANo { get; set; } + public string Section { get; set; } + public string ContainmentAction { get; set; } + public string Result { get; set; } + public string ECNLinks { get; set; } + public int ResponsibilityOwnerID { get; set; } + public int CurrentResponsibilityOwnerID { get; set; } + public string ResponsibilityOwnerName { get; set; } + public DateTime? ECD { get; set; } + public DateTime? ImplementedDate { get; set; } + public DateTime AssignedDate { get; set; } + +} + +public class RiskAssessmentArea { + + public int RiskAssessmentAreaID { get; set; } + public string RiskAssessmentAreaName { get; set; } + +} + +public class D5D6CorrectivetAction { + + public int ID { get; set; } + public int CANo { get; set; } + public string CorrectiveAction { get; set; } + public string CARequired { get; set; } + public string Result { get; set; } + public string ECNLinks { get; set; } + public string AttachmentLinks { get; set; } + public int ResponsibilityOwnerID { get; set; } + public int CurrentResponsibilityOwnerID { get; set; } + public string ResponsibilityOwnerName { get; set; } + public DateTime? ECD { get; set; } + public DateTime? ImplementedDate { get; set; } + public bool IsImplemented { get; set; } + public string ImprovementID { get; set; } + public string Improvement { get; set; } + public CA_Attachment CA_Attachment { get; set; } + public DateTime AssignedDate { get; set; } + public bool Approved { get; set; } + public D5D6CorrectivetAction() => + CA_Attachment = new CA_Attachment(); + public string ActionType { get; set; } + +} + +public class D5D6Improvement { + + public int D5D6ImprovementID { get; set; } + public string D5D6ImprovementName { get; set; } + +} + +public class D7PreventiveAction { + + public int ID { get; set; } + public int CANo { get; set; } + public string PreventiveAction { get; set; } + public string Result { get; set; } + public string ECNLinks { get; set; } + public string AttachmentLinks { get; set; } + public int ResponsibilityOwnerID { get; set; } + public int CurrentResponsibilityOwnerID { get; set; } + public string ResponsibilityOwnerName { get; set; } + public DateTime? ECD { get; set; } + public DateTime? ImplementedDate { get; set; } + public CA_Attachment CA_Attachment { get; set; } + public DateTime AssignedDate { get; set; } + public D7PreventiveAction() => + CA_Attachment = new CA_Attachment(); + +} + +public class CAFindings { + + public int ID { get; set; } + public int AuditNo { get; set; } + public string CAFinding { get; set; } + public string CorrectiveAction { get; set; } + public string Result { get; set; } + public string AttachmentLinks { get; set; } + public int? CurrentResponsibilityOwnerID { get; set; } + public int? ResponsibilityOwnerID { get; set; } + public string ResponsibilityOwnerName { get; set; } + public DateTime? ECD { get; set; } + public DateTime? ImplementedDate { get; set; } + public AuditReportAttachment Audit_Attachment { get; set; } + public DateTime AssignedDate { get; set; } + public CAFindings() => + Audit_Attachment = new AuditReportAttachment(); + +} + +public class CASectionApproval { + + public string DSection { get; set; } + public string Fullname { get; set; } + public string ApprovalStatus { get; set; } + public DateTime? DateAssigned { get; set; } + public DateTime? DateCompleted { get; set; } + public string Comments { get; set; } + +} + +public class CANoList { + + public int CANo { get; set; } + public string CANoDisp { get; set; } + +} + +public class CAD3D5D7Due { + + public int CANo { get; set; } + public DateTime DueDate { get; set; } + public string ItemDue { get; set; } + public string ExpiryType { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/FabApproval.Context.cs b/Fab2ApprovalSystem/Models/FabApproval.Context.cs index d662c03..57ecb9d 100644 --- a/Fab2ApprovalSystem/Models/FabApproval.Context.cs +++ b/Fab2ApprovalSystem/Models/FabApproval.Context.cs @@ -1,3 +1,5 @@ +#if !NET8 + //------------------------------------------------------------------------------ // // This code was generated from a template. @@ -36,3 +38,5 @@ namespace Fab2ApprovalSystem.Models public virtual DbSet C_8DAuditedStandardByAudit { get; set; } } } + +#endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/IdentityModels.cs b/Fab2ApprovalSystem/Models/IdentityModels.cs index 836cc81..628b5f5 100644 --- a/Fab2ApprovalSystem/Models/IdentityModels.cs +++ b/Fab2ApprovalSystem/Models/IdentityModels.cs @@ -1,17 +1,17 @@ -using Microsoft.AspNet.Identity.EntityFramework; +#if !NET8 -namespace Fab2ApprovalSystem.Models -{ +using Microsoft.AspNet.Identity.EntityFramework; + +namespace Fab2ApprovalSystem.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. - public class ApplicationUser : IdentityUser - { + public class ApplicationUser : IdentityUser { } - public class ApplicationDbContext : IdentityDbContext - { + public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext() - : base("DefaultConnection") - { + : base("DefaultConnection") { } } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/LoginResult.cs b/Fab2ApprovalSystem/Models/LoginResult.cs index 1b0f2f0..97b103b 100644 --- a/Fab2ApprovalSystem/Models/LoginResult.cs +++ b/Fab2ApprovalSystem/Models/LoginResult.cs @@ -1,6 +1,8 @@ -namespace Fab2ApprovalSystem.Models { - public class LoginResult { - public bool IsAuthenticated { get; set; } - public AuthTokens AuthTokens { get; set; } - } -} +namespace Fab2ApprovalSystem.Models; + +public class LoginResult { + + public bool IsAuthenticated { get; set; } + public AuthTokens AuthTokens { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/LotDispositionModels.cs b/Fab2ApprovalSystem/Models/LotDispositionModels.cs index 0bc6aa6..fde5abd 100644 --- a/Fab2ApprovalSystem/Models/LotDispositionModels.cs +++ b/Fab2ApprovalSystem/Models/LotDispositionModels.cs @@ -1,281 +1,202 @@ -using Fab2ApprovalSystem.ViewModels; -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; + +#if !NET8 using System.Web.Mvc; using System.Web.Script.Serialization; +#endif -namespace Fab2ApprovalSystem.Models -{ +namespace Fab2ApprovalSystem.Models; - - [Serializable] - public class LotDisposition - { - //[Editable(false)] - [Display(Name = "Issue Number")] - public int IssueID { get; set; } - //[Editable(false)] - public string Title { get; set; } - public bool PERequired { get; set; } - public string IssueDescription { get; set; } - [ReadOnly(true)] - public DateTime? IssueDate { get; set; } - public DateTime? SubmitedDate { get; set; } - public DateTime? CloseDate { get; set; } - public int OriginatorID { get; set; } - public string OriginatorName { get; set; } - public string ReasonForDisposition { get; set; } - public int ResponsibilityID { get; set; } - public int ResponsibilityIssueID { get; set; } - public string SPNScrapCode { get; set; } - public byte CurrentStep { get; set; } - // Extra field Defined for Scraping wafer for a given lot - public Lot Lot { get; set; } - //Extra field defined for Attachments - public Attachment DocumentAttachment { get; set; } - - // important!!make sure the id of the control matches the name of the field in the model it is being binded to, - // in order to get the selected items from the control - public List DepartmentIDs { get; set; } - - public List Attachments { get; set; } - public List Approvals { get; set; } - public List ScrapLots { get; set; } - - public int CANo { get; set; } - [Display(Name = "MRB Required")] - public bool MRBRequired { get; set; } - public int WorkFlowNumber { get; set; } - - [Display(Name = "Dispositon By OCAP")] - public bool DispositionByOCAP { get; set; } - - public bool RecordLockIndicator { get; set; } - public int RecordLockedBy { get; set; } - public string RecordLockByName { get; set; } - public DateTime? RecordLockedDate { get; set; } - public int LastUpdatedBy { get; set; } - public DateTime? LastUpdateDate { get; set; } - - - - - public LotDisposition() - { - DepartmentIDs = new List(); - Lot = new Lot(); - DocumentAttachment = new Attachment(); - //Lots = new List(); - Attachments = new List(); - Approvals = new List(); - ScrapLots = new List(); - IssueDate = DateTime.Now; - CurrentStep = 0; - } +[Serializable] +public class LotDisposition { + //[Editable(false)] + [Display(Name = "Issue Number")] + public int IssueID { get; set; } + //[Editable(false)] + public string Title { get; set; } + public bool PERequired { get; set; } + public string IssueDescription { get; set; } + [ReadOnly(true)] + public DateTime? IssueDate { get; set; } + public DateTime? SubmitedDate { get; set; } + public DateTime? CloseDate { get; set; } + public int OriginatorID { get; set; } + public string OriginatorName { get; set; } + public string ReasonForDisposition { get; set; } + public int ResponsibilityID { get; set; } + public int ResponsibilityIssueID { get; set; } + public string SPNScrapCode { get; set; } + public byte CurrentStep { get; set; } + // Extra field Defined for Scraping wafer for a given lot + public Lot Lot { get; set; } + //Extra field defined for Attachments + public Attachment DocumentAttachment { get; set; } + // important!!make sure the id of the control matches the name of the field in the model it is being binded to, + // in order to get the selected items from the control + public List DepartmentIDs { get; set; } + public List Attachments { get; set; } + public List Approvals { get; set; } + public List ScrapLots { get; set; } + public int CANo { get; set; } + [Display(Name = "MRB Required")] + public bool MRBRequired { get; set; } + public int WorkFlowNumber { get; set; } + [Display(Name = "Dispositon By OCAP")] + public bool DispositionByOCAP { get; set; } + public bool RecordLockIndicator { get; set; } + public int RecordLockedBy { get; set; } + public string RecordLockByName { get; set; } + public DateTime? RecordLockedDate { get; set; } + public int LastUpdatedBy { get; set; } + public DateTime? LastUpdateDate { get; set; } + public LotDisposition() { + DepartmentIDs = new List(); + Lot = new Lot(); + DocumentAttachment = new Attachment(); + //Lots = new List(); + Attachments = new List(); + Approvals = new List(); + ScrapLots = new List(); + IssueDate = DateTime.Now; + CurrentStep = 0; } - //public class Lot - //{ - // public int LotID { get; set; } - // [Display(Name = "Wafer Lot#")] - // public string LotNumber { get; set; } - // public string ParentLotNumber { get { return LotNumber.Length >= 7 ? LotNumber.Substring(0, 7) : LotNumber; } } +} - // public int MRBNumber { get; set; } - // public int IssueID { get; set; } - // public string DieLotNumber { get; set; } - // public string Description { get; set; } - // [Display(Name="New PN#")] - // public string NewPartNo { get; set; } - // [Display(Name = "WIP PN#")] - // public string WipPartNo { get; set; } - // [Display(Name = "Die PN#")] - // public string DiePartNo { get; set; } - // [Display(Name="Family")] - // public string ProductFamily { get; set; } - // public double Gen { get; set; } - // public string Channel { get; set; } - // public double Hexsize { get; set; } - // public double Voltage { get; set; } - // public int WaferCount { get; set; } - // public int ReleaseCount { get; set; } - // public int ScrapCount { get; set; } - // public int DieCount { get; set; } - // public string Location { get; set; } - // public double TotalCost { get; set; } - // public int LotStatusOptionID { get; set; } - // public string LotStatusOptionName { get; set; } - // public double WaferCost { get; set; } - // public double DieCost { get; set; } +public class LotDispoDepartment { - // [UIHint("LotStatusOptionTemplate")] - // [Display(Name="Lot Status")] - // public LotStatusOptionViewModel LotStatusOption { get; set; } + public int DepartmentID { get; set; } + public string DepartmentName { get; set; } - // public ScrapLot ScrapLotWafer { get; set; } - +} - // public Lot() - // { - // LotStatusOption = new LotStatusOptionViewModel(); - // ScrapLotWafer = new ScrapLot(); - // } +public class Attachment { - //} + public int AttachmentID { set; get; } + public int IssueID { get; set; } + public string FileName { get; set; } + public int UserID { get; set; } + // extrafield + public string FullName { get; set; } + public string UploadDate { get; set; } + public string Path { get; set; } - public class LotDispoDepartment - { - //public int LotDispoDepartmentID { get; set; } - //public int IssueID { get; set; } - public int DepartmentID { get; set; } - public string DepartmentName { get; set; } - } +} - public class Attachment - { - public int AttachmentID { set; get; } - public int IssueID { get; set; } - public string FileName { get; set; } - public int UserID { get; set; } - // extrafield - public string FullName { get; set; } - public string UploadDate { get; set; } - public string Path { get; set; } +public class Approval { - } + public int ApprovalID { get; set; } + public int IssueID { get; set; } + private string StateName { get; set; } + public int UserID { get; set; } + public int SubRoleID { get; set; } + public int ItemStatus { get; set; } + public int Step { get; set; } + public DateTime? NotifyDate { get; set; } + public DateTime? AssignedDate { get; set; } + public DateTime? RoleAssignedDate { get; set; } + public DateTime? CompleteDateTime { get; set; } + public string UserComments { get; set; } +} - public class Approval - { - public int ApprovalID { get; set; } - public int IssueID { get; set; } - string StateName { get; set; } - public int UserID { get; set; } - public int SubRoleID { get; set; } - public int ItemStatus { get; set; } - public int Step { get; set; } - public DateTime? NotifyDate { get; set; } - public DateTime? AssignedDate { get; set; } - public DateTime? RoleAssignedDate { get; set; } - public DateTime? CompleteDateTime { get; set; } - public string UserComments { get; set; } - } +public class ScrapLot { + public string LotNo { get; set; } + public int IssueID { get; set; } + public int ScrapCount { get; set; } + public int ReleaseCount { get; set; } + public int SplitOfHoldCount { get; set; } + public int CloseToQDBCount { get; set; } - public class ScrapLot - { + // extra field ( a viewmodel can be created) + public int WaferCount { get; set; } + public byte Lot1State { get; set; } + public byte Lot2State { get; set; } + public byte Lot3State { get; set; } + public byte Lot4State { get; set; } + public byte Lot5State { get; set; } + public byte Lot6State { get; set; } + public byte Lot7State { get; set; } + public byte Lot8State { get; set; } + public byte Lot9State { get; set; } + public byte Lot10State { get; set; } + public byte Lot11State { get; set; } + public byte Lot12State { get; set; } + public byte Lot13State { get; set; } + public byte Lot14State { get; set; } + public byte Lot15State { get; set; } + public byte Lot16State { get; set; } + public byte Lot17State { get; set; } + public byte Lot18State { get; set; } + public byte Lot19State { get; set; } + public byte Lot20State { get; set; } + public byte Lot21State { get; set; } + public byte Lot22State { get; set; } + public byte Lot23State { get; set; } + public byte Lot24State { get; set; } + public byte Lot25State { get; set; } + public byte Lot26State { get; set; } + public byte Lot27State { get; set; } + public byte Lot28State { get; set; } + public byte Lot29State { get; set; } + public byte Lot30State { get; set; } + public byte Lot31State { get; set; } + public byte Lot32State { get; set; } + public byte Lot33State { get; set; } + public byte Lot34State { get; set; } + public byte Lot35State { get; set; } + public byte Lot36State { get; set; } + public byte Lot37State { get; set; } + public byte Lot38State { get; set; } + public byte Lot39State { get; set; } + public byte Lot40State { get; set; } + public byte Lot41State { get; set; } + public byte Lot42State { get; set; } + public byte Lot43State { get; set; } + public byte Lot44State { get; set; } + public byte Lot45State { get; set; } + public byte Lot46State { get; set; } + public byte Lot47State { get; set; } + public byte Lot48State { get; set; } + public byte Lot49State { get; set; } + public byte Lot50State { get; set; } - - public string LotNo { get; set; } - public int IssueID { get; set; } - public int ScrapCount { get; set; } - public int ReleaseCount { get; set; } - public int SplitOfHoldCount { get; set; } - public int CloseToQDBCount { get; set; } +} - // extra field ( a viewmodel can be created) - public int WaferCount { get; set; } +public class Users { - public byte Lot1State { get; set; } - public byte Lot2State { get; set; } - public byte Lot3State { get; set; } - public byte Lot4State { get; set; } - public byte Lot5State { get; set; } - public byte Lot6State { get; set; } - public byte Lot7State { get; set; } - public byte Lot8State { get; set; } - public byte Lot9State { get; set; } - public byte Lot10State { get; set; } - public byte Lot11State { get; set; } - public byte Lot12State { get; set; } - public byte Lot13State { get; set; } - public byte Lot14State { get; set; } - public byte Lot15State { get; set; } - public byte Lot16State { get; set; } - public byte Lot17State { get; set; } - public byte Lot18State { get; set; } - public byte Lot19State { get; set; } - public byte Lot20State { get; set; } - public byte Lot21State { get; set; } - public byte Lot22State { get; set; } - public byte Lot23State { get; set; } - public byte Lot24State { get; set; } - public byte Lot25State { get; set; } - public byte Lot26State { get; set; } - public byte Lot27State { get; set; } - public byte Lot28State { get; set; } - public byte Lot29State { get; set; } - public byte Lot30State { get; set; } - public byte Lot31State { get; set; } - public byte Lot32State { get; set; } - public byte Lot33State { get; set; } - public byte Lot34State { get; set; } - public byte Lot35State { get; set; } - public byte Lot36State { get; set; } - public byte Lot37State { get; set; } - public byte Lot38State { get; set; } - public byte Lot39State { get; set; } - public byte Lot40State { get; set; } - public byte Lot41State { get; set; } - public byte Lot42State { get; set; } - public byte Lot43State { get; set; } - public byte Lot44State { get; set; } - public byte Lot45State { get; set; } - public byte Lot46State { get; set; } - public byte Lot47State { get; set; } - public byte Lot48State { get; set; } - public byte Lot49State { get; set; } - public byte Lot50State { get; set; } - - } + public int OriginatorID { get; set; } + public string Originatorname { get; set; } - /// - /// - /// - public class Users - { - public int OriginatorID { get; set; } - public string Originatorname { get;set;} - - } +} - /// - /// - /// - public class Responsibility - { - public int ResponsibilityID { get; set; } - public string ResponsibilityName { get; set; } - } +public class Responsibility { + public int ResponsibilityID { get; set; } + public string ResponsibilityName { get; set; } - /// - /// - /// - public class ResponsibilityIssue - { - public int ResponsibilityIssueID { get; set; } - public string Issue { get; set; } - } +} - /// - /// - /// - public class Comments - { - public int ID { get; set; } - public int IssueID {get; set;} - public string CommentedBy { get; set; } - public string UserName{ get; set; } - public string UserComments { get; set; } - public DateTime TimeStamp { get; set; } +public class ResponsibilityIssue { - } + public int ResponsibilityIssueID { get; set; } + public string Issue { get; set; } + +} + +public class Comments { + + public int ID { get; set; } + public int IssueID { get; set; } + public string CommentedBy { get; set; } + public string UserName { get; set; } + public string UserComments { get; set; } + public DateTime TimeStamp { get; set; } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/LotTravellerModel.cs b/Fab2ApprovalSystem/Models/LotTravellerModel.cs index ba74ba6..7750d9b 100644 --- a/Fab2ApprovalSystem/Models/LotTravellerModel.cs +++ b/Fab2ApprovalSystem/Models/LotTravellerModel.cs @@ -1,463 +1,381 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.Models -{ - /// - /// - /// - [Serializable] - public class LTWorkRequest - { +namespace Fab2ApprovalSystem.Models; - public int ID{ get; set; } - public int SWRNumber{ get; set; } - public bool RecordLockIndicator{ get; set; } - public int RecordLockedBy { get; set; } - public string RecordLockByName { get; set; } - public byte CurrentStep { get; set; } - public int Revision{ get; set; } - public bool IsCurrentRevision { get; set; } - public int OriginatorID{ get; set; } - public DateTime? OriginatedDate { get; set; } - public DateTime? SubmitedDate { get; set; } - public DateTime? CloseDate { get; set; } - public int Status{ get; set; } - public bool IsITAR{ get; set; } - public string Title{ get; set; } - public char? LotType{ get; set; } - public string PCRBNumber{ get; set; } - public int? EngLotStartRequired{ get; set; } - public int? LotTypeConversion{ get; set; } - public int? QualLot{ get; set; } - public string PurposeOfRequest{ get; set; } - public DateTime? PlannedLotStartDate{ get; set; } - public DateTime? PlannedScheduledCloseDate{ get; set; } - public string ChargeDepartment{ get; set; } - public string AllocationToUse{ get; set; } - public int? PredictedCyleTime{ get; set; } - public string ChargesForRawWafers{ get; set; } - public string DeptChargedForRawWafers{ get; set; } - public string DeptOwnerForRawWafers{ get; set; } - public string FabCost{ get; set; } - public string DeptChargedForFabCost{ get; set; } - public string SignOn{ get; set; } - public string Verb1{ get; set; } - public DateTime? EstimatedBinCLoseDate { get; set; } - public int? TotalQty { get; set; } - public int? StartQty{ get; set; } - public string Verb2{ get; set; } - public string WIPArea{ get; set; } - public DateTime? LotStartDate{ get; set; } - public string LotNumber { get; set; } - public string WIPPartNumber{ get; set; } - public string PartDescription { get; set; } - public string DefaultEPISiliconPartNumber { get; set; } - public string ProcessFlow{ get; set; } - public string EmployeeID{ get; set; } - public string VerbComment{ get; set; } - public int? RecordSiliconLotInSPNTapeTagTotrav { get;set;} - public string SiliconLotNoCassette1 { get; set; } +/// +/// +/// +[Serializable] +public class LTWorkRequest { - public bool SiliconOnHand { get; set; } - public DateTime? SiliconExpectedDueDate { get; set; } - public string SiliconComments { get; set; } + public int ID { get; set; } + public int SWRNumber { get; set; } + public bool RecordLockIndicator { get; set; } + public int RecordLockedBy { get; set; } + public string RecordLockByName { get; set; } + public byte CurrentStep { get; set; } + public int Revision { get; set; } + public bool IsCurrentRevision { get; set; } + public int OriginatorID { get; set; } + public DateTime? OriginatedDate { get; set; } + public DateTime? SubmitedDate { get; set; } + public DateTime? CloseDate { get; set; } + public int Status { get; set; } + public bool IsITAR { get; set; } + public string Title { get; set; } + public char? LotType { get; set; } + public string PCRBNumber { get; set; } + public int? EngLotStartRequired { get; set; } + public int? LotTypeConversion { get; set; } + public int? QualLot { get; set; } + public string PurposeOfRequest { get; set; } + public DateTime? PlannedLotStartDate { get; set; } + public DateTime? PlannedScheduledCloseDate { get; set; } + public string ChargeDepartment { get; set; } + public string AllocationToUse { get; set; } + public int? PredictedCyleTime { get; set; } + public string ChargesForRawWafers { get; set; } + public string DeptChargedForRawWafers { get; set; } + public string DeptOwnerForRawWafers { get; set; } + public string FabCost { get; set; } + public string DeptChargedForFabCost { get; set; } + public string SignOn { get; set; } + public string Verb1 { get; set; } + public DateTime? EstimatedBinCLoseDate { get; set; } + public int? TotalQty { get; set; } + public int? StartQty { get; set; } + public string Verb2 { get; set; } + public string WIPArea { get; set; } + public DateTime? LotStartDate { get; set; } + public string LotNumber { get; set; } + public string WIPPartNumber { get; set; } + public string PartDescription { get; set; } + public string DefaultEPISiliconPartNumber { get; set; } + public string ProcessFlow { get; set; } + public string EmployeeID { get; set; } + public string VerbComment { get; set; } + public int? RecordSiliconLotInSPNTapeTagTotrav { get; set; } + public string SiliconLotNoCassette1 { get; set; } + public bool SiliconOnHand { get; set; } + public DateTime? SiliconExpectedDueDate { get; set; } + public string SiliconComments { get; set; } + public bool ReticleOnHand { get; set; } + public DateTime? ReticleExpectedDueDate { get; set; } + public string ReticleComments { get; set; } + public bool SPNTransferOnHand { get; set; } + public DateTime? SPNTransferExpectedDueDate { get; set; } + public string SPNTransferComments { get; set; } + public bool ProbeCardOnHand { get; set; } + public DateTime? ProbeCardExpectedDueDate { get; set; } + public string ProbeCardComments { get; set; } + public bool ProbeRecipeOnHand { get; set; } + public DateTime? ProbeRecipeExpectedDueDate { get; set; } + public string ProbeRecipeComments { get; set; } + public bool ProcessChangeDetailsOnHand { get; set; } + public DateTime? ProcessChangeDetailsDueDate { get; set; } + public string LotStartCheckListComments { get; set; } + public LTHoldStep LTHoldStep { get; set; } + public LTWorkRequestAttachment WorkRequestAttachment { get; set; } + public int LotCount { get; set; } - public bool ReticleOnHand { get; set; } - public DateTime? ReticleExpectedDueDate { get; set; } - public string ReticleComments { get; set; } - - public bool SPNTransferOnHand { get; set; } - public DateTime? SPNTransferExpectedDueDate { get; set; } - public string SPNTransferComments { get; set; } - - public bool ProbeCardOnHand { get; set; } - public DateTime? ProbeCardExpectedDueDate { get; set; } - public string ProbeCardComments { get; set; } - - public bool ProbeRecipeOnHand { get; set; } - public DateTime? ProbeRecipeExpectedDueDate { get; set; } - public string ProbeRecipeComments { get; set; } - - public bool ProcessChangeDetailsOnHand { get; set; } - public DateTime? ProcessChangeDetailsDueDate { get; set; } - - public string LotStartCheckListComments { get; set; } - - public LTHoldStep LTHoldStep { get; set; } - public LTWorkRequestAttachment WorkRequestAttachment { get; set; } - public int LotCount { get; set; } - - // View Model attributes - public List DepartmentIDs { get; set; } - public List ModuleIDs { get; set; } - public string OriginatorName { get; set; } - public string RevisionComments { get; set; } - public LTMaterial LTMaterial { get; set; } - public int PreviousWorkRequestID { get; set; } - public int WorkFlowNumber { get; set; } - public string ApprovalStatus - { - get - { - return Status == 1? "Approved" : "Pending"; - } - - } - - public LTWorkRequest() - { - DepartmentIDs = new List(); - ModuleIDs = new List(); - LTHoldStep = new LTHoldStep(); - LTMaterial = new LTMaterial(); + // View Model attributes + public List DepartmentIDs { get; set; } + public List ModuleIDs { get; set; } + public string OriginatorName { get; set; } + public string RevisionComments { get; set; } + public LTMaterial LTMaterial { get; set; } + public int PreviousWorkRequestID { get; set; } + public int WorkFlowNumber { get; set; } + public string ApprovalStatus { + get { + return Status == 1 ? "Approved" : "Pending"; } } - - public class LTMaterial - { - public int ID { get; set; } - [Display(Name = "WIP Part #")] - public string WIPPartNumber { get; set; } - [Display(Name = "EPI Silicon Part#")] - public string EPISiliconPartNumber { get; set; } - public int Quantity { get; set; } - public string Supplier { get; set; } - public string Source { get; set; } - public int LTWorkRequestID { get; set; } - public int PreviousMaterialID { get; set; } - + public LTWorkRequest() { + DepartmentIDs = new List(); + ModuleIDs = new List(); + LTHoldStep = new LTHoldStep(); + LTMaterial = new LTMaterial(); } - /// - /// - /// - public class LTAffectedDepartment - { - public int ID { get; set; } - public int DepartmentID { get; set; } - public int LTWorkRequestID { get; set; } +} - } +public class LTMaterial { - /// - /// - /// - public class LTAffectedModule - { - public int ID { get; set; } - public int ModuleID { get; set; } - public int LTWorkRequestID { get; set; } - } + public int ID { get; set; } + [Display(Name = "WIP Part #")] + public string WIPPartNumber { get; set; } + [Display(Name = "EPI Silicon Part#")] + public string EPISiliconPartNumber { get; set; } + public int Quantity { get; set; } + public string Supplier { get; set; } + public string Source { get; set; } + public int LTWorkRequestID { get; set; } + public int PreviousMaterialID { get; set; } - /// - /// - /// - //public class LTMaterial - //{ - // public int ID { get; set; } - // public string WIPPartNumber { get; set; } - // public string Description { get; set; } - // public string EPISiliconPartNumber { get; set; } - // public int Quantity { get; set; } - // public string Supplier { get; set; } - // public int LTWorkRequestID { get; set; } +} - // public LTMaterial() - // { - // Description = ""; - // } +public class LTAffectedDepartment { - //} + public int ID { get; set; } + public int DepartmentID { get; set; } + public int LTWorkRequestID { get; set; } - /// - /// - /// - public class LTLotStartCheckList - { - public int ID { get; set; } - public string Item { get; set; } - public bool OnHand { get; set; } - public DateTime? ExpectedDueDate { get; set; } - public int LTWorkRequestID { get; set; } - public string Comments { get; set; } - } +} - /// - /// - /// - public class LTHoldStep - { - public int ID { get; set; } - public string BaseFlow { get; set; } - public string Location { get; set; } +public class LTAffectedModule { - [Display(Name="Seq")] - public string OperSequence { get; set; } - - public string Operation { get; set; } - public string OperationDescription { get; set; } - public string ChangeInstructions { get; set; } - public string FileNames { get; set; } - public int LTWorkRequestID { get; set; } - public int UpdatedBy { get; set; } - public LTWorkRequestAttachment LTWorkRequestAttachment { get; set; } - public int Revision { get; set; } - public int SWRNumber { get; set; } - public int currentStep { get; set; } - public int PreviousHoldStepID { get; set; } - public LTHoldStep() - { - LTWorkRequestAttachment = new LTWorkRequestAttachment(); + public int ID { get; set; } + public int ModuleID { get; set; } + public int LTWorkRequestID { get; set; } + +} + +public class LTLotStartCheckList { + + public int ID { get; set; } + public string Item { get; set; } + public bool OnHand { get; set; } + public DateTime? ExpectedDueDate { get; set; } + public int LTWorkRequestID { get; set; } + public string Comments { get; set; } + +} + +public class LTHoldStep { + + public int ID { get; set; } + public string BaseFlow { get; set; } + public string Location { get; set; } + + [Display(Name = "Seq")] + public string OperSequence { get; set; } + public string Operation { get; set; } + public string OperationDescription { get; set; } + public string ChangeInstructions { get; set; } + public string FileNames { get; set; } + public int LTWorkRequestID { get; set; } + public int UpdatedBy { get; set; } + public LTWorkRequestAttachment LTWorkRequestAttachment { get; set; } + public int Revision { get; set; } + public int SWRNumber { get; set; } + public int currentStep { get; set; } + public int PreviousHoldStepID { get; set; } + public LTHoldStep() => + LTWorkRequestAttachment = new LTWorkRequestAttachment(); + +} + +public class LTWorkRequestAttachment { + + public int ID { get; set; } + public string FileGUID { get; set; } + public string FileName { get; set; } + public string DocType { get; set; } + public string Comments { get; set; } + public DateTime? UploadDateTime { get; set; } + public int LTHoldStepID { get; set; } + public string UploadedByName { get; set; } + public int UploadedByID { get; set; } + public int Revision { get; set; } + public int WorkRequestID { get; set; } + public int SWRNumber { get; set; } + public string FileExtension { get; set; } + public int PreviousWorkRequestAttachmentID { get; set; } + +} + +public class LTLotTravelerHeaderViewModel { + + public int ID { get; set; } + public int SWRNumber { get; set; } + public string LotNumber { get; set; } + public string Title { get; set; } // + public string Status { get; set; } // + public string Originator { get; set; } // + public string WIPPartNumber { get; set; } + public string PartDescription { get; set; } + public string BaseFlow { set; get; } + public bool IsITAR { set; get; } + public DateTime? LastUpdate { get; set; } + public string LastUpdatedBy { get; set; } + public string PurposeOfRequest { get; set; } + public int LotTravCurrentRevision { get; set; } + public LTLotTravelerHoldSteps LTLotTravelerHoldStep { get; set; } + public bool IsCurrentRevision { get; set; } + public int LTWorkRequestID { get; set; } + public int LotTravRevID { get; set; } + public bool RecordLockIndicator { get; set; } + public int RecordLockedBy { get; set; } + public int RecordLockedByName { get; set; } + public List Revisions { get; set; } + public bool TravelerClosed { get; set; } + public DateTime? TravelerClosedDate { get; set; } + public string TravelerClosedBy { get; set; } + public string TravelerClosedReason { get; set; } + public int WorkReqRevision { get; set; } + public string TravelerStatus { + get { + return TravelerClosedDate == null ? "Open" : "Closed"; } } - /// - /// - /// - public class LTWorkRequestAttachment - { - public int ID { get; set; } - public string FileGUID { get; set; } - public string FileName { get; set; } - public string DocType { get; set; } - public string Comments { get; set; } - public DateTime? UploadDateTime { get; set; } - public int LTHoldStepID { get; set; } - public string UploadedByName { get; set; } - public int UploadedByID { get; set; } - public int Revision { get; set; } - public int WorkRequestID { get; set; } - public int SWRNumber { get; set; } - public string FileExtension { get; set; } - public int PreviousWorkRequestAttachmentID { get; set; } - } + public LTLotTravelerHeaderViewModel() => + LTLotTravelerHoldStep = new LTLotTravelerHoldSteps(); - /// - /// - /// - public class LTLotTravelerHeaderViewModel - { - public int ID { get; set; } - public int SWRNumber { get; set; } - public string LotNumber { get; set; } - public string Title { get; set; } // - public string Status { get; set; } // - public string Originator { get; set; } // - public string WIPPartNumber { get; set; } - public string PartDescription { get; set; } - public string BaseFlow { set; get; } - public bool IsITAR { set; get; } - public DateTime? LastUpdate { get; set; } - public string LastUpdatedBy { get; set; } - public string PurposeOfRequest { get; set; } - //public int Quantity { get; set; } - //public bool TravelerAttachedToLot { get; set; } - public int LotTravCurrentRevision { get; set; } - public LTLotTravelerHoldSteps LTLotTravelerHoldStep { get; set; } - public bool IsCurrentRevision { get; set; } - //public string Comments { get; set; } - public int LTWorkRequestID { get; set; } - public int LotTravRevID { get; set; } - public bool RecordLockIndicator { get; set; } - public int RecordLockedBy { get; set; } - public int RecordLockedByName { get; set; } - public List Revisions { get; set; } - public bool TravelerClosed { get; set; } - public DateTime? TravelerClosedDate { get; set; } - public string TravelerClosedBy { get; set; } - public string TravelerClosedReason { get; set; } - public int WorkReqRevision { get; set; } +} - public string TravelerStatus - { - get - { - return TravelerClosedDate == null ? "Open" : "Closed"; - } - } +public class LTLot { - - public LTLotTravelerHeaderViewModel() - { - LTLotTravelerHoldStep = new LTLotTravelerHoldSteps(); + public int ID { get; set; } + public int WorkRequestID { get; set; } + public string LotNumber { get; set; } + public string WIPPartNumber { get; set; } + public int WaferQty { get; set; } + public string PartDescription { get; set; } + public string Process { get; set; } + public string Location { get; set; } + public string Operation { get; set; } + public string LotStatus { get; set; } + public bool IsTravelerGenerated { get; set; } + [Display(Name = "Revision")] + public int LotTravelerCurrentRevision { get; set; } + public int LotUploadedBy { get; set; } + public string UploadedByName { get; set; } + public DateTime LotUploadDatetime { get; set; } + public int WRWithExistingLot { get; set; } + public string TravelerStatus { get; set; } + public bool TravelerClosed { get; set; } + public DateTime? TravelerClosedDate { get; set; } + + [Display(Name = "")] + public string ButtonAttrib { + get { + return (IsTravelerGenerated ? "True" : "False") + "~" + ID + "~" + WorkRequestID + "~" + LotStatus + "~" + TravelerStatus; } } - /// - /// - /// - public class LTLot - { - public int ID { get; set; } - public int WorkRequestID { get; set; } - public string LotNumber { get; set; } - public string WIPPartNumber { get; set; } - public int WaferQty { get; set; } - public string PartDescription { get; set; } - public string Process { get; set; } - public string Location { get; set; } - public string Operation { get; set; } - public string LotStatus { get; set; } - public bool IsTravelerGenerated { get; set; } - [Display(Name="Revision")] - public int LotTravelerCurrentRevision { get; set; } - public int LotUploadedBy { get; set; } - public string UploadedByName { get; set; } - public DateTime LotUploadDatetime { get; set; } - public int WRWithExistingLot { get; set; } - public string TravelerStatus { get; set; } - public bool TravelerClosed { get; set; } - public DateTime? TravelerClosedDate { get; set; } - //public int RecordLockIndicator { get; set; } - //public int RecordLockedBy { get; set; } - //public DateTime? RecordLockedDateTime { get; set; } - //public bool IsCurrentRevision { get; set;} - //public int Revision { get; set; } - [Display(Name = "")] - public string ButtonAttrib - { - get - { - return (IsTravelerGenerated ? "True" : "False") + "~" + ID + "~" + WorkRequestID + "~" + LotStatus + "~" + TravelerStatus; - } - } +} - } +public class LTLotTravelerRevisionAttrib { - /// - /// - /// - public class LTLotTravelerRevisionAttrib - { - public int ID { get; set; } - public int LTLotID { get; set; } - public int RevisionNumber { get; set; } - public bool IsCurrentRevision { get; set; } - public string Comments { get; set; } - public int RecordLockIndicator { get; set; } - public int RecordLockedBy { get; set; } - public DateTime? RecordLockedDate { get; set; } - public int TravelerLastUpdatedBy { get; set; } - public DateTime? TraverlerLastUpdatedDatetime { get; set; } - + public int ID { get; set; } + public int LTLotID { get; set; } + public int RevisionNumber { get; set; } + public bool IsCurrentRevision { get; set; } + public string Comments { get; set; } + public int RecordLockIndicator { get; set; } + public int RecordLockedBy { get; set; } + public DateTime? RecordLockedDate { get; set; } + public int TravelerLastUpdatedBy { get; set; } + public DateTime? TraverlerLastUpdatedDatetime { get; set; } +} - } +public class LTLotTravlerHistory { - public class LTLotTravlerHistory - { +} - } +public class LTLotTravelerHoldSteps { - /// - /// - /// - public class LTLotTravelerHoldSteps - { - public int ID { get; set; } - public string Location { get; set; } - public string Operation { get; set; } - public string OperSequence { get; set; } - public string Description { get; set; } - public string OperationDescription { get; set; } - public string ChangeInstructions { get; set; } - public bool OLHoldInSPN { get; set; } - public string ExecutionTaskComments { get; set; } - public string EmployeeID { get; set; } - public bool Completed { get; set; } - public DateTime? SignOffTime { get; set; } - public int SignedOffBy { get; set; } - [Display(Name="SignedOff By")] - public string SignedOffByName { get; set; } - public int LotTravelerRevisionID { get; set; } - public string RevisionComments { get; set; } - public DateTime? UpdatedDateTime { get; set; } - public int? UpdatedBy { get; set; } - public int CurrentRevision { get; set; } - // view model fields - public string FileNames { get; set; } - public int SWRNumber { get; set; } - public int LTLotID { get; set; } - public int WorkRequestID { get; set; } - } + public int ID { get; set; } + public string Location { get; set; } + public string Operation { get; set; } + public string OperSequence { get; set; } + public string Description { get; set; } + public string OperationDescription { get; set; } + public string ChangeInstructions { get; set; } + public bool OLHoldInSPN { get; set; } + public string ExecutionTaskComments { get; set; } + public string EmployeeID { get; set; } + public bool Completed { get; set; } + public DateTime? SignOffTime { get; set; } + public int SignedOffBy { get; set; } + [Display(Name = "SignedOff By")] + public string SignedOffByName { get; set; } + public int LotTravelerRevisionID { get; set; } + public string RevisionComments { get; set; } + public DateTime? UpdatedDateTime { get; set; } + public int? UpdatedBy { get; set; } + public int CurrentRevision { get; set; } + // view model fields + public string FileNames { get; set; } + public int SWRNumber { get; set; } + public int LTLotID { get; set; } + public int WorkRequestID { get; set; } - /// - /// - /// - public class LTLotTravAttachment - { - public int ID { get; set; } - public string FileGUID { get; set; } - public string FileName { get; set; } - public string DocType { get; set; } - public string Comments { get; set; } - public int LotTravelerRevisionID { get; set; } - public int LTLotTravHoldStepID { get; set; } - public DateTime? UploadTime { get; set; } - public int UploadedByID { get; set; } - public string UploadedByName { get; set; } - - - } +} +public class LTLotTravAttachment { + public int ID { get; set; } + public string FileGUID { get; set; } + public string FileName { get; set; } + public string DocType { get; set; } + public string Comments { get; set; } + public int LotTravelerRevisionID { get; set; } + public int LTLotTravHoldStepID { get; set; } + public DateTime? UploadTime { get; set; } + public int UploadedByID { get; set; } + public string UploadedByName { get; set; } - - /// - public class BaseFlowLocation - { - public string Location { get; set; } - } +} - public class BaseFlowOperations - { - public string Operation { get; set; } - public string OperationDesc { get; set; } - public string OperCode { get; set; } - public string SeqCode { get; set; } +/// +public class BaseFlowLocation { - } + public string Location { get; set; } +} - /// - public class BaseFlowLocationOperation - { - public string BaseFlow { get; set; } - public string Location { get; set; } - public string Operation { get; set; } - } +public class BaseFlowOperations { - public class PartNumberAttrib - { - public string PartNumber { get; set; } - public string SiliconAndDesc { get; set; } - } + public string Operation { get; set; } + public string OperationDesc { get; set; } + public string OperCode { get; set; } + public string SeqCode { get; set; } - public class Revision - { - public int ID { get; set; } - public int RevisionNumber { get; set; } - } +} +/// +public class BaseFlowLocationOperation { - public class LotWithTraveler - { - public int LotID { get; set; } - public string LotNumber { get; set; } - } + public string BaseFlow { get; set; } + public string Location { get; set; } + public string Operation { get; set; } +} + +public class PartNumberAttrib { + + public string PartNumber { get; set; } + public string SiliconAndDesc { get; set; } + +} + +public class Revision { + + public int ID { get; set; } + public int RevisionNumber { get; set; } + +} + +public class LotWithTraveler { + + public int LotID { get; set; } + public string LotNumber { get; set; } + +} + +public class RevisionHistory { + + public int ID { get; set; } + public string RevisionedBy { get; set; } + public string Comments { get; set; } + public DateTime RevisionCreateDate { get; set; } - public class RevisionHistory - { - public int ID { get; set; } - public string RevisionedBy { get; set; } - public string Comments { get; set; } - public DateTime RevisionCreateDate { get; set; } - } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/MRBModels.cs b/Fab2ApprovalSystem/Models/MRBModels.cs index d9c6eac..42464a7 100644 --- a/Fab2ApprovalSystem/Models/MRBModels.cs +++ b/Fab2ApprovalSystem/Models/MRBModels.cs @@ -1,226 +1,167 @@ -using Fab2ApprovalSystem.ViewModels; -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.Models -{ +using Fab2ApprovalSystem.ViewModels; + +namespace Fab2ApprovalSystem.Models; + +/// +/// +/// +[Serializable] +public class MRB { + + public int MRBNumber { get; set; } + public string Title { get; set; } + public int MRBRaisedAreaID { get; set; } + public int OriginatorID { get; set; } + public int Owner { get; set; } + public int Module { get; set; } + public DateTime? MRBRaisedDate { get; set; } + public string Process { get; set; } + public int ApprovalStatus { get; set; } + public string Tool { get; set; } + public string ToolCSV { get; set; } + public int NumberOfLotsAffected { get; set; } + public int NumberOfWafersAffected { get; set; } + public int NumberOfDiesAffected { get; set; } + public DateTime? ApprovalDate { get; set; } + public int CANo { get; set; } + public string IssueDescription { get; set; } + public DateTime? IssueDetectedDate { get; set; } + public DateTime? IssueStartDate { get; set; } + public DateTime? IssueEndDate { get; set; } + + // viewmodel + public string OwnerName { get; set; } + public List PartGroupIDs { get; set; } + public List ModuleIDs { get; set; } + public List DispositionIDs { get; set; } + public List RiskAssessmentIDs { get; set; } + public string Notes { get; set; } + public string OwnerApprover { get; set; } + public string MfgEngineeringAppover { get; set; } + public string YEApprover { get; set; } + public string PEApprover { get; set; } + public string OtherApprovers { get; set; } + public string QualityApprovers { get; set; } + public byte CurrentStep { get; set; } + public string DetailsFolder { get; set; } + public bool CustomerImpacted { get; set; } + public int WorkFlowNumber { get; set; } + public string ApprovalStatusString { + get { + switch (ApprovalStatus) { + case 0: + return "PENDING"; + case 1: + return "APPROVED"; + default: + return "CLOSED"; + } + } + } + /// /// /// - [Serializable] - public class MRB - { - - public int MRBNumber {get;set;} - public string Title { get; set; } - public int MRBRaisedAreaID { get; set; } - public int OriginatorID { get; set; } - public int Owner { get; set; } - public int Module { get; set; } - public DateTime? MRBRaisedDate { get; set; } - public string Process { get; set; } - public int ApprovalStatus { get; set; } - public string Tool { get; set; } - public string ToolCSV { get; set; } - public int NumberOfLotsAffected { get; set; } - public int NumberOfWafersAffected { get; set; } - public int NumberOfDiesAffected { get; set; } - public DateTime? ApprovalDate { get; set; } - public int CANo { get; set; } - public string IssueDescription { get; set; } - public DateTime? IssueDetectedDate { get; set; } - public DateTime? IssueStartDate { get; set; } - public DateTime? IssueEndDate { get; set; } - - // viewmodel - public string OwnerName { get; set; } - public List PartGroupIDs { get; set; } - public List ModuleIDs { get; set; } - public List DispositionIDs { get; set; } - public List RiskAssessmentIDs { get; set; } - - //public List PartGroups { get; set; } - //public List Modules { get; set; } - //public List Dispositions { get; set; } - //public List RiskAssessments { get; set; } - - public string Notes { get; set; } - public string OwnerApprover { get; set; } - public string MfgEngineeringAppover { get; set; } - public string YEApprover { get; set; } - public string PEApprover { get; set; } - public string OtherApprovers { get; set; } - public string QualityApprovers { get; set; } - //public string Details { get; set; } - public byte CurrentStep { get; set; } - public string DetailsFolder { get; set; } - public bool CustomerImpacted { get; set; } - public int WorkFlowNumber { get; set; } - - public string ApprovalStatusString { - get - { - switch (ApprovalStatus) - { - case 0: - return "PENDING"; - case 1: - return "APPROVED"; - default: - return "CLOSED"; - } - } - } - - /// - /// - /// - public MRB() - { - PartGroupIDs = new List(); - ModuleIDs = new List(); - DispositionIDs = new List(); - RiskAssessmentIDs = new List(); - } - - + public MRB() { + PartGroupIDs = new List(); + ModuleIDs = new List(); + DispositionIDs = new List(); + RiskAssessmentIDs = new List(); } - //public class zMRBLot - //{ - // public int LotID { get; set; } - // [Display(Name = "Wafer Lot#")] - // public string LotNumber { get; set; } - // public string ParentLotNumber { get { return LotNumber.Length >= 7 ? LotNumber.Substring(0, 7) : LotNumber; } } +} - // public int MRBNumber { get; set; } - // public string DieLotNumber { get; set; } - // public string Description { get; set; } - // [Display(Name = "New PN#")] - // public string NewPartNo { get; set; } - // [Display(Name = "WIP PN#")] - // public string WipPartNo { get; set; } - // [Display(Name = "Die PN#")] - // public string DiePartNo { get; set; } - // [Display(Name = "Family")] - // public string ProductFamily { get; set; } - // public double Gen { get; set; } - // public string Channel { get; set; } - // public double Hexsize { get; set; } - // public double Voltage { get; set; } - // public int WaferCount { get; set; } - // public int ReleaseCount { get; set; } - // public int ScrapCount { get; set; } - // public int DieCount { get; set; } - // public string Location { get; set; } - // public double TotalCost { get; set; } - // public string LotStatusOptionName { get; set; } - // public double WaferCost { get; set; } - // public double DieCost { get; set; } - //} +public class PartGroup { + public int PartGroupID { get; set; } + public string PartGroupName { get; set; } - public class PartGroup - { - public int PartGroupID { get; set; } - public string PartGroupName { get; set; } +} - } +public class Module { - public class Module - { - public int ModuleID { get; set; } - //public int MRBNumber { get; set; } - public string ModuleName { get; set; } + public int ModuleID { get; set; } + public string ModuleName { get; set; } - } +} +public class RiskAssessment { - public class RiskAssessment - { + public int RiskAssessmentID { get; set; } + public string RiskAssessmentName { get; set; } - public int RiskAssessmentID { get; set; } - //public int MRBNumber { get; set; } - public string RiskAssessmentName { get; set; } +} - } +public class Disposition { + public int DispositionID { get; set; } + public int MRBNumber { get; set; } + [Display(Name = "Type")] + public string DispositionType { get; set; } + [Display(Name = "Dispo Desc")] + public string DispositionName { get; set; } + public string DispositionNotes { get; set; } - public class Disposition - { + //Duplicated as the CloseToQDBOptionID is being used in the dropdown in the Grid kept the old code + public int CloseToQDBOption_ID { get; set; } - public int DispositionID { get; set; } - public int MRBNumber { get; set; } - [Display(Name = "Type")] - public string DispositionType { get; set; } - [Display(Name="Dispo Desc")] - public string DispositionName { get; set; } - public string DispositionNotes { get; set; } + [UIHint("CloseToQDBTemplate")] + [Display(Name = "Close To QDB(Yes/No)")] + public CloseToQDBOptionViewModel CloseToQDBOption { get; set; } - //Duplicated as the CloseToQDBOptionID is being used in the dropdown in the Grid kept the old code - public int CloseToQDBOption_ID { get; set; } - //public string CloseToQDBOption { get; set; } - - [UIHint("CloseToQDBTemplate")] - [Display(Name = "Close To QDB(Yes/No)")] - public CloseToQDBOptionViewModel CloseToQDBOption { get; set; } - - [Display(Name = "MRB Flag to SPN")] - public string CloseToQDBOptionString - { - get - { - switch (CloseToQDBOption_ID) - { - case 0: - return "No"; - case 1: - return "Yes"; - default: - return "No"; - } + [Display(Name = "MRB Flag to SPN")] + public string CloseToQDBOptionString { + get { + switch (CloseToQDBOption_ID) { + case 0: + return "No"; + case 1: + return "Yes"; + default: + return "No"; } } - } +} - public class MRBAttachment - { - public int AttachmentID { set; get; } - public int MRBNumber { get; set; } - public string FileName { get; set; } - public int UserID { get; set; } - // extrafield - public string FullName { get; set; } - public string UploadDate { get; set; } - public string Path { get; set; } +public class MRBAttachment { - } + public int AttachmentID { set; get; } + public int MRBNumber { get; set; } + public string FileName { get; set; } + public int UserID { get; set; } + // extrafield + public string FullName { get; set; } + public string UploadDate { get; set; } + public string Path { get; set; } +} - public class ContainmentActionObj - { - public int ContainmentActionID { get; set; } - public int MRBNumber { get; set; } - public string ContainmentAction { get; set; } - public int ResponsibilityOwnerID { get; set; } - public int CurrentResponsibilityOwnerID { get; set; } - public string ResponsibilityOwner { get; set; } +public class ContainmentActionObj { - //[DataType(DataType.Date)] - public DateTime? ECD { get; set; } + public int ContainmentActionID { get; set; } + public int MRBNumber { get; set; } + public string ContainmentAction { get; set; } + public int ResponsibilityOwnerID { get; set; } + public int CurrentResponsibilityOwnerID { get; set; } + public string ResponsibilityOwner { get; set; } - [DataType(DataType.Date)] - public DateTime? ImplementedDate { get; set; } - } + //[DataType(DataType.Date)] + public DateTime? ECD { get; set; } + + [DataType(DataType.Date)] + public DateTime? ImplementedDate { get; set; } + +} + +public class SPN_MRB { + + public int MRBNumber; + public char? DispoType; - public class SPN_MRB - { - public int MRBNumber; - public char? DispoType; - } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/PartsRequestModels.cs b/Fab2ApprovalSystem/Models/PartsRequestModels.cs index 7c502bc..7b2573f 100644 --- a/Fab2ApprovalSystem/Models/PartsRequestModels.cs +++ b/Fab2ApprovalSystem/Models/PartsRequestModels.cs @@ -1,85 +1,77 @@ using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.Models -{ +namespace Fab2ApprovalSystem.Models; - [Serializable] - public class PartsRequest - { - public int PRNumber { get; set; } - public string Title { get; set; } +[Serializable] +public class PartsRequest { - public DateTime CreateDate { get; set; } - public DateTime? SubmitDate { get; set; } - public DateTime? CloseDate { get; set; } + public int PRNumber { get; set; } + public string Title { get; set; } + public DateTime CreateDate { get; set; } + public DateTime? SubmitDate { get; set; } + public DateTime? CloseDate { get; set; } + public int OriginatorID { get; set; } + public int RequestorID { get; set; } + public int TechLeadID { get; set; } + public string Description { get; set; } + public DateTime? LastUpdateDate { get; set; } + public int CurrentStep { get; set; } + public string Status { get; set; } - public int OriginatorID { get; set; } - public int RequestorID { get; set; } - public int TechLeadID { get; set; } - public string Description { get; set; } +} - public DateTime? LastUpdateDate { get; set; } +[Serializable] +public class PartsRequestAttachment { - public int CurrentStep { get; set; } + public int AttachmentID { set; get; } + public int PRNumber { get; set; } + public string FileName { get; set; } + public int UserID { get; set; } + public string UploadDate { get; set; } - public string Status { get; set; } - } +} - [Serializable] - public class PartsRequestAttachment - { - public int AttachmentID { set; get; } - public int PRNumber { get; set; } - public string FileName { get; set; } - public int UserID { get; set; } - public string UploadDate { get; set; } - } +[Serializable] +public class PartsRequestAttachmentList { - [Serializable] - public class PartsRequestAttachmentList - { - public int AttachmentID { set; get; } - public int PRNumber { get; set; } - public string FileName { get; set; } - public int UserID { get; set; } - public string UploadDate { get; set; } + public int AttachmentID { set; get; } + public int PRNumber { get; set; } + public string FileName { get; set; } + public int UserID { get; set; } + public string UploadDate { get; set; } + public string FullName { get; set; } - public string FullName { get; set; } - } +} - public class PartsRequestList - { - public int PRNumber { get; set; } - public string Title { get; set; } - public DateTime CreateDate { get; set; } - public DateTime SubmitDate { get; set; } - public DateTime CloseDate { get; set; } - public string Originator { get; set; } - public string Requestor { get; set; } - public string TechLead { get; set; } - public string Description { get; set; } - public string Status { get; set; } - public string PendingApprovers { get; set; } - } +public class PartsRequestList { - public class MyPartsRequestList - { - public int PRNumber { get; set; } - public string Title { get; set; } - public string Description { get; set; } - public DateTime CreateDate { get; set; } - public DateTime? SubmitDate { get; set; } - public DateTime? CloseDate { get; set; } - public string Originator { get; set; } - public string Requestor { get; set; } - public string TechLead { get; set; } - public string Status { get; set; } - public string PendingApprovers { get; set; } - public string WorkFlowStepName { get; set; } - } + public int PRNumber { get; set; } + public string Title { get; set; } + public DateTime CreateDate { get; set; } + public DateTime SubmitDate { get; set; } + public DateTime CloseDate { get; set; } + public string Originator { get; set; } + public string Requestor { get; set; } + public string TechLead { get; set; } + public string Description { get; set; } + public string Status { get; set; } + public string PendingApprovers { get; set; } + +} + +public class MyPartsRequestList { + + public int PRNumber { get; set; } + public string Title { get; set; } + public string Description { get; set; } + public DateTime CreateDate { get; set; } + public DateTime? SubmitDate { get; set; } + public DateTime? CloseDate { get; set; } + public string Originator { get; set; } + public string Requestor { get; set; } + public string TechLead { get; set; } + public string Status { get; set; } + public string PendingApprovers { get; set; } + public string WorkFlowStepName { get; set; } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/ProductViewModel.cs b/Fab2ApprovalSystem/Models/ProductViewModel.cs index 4e65c7d..9433520 100644 --- a/Fab2ApprovalSystem/Models/ProductViewModel.cs +++ b/Fab2ApprovalSystem/Models/ProductViewModel.cs @@ -1,68 +1,56 @@ using System; -using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.Models -{ - public class ProductViewModel - { - [ScaffoldColumn(false)] - public int ProductID - { - get; - set; - } +namespace Fab2ApprovalSystem.Models; - [Required] - [DisplayName("Product name")] - public string ProductName - { - get; - set; - } +public class ProductViewModel { + [ScaffoldColumn(false)] + public int ProductID { + get; + set; + } - [Required] - [DisplayName("Unit price")] - [DataType(DataType.Currency)] - [Range(0, int.MaxValue)] - public decimal UnitPrice - { - get; - set; - } + [Required] + [DisplayName("Product name")] + public string ProductName { + get; + set; + } - [Required] - [DisplayName("Units in stock")] - [DataType("Integer")] - [Range(0, int.MaxValue)] - public int UnitsInStock - { - get; - set; - } + [Required] + [DisplayName("Unit price")] + [DataType(DataType.Currency)] + [Range(0, int.MaxValue)] + public decimal UnitPrice { + get; + set; + } - public bool Discontinued - { - get; - set; - } + [Required] + [DisplayName("Units in stock")] + [DataType("Integer")] + [Range(0, int.MaxValue)] + public int UnitsInStock { + get; + set; + } - [DisplayName("Last supply")] - [DataType(DataType.Date)] - public DateTime LastSupply - { - get; - set; - } + public bool Discontinued { + get; + set; + } - [DataType("Integer")] - public int UnitsOnOrder - { - get; - set; - } + [DisplayName("Last supply")] + [DataType(DataType.Date)] + public DateTime LastSupply { + get; + set; + } + + [DataType("Integer")] + public int UnitsOnOrder { + get; + set; } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/TestModels.cs b/Fab2ApprovalSystem/Models/TestModels.cs index d51099a..e09bb7f 100644 --- a/Fab2ApprovalSystem/Models/TestModels.cs +++ b/Fab2ApprovalSystem/Models/TestModels.cs @@ -1,15 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using System.Collections.Generic; -namespace Fab2ApprovalSystem.Models -{ - public class TestModel - { - public string Name { get; set; } +namespace Fab2ApprovalSystem.Models; - public List Countries { get; set; } +public class TestModel { + + public string Name { get; set; } + public List Countries { get; set; } - } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/Training.cs b/Fab2ApprovalSystem/Models/Training.cs index abcb711..9b3d39c 100644 --- a/Fab2ApprovalSystem/Models/Training.cs +++ b/Fab2ApprovalSystem/Models/Training.cs @@ -28,7 +28,6 @@ namespace Fab2ApprovalSystem.Models { get { - ECN_DMO ecnDMO = new ECN_DMO(); string ECNTitle = ecnDMO.GetECN(ECN).Title; diff --git a/Fab2ApprovalSystem/Models/TrainingDB.Context.cs b/Fab2ApprovalSystem/Models/TrainingDB.Context.cs index b7d955d..de006ad 100644 --- a/Fab2ApprovalSystem/Models/TrainingDB.Context.cs +++ b/Fab2ApprovalSystem/Models/TrainingDB.Context.cs @@ -1,3 +1,5 @@ +#if !NET8 + //------------------------------------------------------------------------------ // // This code was generated from a template. @@ -42,3 +44,5 @@ namespace Fab2ApprovalSystem.Models public virtual DbSet TECNNotificationsUsers { get; set; } } } + +#endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/UserSubRoles.cs b/Fab2ApprovalSystem/Models/UserSubRoles.cs index 22d9c5d..a2176c7 100644 --- a/Fab2ApprovalSystem/Models/UserSubRoles.cs +++ b/Fab2ApprovalSystem/Models/UserSubRoles.cs @@ -1,14 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +namespace Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.Models -{ - public class UserSubRoles - { - public int SubRoleID { get; set; } - public string RoleName { get; set; } - public string SubRoleName { get; set; } - } -} +public class UserSubRoles { + + public int SubRoleID { get; set; } + public string RoleName { get; set; } + public string SubRoleName { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/WinEventLogModel.cs b/Fab2ApprovalSystem/Models/WinEventLogModel.cs index ca0ff06..17d70ae 100644 --- a/Fab2ApprovalSystem/Models/WinEventLogModel.cs +++ b/Fab2ApprovalSystem/Models/WinEventLogModel.cs @@ -1,22 +1,13 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; +namespace Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.Models -{ - public class WinEventLog - { - //[Key] +public class WinEventLog { + //[Key] - public int SysDocumentID{ get; set; } - public int IssueID { get; set; } - public string DocumentType { get; set; } - public string UserID { get; set; } - public string OperationType { get; set; } - public string Comments { get; set; } + public int SysDocumentID { get; set; } + public int IssueID { get; set; } + public string DocumentType { get; set; } + public string UserID { get; set; } + public string OperationType { get; set; } + public string Comments { get; set; } - - } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/WorkFlowModels.cs b/Fab2ApprovalSystem/Models/WorkFlowModels.cs index 24a8682..b837df5 100644 --- a/Fab2ApprovalSystem/Models/WorkFlowModels.cs +++ b/Fab2ApprovalSystem/Models/WorkFlowModels.cs @@ -1,43 +1,39 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.Models -{ - public class ApprovalModel - { - public int ApprovalID { get; set; } - public int? IssueID { get; set; } - public string RoleName { get; set; } // nullable - public string SubRole { get; set; } - public int UserID { get; set; } - public int SubRoleID { get; set; } - public int? ItemStatus { get; set; } - public int? Step { get; set; } - public DateTime NotifyDate { get; set; } // nullable - public DateTime AssignedDate { get; set; } // nullable - public DateTime RoleAssignedDate { get; set; } // nullable - public DateTime CompletedDate { get; set; } // nullable - public string Comments { get; set; } // nullable - public byte? ApprovalType { get; set; } - public Guid? BackToApprovalID { get; set; } - public int DocumentTypeID { get; set; } - public bool DisplayDeniedDocument { get; set; } - public bool Delegated { get; set; } - } +namespace Fab2ApprovalSystem.Models; + +public class ApprovalModel { + + public int ApprovalID { get; set; } + public int? IssueID { get; set; } + public string RoleName { get; set; } // nullable + public string SubRole { get; set; } + public int UserID { get; set; } + public int SubRoleID { get; set; } + public int? ItemStatus { get; set; } + public int? Step { get; set; } + public DateTime NotifyDate { get; set; } // nullable + public DateTime AssignedDate { get; set; } // nullable + public DateTime RoleAssignedDate { get; set; } // nullable + public DateTime CompletedDate { get; set; } // nullable + public string Comments { get; set; } // nullable + public byte? ApprovalType { get; set; } + public Guid? BackToApprovalID { get; set; } + public int DocumentTypeID { get; set; } + public bool DisplayDeniedDocument { get; set; } + public bool Delegated { get; set; } - public class WorkflowSteps - { - public int WorkflowStepID { get; set; } - public int WorkflowID { get; set; } - public int WorkflowStepNumber { get; set; } - public string WorkFlowStepName { get; set; } // nullable - public int RoleID { get; set; } - public bool RulesApply { get; set; } - public int ApprovalType { get; set; } - public bool? AllowReject { get; set; } - } } +public class WorkflowSteps { + public int WorkflowStepID { get; set; } + public int WorkflowID { get; set; } + public int WorkflowStepNumber { get; set; } + public string WorkFlowStepName { get; set; } // nullable + public int RoleID { get; set; } + public bool RulesApply { get; set; } + public int ApprovalType { get; set; } + public bool? AllowReject { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/PdfGenerator/BinaryContentResult.cs b/Fab2ApprovalSystem/PdfGenerator/BinaryContentResult.cs index 0a98785..ba08fc7 100644 --- a/Fab2ApprovalSystem/PdfGenerator/BinaryContentResult.cs +++ b/Fab2ApprovalSystem/PdfGenerator/BinaryContentResult.cs @@ -1,4 +1,6 @@ -// -------------------------------------------------------------------------------------------------------------------- +#if !NET8 + +// -------------------------------------------------------------------------------------------------------------------- // // http://www.SemanticArchitecture.net pkalkie@gmail.com // @@ -7,8 +9,7 @@ // // -------------------------------------------------------------------------------------------------------------------- -namespace Fab2ApprovalSystem.PdfGenerator -{ +namespace Fab2ApprovalSystem.PdfGenerator { using System.IO; using System.Web; using System.Web.Mvc; @@ -16,29 +17,27 @@ namespace Fab2ApprovalSystem.PdfGenerator /// /// An ActionResult used to send binary data to the browser. /// - public class BinaryContentResult : ActionResult - { + public class BinaryContentResult : ActionResult { private readonly string contentType; private readonly byte[] contentBytes; - public BinaryContentResult(byte[] contentBytes, string contentType) - { + public BinaryContentResult(byte[] contentBytes, string contentType) { this.contentBytes = contentBytes; this.contentType = contentType; } - public override void ExecuteResult(ControllerContext context) - { + public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; response.Clear(); response.Cache.SetCacheability(HttpCacheability.Public); response.ContentType = this.contentType; - using (var stream = new MemoryStream(this.contentBytes)) - { + using (var stream = new MemoryStream(this.contentBytes)) { stream.WriteTo(response.OutputStream); stream.Flush(); } } } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/PdfGenerator/FakeView.cs b/Fab2ApprovalSystem/PdfGenerator/FakeView.cs index cceab06..1aff427 100644 --- a/Fab2ApprovalSystem/PdfGenerator/FakeView.cs +++ b/Fab2ApprovalSystem/PdfGenerator/FakeView.cs @@ -1,3 +1,5 @@ +#if !NET8 + // -------------------------------------------------------------------------------------------------------------------- // // http://www.SemanticArchitecture.net pkalkie@gmail.com @@ -7,21 +9,20 @@ // // -------------------------------------------------------------------------------------------------------------------- -namespace Fab2ApprovalSystem.PdfGenerator -{ +namespace Fab2ApprovalSystem.PdfGenerator { using System; using System.IO; using System.Web.Mvc; - public class FakeView : IView - { + public class FakeView : IView { #region IView Members - public void Render(ViewContext viewContext, TextWriter writer) - { + public void Render(ViewContext viewContext, TextWriter writer) { throw new NotImplementedException(); } #endregion } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/PdfGenerator/HtmlViewRenderer.cs b/Fab2ApprovalSystem/PdfGenerator/HtmlViewRenderer.cs index 4339175..d3ba69d 100644 --- a/Fab2ApprovalSystem/PdfGenerator/HtmlViewRenderer.cs +++ b/Fab2ApprovalSystem/PdfGenerator/HtmlViewRenderer.cs @@ -1,3 +1,5 @@ +#if !NET8 + // -------------------------------------------------------------------------------------------------------------------- // // http://www.SemanticArchitecture.net pkalkie@gmail.com @@ -7,8 +9,7 @@ // // -------------------------------------------------------------------------------------------------------------------- -namespace Fab2ApprovalSystem.PdfGenerator -{ +namespace Fab2ApprovalSystem.PdfGenerator { using System.IO; using System.Text; using System.Web; @@ -18,13 +19,10 @@ namespace Fab2ApprovalSystem.PdfGenerator /// /// This class is responsible for rendering a HTML view into a string. /// - public class HtmlViewRenderer - { - public string RenderViewToString(Controller controller, string viewName, object viewData) - { + public class HtmlViewRenderer { + public string RenderViewToString(Controller controller, string viewName, object viewData) { var renderedView = new StringBuilder(); - using (var responseWriter = new StringWriter(renderedView)) - { + using (var responseWriter = new StringWriter(renderedView)) { var fakeResponse = new HttpResponse(responseWriter); var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse); var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), controller.ControllerContext.RouteData, controller.ControllerContext.Controller); @@ -32,8 +30,7 @@ namespace Fab2ApprovalSystem.PdfGenerator var oldContext = HttpContext.Current; HttpContext.Current = fakeContext; - using (var viewPage = new ViewPage()) - { + using (var viewPage = new ViewPage()) { var html = new HtmlHelper(CreateViewContext(responseWriter, fakeControllerContext), viewPage); html.RenderPartial(viewName, viewData); HttpContext.Current = oldContext; @@ -43,9 +40,10 @@ namespace Fab2ApprovalSystem.PdfGenerator return renderedView.ToString(); } - private static ViewContext CreateViewContext(TextWriter responseWriter, ControllerContext fakeControllerContext) - { + private static ViewContext CreateViewContext(TextWriter responseWriter, ControllerContext fakeControllerContext) { return new ViewContext(fakeControllerContext, new FakeView(), new ViewDataDictionary(), new TempDataDictionary(), responseWriter); } } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/PdfGenerator/PdfViewController.cs b/Fab2ApprovalSystem/PdfGenerator/PdfViewController.cs index 70b8232..07ae2f5 100644 --- a/Fab2ApprovalSystem/PdfGenerator/PdfViewController.cs +++ b/Fab2ApprovalSystem/PdfGenerator/PdfViewController.cs @@ -1,4 +1,6 @@ -// -------------------------------------------------------------------------------------------------------------------- +#if !NET8 + +// -------------------------------------------------------------------------------------------------------------------- // // http://www.SemanticArchitecture.net pkalkie@gmail.com // @@ -7,21 +9,18 @@ // // -------------------------------------------------------------------------------------------------------------------- -namespace Fab2ApprovalSystem.PdfGenerator -{ +namespace Fab2ApprovalSystem.PdfGenerator { using System.Web.Mvc; using System.IO; /// /// Extends the controller with functionality for rendering PDF views /// - public class PdfViewController : Controller - { + public class PdfViewController : Controller { private readonly HtmlViewRenderer htmlViewRenderer; private readonly StandardPdfRenderer standardPdfRenderer; - public PdfViewController() - { + public PdfViewController() { this.htmlViewRenderer = new HtmlViewRenderer(); this.standardPdfRenderer = new StandardPdfRenderer(); } @@ -29,12 +28,11 @@ namespace Fab2ApprovalSystem.PdfGenerator /// /// /// - /// - /// - /// + + + /// - protected ActionResult ViewPdf(string pageTitle, string viewName, object model) - { + protected ActionResult ViewPdf(string pageTitle, string viewName, object model) { // Render the view html to a string. string htmlText = this.htmlViewRenderer.RenderViewToString(this, viewName, model); @@ -48,22 +46,22 @@ namespace Fab2ApprovalSystem.PdfGenerator /// /// /// - /// - /// - /// - protected void SavePdf(string fileName, string viewName, object model) - { + + + + protected void SavePdf(string fileName, string viewName, object model) { // Render the view html to a string. string htmlText = this.htmlViewRenderer.RenderViewToString(this, viewName, model); // Let the html be rendered into a PDF document through iTextSharp. byte[] buffer = standardPdfRenderer.Render(htmlText, ""); - using (FileStream fs = new FileStream(fileName, FileMode.Create)) - { + using (FileStream fs = new FileStream(fileName, FileMode.Create)) { fs.Write(buffer, 0, buffer.Length); } - + } } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/PdfGenerator/PrintHeaderFooter.cs b/Fab2ApprovalSystem/PdfGenerator/PrintHeaderFooter.cs index 2d21e5d..00322fc 100644 --- a/Fab2ApprovalSystem/PdfGenerator/PrintHeaderFooter.cs +++ b/Fab2ApprovalSystem/PdfGenerator/PrintHeaderFooter.cs @@ -1,17 +1,16 @@ -namespace Fab2ApprovalSystem.PdfGenerator -{ - using System; - +#if !NET8 +namespace Fab2ApprovalSystem.PdfGenerator { using iTextSharp.text; using iTextSharp.text.pdf; + using System; + /// /// This class represents the standard header and footer for a PDF print. /// application. /// - public class PrintHeaderFooter : PdfPageEventHelper - { + public class PrintHeaderFooter : PdfPageEventHelper { private PdfContentByte pdfContent; private PdfTemplate pageNumberTemplate; private BaseFont baseFont; @@ -19,22 +18,19 @@ namespace Fab2ApprovalSystem.PdfGenerator public string Title { get; set; } - public override void OnOpenDocument(PdfWriter writer, Document document) - { + public override void OnOpenDocument(PdfWriter writer, Document document) { printTime = DateTime.Now; baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); pdfContent = writer.DirectContent; pageNumberTemplate = pdfContent.CreateTemplate(50, 50); } - public override void OnStartPage(PdfWriter writer, Document document) - { + public override void OnStartPage(PdfWriter writer, Document document) { base.OnStartPage(writer, document); Rectangle pageSize = document.PageSize; - if (Title != string.Empty) - { + if (Title != string.Empty) { pdfContent.BeginText(); pdfContent.SetFontAndSize(baseFont, 11); pdfContent.SetRGBColorFill(0, 0, 0); @@ -44,8 +40,7 @@ namespace Fab2ApprovalSystem.PdfGenerator } } - public override void OnEndPage(PdfWriter writer, Document document) - { + public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); int pageN = writer.PageNumber; @@ -70,8 +65,7 @@ namespace Fab2ApprovalSystem.PdfGenerator pdfContent.EndText(); } - public override void OnCloseDocument(PdfWriter writer, Document document) - { + public override void OnCloseDocument(PdfWriter writer, Document document) { base.OnCloseDocument(writer, document); pageNumberTemplate.BeginText(); @@ -81,4 +75,5 @@ namespace Fab2ApprovalSystem.PdfGenerator pageNumberTemplate.EndText(); } } -} \ No newline at end of file +} +#endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/PdfGenerator/StandardPdfRenderer.cs b/Fab2ApprovalSystem/PdfGenerator/StandardPdfRenderer.cs index 408b034..27b0946 100644 --- a/Fab2ApprovalSystem/PdfGenerator/StandardPdfRenderer.cs +++ b/Fab2ApprovalSystem/PdfGenerator/StandardPdfRenderer.cs @@ -1,49 +1,44 @@ -using System.IO; +#if !NET8 using iTextSharp.text; using iTextSharp.text.html.simpleparser; using iTextSharp.text.pdf; +#endif +using System.IO; -namespace Fab2ApprovalSystem.PdfGenerator -{ +namespace Fab2ApprovalSystem.PdfGenerator; +/// +/// This class is responsible for rendering a html text string to a PDF document using the html renderer of iTextSharp. +/// +public class StandardPdfRenderer { + private const int HorizontalMargin = 40; + private const int VerticalMargin = 40; - /// - /// This class is responsible for rendering a html text string to a PDF document using the html renderer of iTextSharp. - /// - public class StandardPdfRenderer - { - private const int HorizontalMargin = 40; - private const int VerticalMargin = 40; + public byte[] Render(string htmlText, string pageTitle) { + byte[] renderedBuffer; - public byte[] Render(string htmlText, string pageTitle) - { - byte[] renderedBuffer; - - using (var outputMemoryStream = new MemoryStream()) - { - using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin)) - { - PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream); - pdfWriter.CloseStream = false; - pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle }; - pdfDocument.Open(); - using (var htmlViewReader = new StringReader(htmlText)) - { - using (var htmlWorker = new HTMLWorker(pdfDocument)) - { - htmlWorker.Parse(htmlViewReader); - } + using (MemoryStream outputMemoryStream = new()) { +#if !NET8 + using (Document pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin)) { + PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream); + pdfWriter.CloseStream = false; + pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle }; + pdfDocument.Open(); + using (StringReader htmlViewReader = new StringReader(htmlText)) { + using (HTMLWorker htmlWorker = new HTMLWorker(pdfDocument)) { + htmlWorker.Parse(htmlViewReader); } - } - - renderedBuffer = new byte[outputMemoryStream.Position]; - outputMemoryStream.Position = 0; - outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length); - } - return renderedBuffer; + } +#endif + + renderedBuffer = new byte[outputMemoryStream.Position]; + outputMemoryStream.Position = 0; + outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length); } + + return renderedBuffer; } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Startup.cs b/Fab2ApprovalSystem/Startup.cs index 65ba6aa..283d144 100644 --- a/Fab2ApprovalSystem/Startup.cs +++ b/Fab2ApprovalSystem/Startup.cs @@ -8,6 +8,7 @@ using Quartz.Impl; [assembly: OwinStartupAttribute(typeof(Fab2ApprovalSystem.Startup))] namespace Fab2ApprovalSystem { + public partial class Startup { protected void Application_Start() diff --git a/Fab2ApprovalSystem/Utilities/EmailUtilities.cs b/Fab2ApprovalSystem/Utilities/EmailUtilities.cs index 280f967..fdebde3 100644 --- a/Fab2ApprovalSystem/Utilities/EmailUtilities.cs +++ b/Fab2ApprovalSystem/Utilities/EmailUtilities.cs @@ -1,45 +1,34 @@ +#pragma warning disable CS8019 + using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Web; -using System.Web.Mvc; -namespace Fab2ApprovalSystem.Utilities -{ - public class EmailUtilities - { - // GET: EmailUtilities - public void SendNotification(string Recep, List ccRecipients, string emailTitle, string email_body, string email_title) - { - SmtpClient client = new SmtpClient(); - MailMessage msg = new MailMessage(); - msg.IsBodyHtml = true; - msg.From = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval"); - msg.Sender = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval"); - msg.To.Add(Recep); - //msg.To.Add("Jonathan.Ouellette@infineon.com"); - foreach (string ccRecipient in ccRecipients) - { - try - { - msg.CC.Add(ccRecipient); - } - catch - { - Console.WriteLine("Invalid Email Address detected: " + ccRecipient); - } +#pragma warning restore CS8019 - } - //msg.CC.Add(recipientCC); - msg.Subject = email_title; - msg.Body = email_body; +namespace Fab2ApprovalSystem.Utilities; - SmtpClient SmtpMail = new SmtpClient("mailrelay-internal.infineon.com"); +public class EmailUtilities { - SmtpMail.Send(msg); - - + public static void SendNotification(string to, List ccRecipients, string subject, string body) { + MailMessage msg = new(); + msg.To.Add(to); + msg.IsBodyHtml = true; + msg.From = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval"); + msg.Sender = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval"); + foreach (string ccRecipient in ccRecipients) { + try { + msg.CC.Add(ccRecipient); + } catch { + Console.WriteLine("Invalid Email Address detected: " + ccRecipient); + } } + msg.Body = body; + msg.Subject = subject; + SmtpClient smtpClient = new("mailrelay-internal.infineon.com"); + smtpClient.Send(msg); } -} + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Utilities/FileUtilities.cs b/Fab2ApprovalSystem/Utilities/FileUtilities.cs index d011fab..ff850b8 100644 --- a/Fab2ApprovalSystem/Utilities/FileUtilities.cs +++ b/Fab2ApprovalSystem/Utilities/FileUtilities.cs @@ -1,34 +1,50 @@ +#pragma warning disable CS8019 + using System; using System.Collections.Generic; using System.Linq; using System.Web; + +#if !NET8 using System.Web.Mvc; +#endif + using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Misc; + using System.IO; using System.Configuration; -namespace Fab2ApprovalSystem.Utilities +#pragma warning restore CS8019 + +namespace Fab2ApprovalSystem.Utilities; + +#if !NET8 +public class FileUtilities : Controller // => System.Web.Mvc.FileContentResult { - public class FileUtilities : Controller - { - public ActionResult DownloadFilesFromServer(string pathToFile) - { - //string templatesPath = GlobalVars.CA_BlankFormsLocation; - //string fullName = Server.MapPath("~" + filePath); - byte[] fileBytes = GetFile(pathToFile); - return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, pathToFile); - } + public T DownloadFilesFromServer(string pathToFile) { + //string templatesPath = GlobalVars.CA_BlankFormsLocation; + //string fullName = Server.MapPath("~" + filePath); - public byte[] GetFile(string s) - { - System.IO.FileStream fs = System.IO.File.OpenRead(s); - byte[] data = new byte[fs.Length]; - int br = fs.Read(data, 0, data.Length); - if (br != fs.Length) - throw new System.IO.IOException(s); - return data; - } + byte[] fileBytes = GetFile(pathToFile); + var result = File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, pathToFile); + return (T)Convert.ChangeType(result, typeof(T)); } -} +#else +public class FileUtilities { +#endif + + public byte[] GetFile(string s) { +#if !NET8 + FileStream fs = System.IO.File.OpenRead(s); +#else + FileStream fs = File.OpenRead(s); +#endif + byte[] data = new byte[fs.Length]; + int br = fs.Read(data, 0, data.Length); + if (br != fs.Length) + throw new IOException(s); + return data; + } +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/Utilities/UserUtilities.cs b/Fab2ApprovalSystem/Utilities/UserUtilities.cs index e5f8fa8..b5c7987 100644 --- a/Fab2ApprovalSystem/Utilities/UserUtilities.cs +++ b/Fab2ApprovalSystem/Utilities/UserUtilities.cs @@ -1,48 +1,39 @@ -using System; using System.Collections.Generic; using System.DirectoryServices.AccountManagement; using System.Linq; -using System.Web; + using Fab2ApprovalSystem.Models; -namespace Fab2ApprovalSystem.Utilities -{ - public class UserUtilities - { - public List GetMesaUsers() - { - PrincipalContext ctx = new PrincipalContext(ContextType.Domain, - "infineon.com", - "DC=infineon,DC=com", - "MESfisharepoint", - "GaN2020=BestWafers!"); +namespace Fab2ApprovalSystem.Utilities; - GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, - IdentityType.Name, - "MES-IFX-Employees-Mesa"); - List MesaUsers = new List(); - if (grp != null) - { - foreach (Principal p in grp.GetMembers(true)) - { - MesaUsers.Add(new AllUserModel - { - UserName = p.Name, - DisplayName = p.DisplayName - - } - - ); - //Console.WriteLine(p.Name); - } - grp.Dispose(); +public class UserUtilities { + + public static List GetMesaUsers() { + PrincipalContext ctx = new(ContextType.Domain, + "infineon.com", + "DC=infineon,DC=com", + "MESfisharepoint", + "GaN2020=BestWafers!"); + + GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, + IdentityType.Name, + "MES-IFX-Employees-Mesa"); + List MesaUsers = new(); + if (grp != null) { + foreach (Principal p in grp.GetMembers(true)) { + MesaUsers.Add(new AllUserModel { + UserName = p.Name, + DisplayName = p.DisplayName + + }); } - - ctx.Dispose(); - MesaUsers = (from a in MesaUsers orderby a.DisplayName ascending select a).ToList(); - - return MesaUsers; + grp.Dispose(); } + ctx.Dispose(); + MesaUsers = (from a in MesaUsers orderby a.DisplayName ascending select a).ToList(); + + return MesaUsers; } -} + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/ApproversListViewModel.cs b/Fab2ApprovalSystem/ViewModels/ApproversListViewModel.cs index e2581fb..5b973bb 100644 --- a/Fab2ApprovalSystem/ViewModels/ApproversListViewModel.cs +++ b/Fab2ApprovalSystem/ViewModels/ApproversListViewModel.cs @@ -1,21 +1,17 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.ViewModels -{ - public class ApproversListViewModel - { - public int ApprovalID { get; set; } - public int UserID { get; set; } - public string FullName { get; set; } - public string RoleName { get; set; } - public string SubRoleName { get; set; } - public string Status { get; set; } - public DateTime? AssignedDate { get; set; } - public DateTime? CompletedDate { get; set; } - public string Comments { get; set; } +namespace Fab2ApprovalSystem.ViewModels; + +public class ApproversListViewModel { + + public int ApprovalID { get; set; } + public int UserID { get; set; } + public string FullName { get; set; } + public string RoleName { get; set; } + public string SubRoleName { get; set; } + public string Status { get; set; } + public DateTime? AssignedDate { get; set; } + public DateTime? CompletedDate { get; set; } + public string Comments { get; set; } - } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/ChangeControlViewModel.cs b/Fab2ApprovalSystem/ViewModels/ChangeControlViewModel.cs index e92d138..2fb77e6 100644 --- a/Fab2ApprovalSystem/ViewModels/ChangeControlViewModel.cs +++ b/Fab2ApprovalSystem/ViewModels/ChangeControlViewModel.cs @@ -1,70 +1,46 @@ using System; -using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.ViewModels -{ - public class ChangeControlViewModel - { +namespace Fab2ApprovalSystem.ViewModels; - public int PlanNumber { get; set; } - public int OwnerID { get; set; } - public string OwnerName { get; set; } - public byte CurrentStep { get; set; } - public int Status { get; set; } - public int MeetingExist { get; set; } +public class ChangeControlViewModel { - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? ClosedDate { get; set; } - - public int ChangeLevel { get; set; } - public int IsITAR { get; set; } - public int IsMedical { get; set; } - public int IsRadHard { get; set; } - public int IsAutomotive { get; set; } - public string Title { get; set; } - public string ReasonForChange { get; set; } - public string ChangeDescription { get; set; } - public string Notes { get; set; } - public string RecordLockByName { get; set; } - public bool PCRBClosed { get; set; } + public int PlanNumber { get; set; } + public int OwnerID { get; set; } + public string OwnerName { get; set; } + public byte CurrentStep { get; set; } + public int Status { get; set; } + public int MeetingExist { get; set; } - // important!!make sure the id of the control matches the name of the field in the model it is being binded to, - // in order to get the selected items from the control - //public List GenerationIDs { get; set; } + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? ClosedDate { get; set; } + public int ChangeLevel { get; set; } + public int IsITAR { get; set; } + public int IsMedical { get; set; } + public int IsRadHard { get; set; } + public int IsAutomotive { get; set; } + public string Title { get; set; } + public string ReasonForChange { get; set; } + public string ChangeDescription { get; set; } + public string Notes { get; set; } + public string RecordLockByName { get; set; } + public bool PCRBClosed { get; set; } + public bool RecordLockIndicator { get; set; } + public int RecordLockedBy { get; set; } + public bool RecordLocked { get; set; } + public DateTime RecordLockedDate { get; set; } + public DateTime LastUpdateDate { get; set; } + public int PCR1ID { get; set; } + public int PCR2ID { get; set; } + public int PCR3ID { get; set; } + public string PlanTitle { get; set; } + public ChangeControlViewModel() { + //GenerationIDs = new List(); + //LogisticsIDs = new List(); + //ProcessIDs = new List(); - //public List LogisticsIDs { get; set; } - //public List ProcessIDs { get; set; } - //public List ToolTypeIDs { get; set; } - //public List PartNumberIDs { get; set; } - - //public string Generations { get; set; } - //public string Logistics { get; set; } - //public string Processes { get; set; } - //public string ToolTypes { get; set; } - //public string PartNumbers { get; set; } - public bool RecordLockIndicator { get; set; } - public int RecordLockedBy { get; set; } - public bool RecordLocked { get; set; } - public DateTime RecordLockedDate { get; set; } - public DateTime LastUpdateDate { get; set; } - public int PCR1ID { get; set; } - public int PCR2ID { get; set; } - public int PCR3ID { get; set; } - public string PlanTitle { get; set; } - - - public ChangeControlViewModel() - { - //GenerationIDs = new List(); - //LogisticsIDs = new List(); - //ProcessIDs = new List(); - - //ToolTypeIDs = new List(); - //PartNumberIDs = new List(); - } - + //ToolTypeIDs = new List(); + //PartNumberIDs = new List(); } -} + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/CloseToQDBOptionViewModel.cs b/Fab2ApprovalSystem/ViewModels/CloseToQDBOptionViewModel.cs index 9cc726f..1783a91 100644 --- a/Fab2ApprovalSystem/ViewModels/CloseToQDBOptionViewModel.cs +++ b/Fab2ApprovalSystem/ViewModels/CloseToQDBOptionViewModel.cs @@ -1,16 +1,11 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; +using System.ComponentModel.DataAnnotations; -namespace Fab2ApprovalSystem.ViewModels -{ - public class CloseToQDBOptionViewModel - { +namespace Fab2ApprovalSystem.ViewModels; + +public class CloseToQDBOptionViewModel { + + public int CloseToQDBOptionID { get; set; } + [Display(Name = "Close To QDB(Yes/No)")] + public string CloseToQDBOption { get; set; } - public int CloseToQDBOptionID { get; set; } - [Display(Name = "Close To QDB(Yes/No)")] - public string CloseToQDBOption { get; set; } - } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/ECNTrainingAssignment.cs b/Fab2ApprovalSystem/ViewModels/ECNTrainingAssignment.cs index b53a02e..fef0abb 100644 --- a/Fab2ApprovalSystem/ViewModels/ECNTrainingAssignment.cs +++ b/Fab2ApprovalSystem/ViewModels/ECNTrainingAssignment.cs @@ -1,11 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +namespace Fab2ApprovalSystem.ViewModels; -namespace Fab2ApprovalSystem.ViewModels -{ - public class ECNTrainingAssignment - { - } +public class ECNTrainingAssignment { } \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/ECNTrainingAssignments.cs b/Fab2ApprovalSystem/ViewModels/ECNTrainingAssignments.cs index b583a4c..ad193df 100644 --- a/Fab2ApprovalSystem/ViewModels/ECNTrainingAssignments.cs +++ b/Fab2ApprovalSystem/ViewModels/ECNTrainingAssignments.cs @@ -1,19 +1,14 @@ using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.ViewModels -{ - public class ECNTrainingAssignments - { - public int TrainingAssignmentID { get; set; } - public int ECN_ID { get; set; } - public int TrainingID { get; set; } - public DateTime? DateAssigned { get; set; } - public DateTime? DateCompleted { get; set; } - public bool Status { get; set; } +namespace Fab2ApprovalSystem.ViewModels; - } -} +public class ECNTrainingAssignments { + + public int TrainingAssignmentID { get; set; } + public int ECN_ID { get; set; } + public int TrainingID { get; set; } + public DateTime? DateAssigned { get; set; } + public DateTime? DateCompleted { get; set; } + public bool Status { get; set; } + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/IssueWithExistingLotsViewModel.cs b/Fab2ApprovalSystem/ViewModels/IssueWithExistingLotsViewModel.cs index 17235c9..ea88efe 100644 --- a/Fab2ApprovalSystem/ViewModels/IssueWithExistingLotsViewModel.cs +++ b/Fab2ApprovalSystem/ViewModels/IssueWithExistingLotsViewModel.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +namespace Fab2ApprovalSystem.ViewModels; + +public class IssueWithExistingLotsViewModel { + + public string IssuesList { get; set; } + public string LotList { get; set; } -namespace Fab2ApprovalSystem.ViewModels -{ - public class IssueWithExistingLotsViewModel - { - public string IssuesList { get; set; } - public string LotList { get; set; } - } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/LTMaterial.cs b/Fab2ApprovalSystem/ViewModels/LTMaterial.cs index bbe8b18..5cb20a4 100644 --- a/Fab2ApprovalSystem/ViewModels/LTMaterial.cs +++ b/Fab2ApprovalSystem/ViewModels/LTMaterial.cs @@ -1,28 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations; -namespace Fab2ApprovalSystem.ViewModels -{ - public class LTMaterialViewModel - { - public int ID { get; set; } - [Display(Name = "WIP Part #")] - public string WIPPartNumber { get; set; } - public string Description { get; set; } - [Display(Name = "EPI Silicon Part#")] - public string EPISiliconPartNumber { get; set; } - public int Quantity { get; set; } - public string Supplier { get; set; } - public string Source { get; set; } - public int LTWorkRequestID { get; set; } - public int PreviousMaterialID { get; set; } +namespace Fab2ApprovalSystem.ViewModels; - public LTMaterialViewModel() - { - Description = ""; - } +public class LTMaterialViewModel { + + public int ID { get; set; } + [Display(Name = "WIP Part #")] + public string WIPPartNumber { get; set; } + public string Description { get; set; } + [Display(Name = "EPI Silicon Part#")] + public string EPISiliconPartNumber { get; set; } + public int Quantity { get; set; } + public string Supplier { get; set; } + public string Source { get; set; } + public int LTWorkRequestID { get; set; } + public int PreviousMaterialID { get; set; } + public LTMaterialViewModel() { + Description = ""; } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/LotDispositionLotSummaryViewModel.cs b/Fab2ApprovalSystem/ViewModels/LotDispositionLotSummaryViewModel.cs index d906133..7b3c1b1 100644 --- a/Fab2ApprovalSystem/ViewModels/LotDispositionLotSummaryViewModel.cs +++ b/Fab2ApprovalSystem/ViewModels/LotDispositionLotSummaryViewModel.cs @@ -1,30 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +namespace Fab2ApprovalSystem.ViewModels; -namespace Fab2ApprovalSystem.ViewModels -{ - public class LotDispositionLotSummaryViewModel - { - public int IssueID { get; set; } +public class LotDispositionLotSummaryViewModel { - // release lot sunn - public int LotCount { get; set; } - public int LotStatusOption { get; set; } + public int IssueID { get; set; } - public int TotalWaferCount { get; set; } - public int TotalDieCount { get; set; } - public double TotalCost { get; set; } - - public int ReleaseWaferCount { get; set; } - public int ReleaseDieCount { get; set; } - public string ReleaseCost { get; set; } - - public int ScrapWaferCount { get; set; } - public int ScrapDieCount { get; set; } - public string ScrapCost { get; set; } - + // release lot sunn + public int LotCount { get; set; } + public int LotStatusOption { get; set; } + public int TotalWaferCount { get; set; } + public int TotalDieCount { get; set; } + public double TotalCost { get; set; } + public int ReleaseWaferCount { get; set; } + public int ReleaseDieCount { get; set; } + public string ReleaseCost { get; set; } + public int ScrapWaferCount { get; set; } + public int ScrapDieCount { get; set; } + public string ScrapCost { get; set; } - } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/LotDispositionViewModel.cs b/Fab2ApprovalSystem/ViewModels/LotDispositionViewModel.cs index 32f87de..5eddcc1 100644 --- a/Fab2ApprovalSystem/ViewModels/LotDispositionViewModel.cs +++ b/Fab2ApprovalSystem/ViewModels/LotDispositionViewModel.cs @@ -1,41 +1,32 @@ using System; -using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.ViewModels -{ - public class IssuesViewModel - { - - [Display(Name = "Document Type")] - public string DocumentType { get; set; } - [Display(Name = "Sub Category")] - public string SubDoc { get; set; } - [Display(Name = "Issue#")] - public int IssueID { get; set; } - public int DocID { get; set; } - public string Title { get; set; } - public string IssueDescription { get; set; } - public string LotNos { get; set; } - public DateTime? IssueDate { get; set; } - [Display(Name = "Submit Date")] - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? SubmitedDate { get; set; } - public DateTime? CloseDate { get; set; } - public string Originator { get; set; } - public string ScrapDescription { get; set; } - public string PendingApprovers { get; set; } - public int ItemStatus { get; set; } - - public DateTime? ExpirationDate { get; set; } - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? ExtensionDate { get; set; } - public DateTime? NextDueDate { get; set; } +namespace Fab2ApprovalSystem.ViewModels; +public class IssuesViewModel { - } + [Display(Name = "Document Type")] + public string DocumentType { get; set; } + [Display(Name = "Sub Category")] + public string SubDoc { get; set; } + [Display(Name = "Issue#")] + public int IssueID { get; set; } + public int DocID { get; set; } + public string Title { get; set; } + public string IssueDescription { get; set; } + public string LotNos { get; set; } + public DateTime? IssueDate { get; set; } + [Display(Name = "Submit Date")] + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? SubmitedDate { get; set; } + public DateTime? CloseDate { get; set; } + public string Originator { get; set; } + public string ScrapDescription { get; set; } + public string PendingApprovers { get; set; } + public int ItemStatus { get; set; } + public DateTime? ExpirationDate { get; set; } + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? ExtensionDate { get; set; } + public DateTime? NextDueDate { get; set; } - -} +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/LotStatusOptionViewModel.cs b/Fab2ApprovalSystem/ViewModels/LotStatusOptionViewModel.cs index 8e3d38f..a32e364 100644 --- a/Fab2ApprovalSystem/ViewModels/LotStatusOptionViewModel.cs +++ b/Fab2ApprovalSystem/ViewModels/LotStatusOptionViewModel.cs @@ -1,16 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations; -namespace Fab2ApprovalSystem.ViewModels -{ - public class LotStatusOptionViewModel - { - public int LotStatusOptionID { get; set; } - [Display(Name="Lot Status")] - public string LotStatusOption { get; set; } - } +namespace Fab2ApprovalSystem.ViewModels; + +public class LotStatusOptionViewModel { + + public int LotStatusOptionID { get; set; } + [Display(Name = "Lot Status")] + public string LotStatusOption { get; set; } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/OOOViewModel.cs b/Fab2ApprovalSystem/ViewModels/OOOViewModel.cs index 1749cb2..7e15d1b 100644 --- a/Fab2ApprovalSystem/ViewModels/OOOViewModel.cs +++ b/Fab2ApprovalSystem/ViewModels/OOOViewModel.cs @@ -1,19 +1,15 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.ViewModels -{ - public class OOOViewModel - { - public int OOOUserID { get; set; } - public string OOOUser { get; set; } - public bool IsOOO { get; set; } - public int DelegatedToUserID { get; set; } - public string DelegatedToUser { get; set; } - public DateTime OOOStartDate { get; set; } - public DateTime OOOEndDate { get; set; } - - } +namespace Fab2ApprovalSystem.ViewModels; + +public class OOOViewModel { + + public int OOOUserID { get; set; } + public string OOOUser { get; set; } + public bool IsOOO { get; set; } + public int DelegatedToUserID { get; set; } + public string DelegatedToUser { get; set; } + public DateTime OOOStartDate { get; set; } + public DateTime OOOEndDate { get; set; } + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/OpenActionItemViewModel.cs b/Fab2ApprovalSystem/ViewModels/OpenActionItemViewModel.cs index b1722fe..491c93b 100644 --- a/Fab2ApprovalSystem/ViewModels/OpenActionItemViewModel.cs +++ b/Fab2ApprovalSystem/ViewModels/OpenActionItemViewModel.cs @@ -1,19 +1,16 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.ViewModels -{ - public class OpenActionItemViewModel - { - public int IssueID { get; set; } - public int DocID { get; set; } - public string DocumentType { get; set; } - public string DocumentTypeDisplay { get; set; } - public string Originator { get; set; } - public DateTime? AssignedDate { get; set; } - public DateTime? DueDate { get; set; } - public string pcrMesaID { get; set; } = string.Empty; - } -} +namespace Fab2ApprovalSystem.ViewModels; + +public class OpenActionItemViewModel { + + public int IssueID { get; set; } + public int DocID { get; set; } + public string DocumentType { get; set; } + public string DocumentTypeDisplay { get; set; } + public string Originator { get; set; } + public DateTime? AssignedDate { get; set; } + public DateTime? DueDate { get; set; } + public string pcrMesaID { get; set; } = string.Empty; + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/PdfViewModel.cs b/Fab2ApprovalSystem/ViewModels/PdfViewModel.cs index ce4d608..127a880 100644 --- a/Fab2ApprovalSystem/ViewModels/PdfViewModel.cs +++ b/Fab2ApprovalSystem/ViewModels/PdfViewModel.cs @@ -1,230 +1,193 @@ -using Fab2ApprovalSystem.Models; -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Web; -namespace Fab2ApprovalSystem.ViewModels -{ - public class ECNPdf - { - public string Title { get; set; } - public int ECNNumber { get; set; } +using Fab2ApprovalSystem.Models; - [DataType(DataType.Date)] - public DateTime IssueDate { get; set; } +namespace Fab2ApprovalSystem.ViewModels; +public class ECNPdf { - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? SubmitedDate { get; set; } + public string Title { get; set; } + public int ECNNumber { get; set; } - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? CloseDate { get; set; } + [DataType(DataType.Date)] + public DateTime IssueDate { get; set; } - public int OriginatorID { get; set; } - public string OriginatorName { get; set; } - // important!!make sure the id of the control matches the name of the field in the model it is being binded to, - // in order to get the selected items from the control - + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? SubmitedDate { get; set; } - //public List AffectedModules { get; set; } - public List Approvalog { get; set; } - public List Attachments { get; set; } + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? CloseDate { get; set; } + public int OriginatorID { get; set; } + public string OriginatorName { get; set; } + // important!!make sure the id of the control matches the name of the field in the model it is being binded to, + // in order to get the selected items from the control - public string AffectedModules { get; set; } - public string AffectedDepartments { get; set; } - //public string Attachments { get; set; } + public List Approvalog { get; set; } + public List Attachments { get; set; } + public string AffectedModules { get; set; } + public string AffectedDepartments { get; set; } + public string AffectedAreas { get; set; } + public string AffectedTechnologies { get; set; } + public string TrainingBy { get; set; } + public string AcknowledgementBy { get; set; } + public bool IsECN { get; set; } + public bool IsTECN { get; set; } + public bool IsEmergencyTECN { get; set; } - public string AffectedAreas { get; set; } - public string AffectedTechnologies { get; set; } - public string TrainingBy { get; set; } - public string AcknowledgementBy { get; set; } + [DataType(DataType.Date)] + //[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? ExpirationDate { get; set; } + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? ExtensionDate { get; set; } - public bool IsECN { get; set; } - public bool IsTECN { get; set; } - public bool IsEmergencyTECN { get; set; } - - [DataType(DataType.Date)] - //[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? ExpirationDate { get; set; } - - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? ExtensionDate { get; set; } - - [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] - public DateTime? CancellationDate { get; set; } - - public bool AcknowledgementRequired { get; set; } - public bool TrainingRequired { get; set; } - public int? AreaID { get; set; } - public int? TechnologyID { get; set; } - - public bool PCRBRequired { get; set; } - public string PCRBNumber { get; set; } - public bool TestProgramChangeRequired { get; set; } - public bool MetrologyChangeRequired { get; set; } - public bool SPCChangeRequired { get; set; } - public bool NewPartFlowRequired { get; set; } - public bool SPNChangeRequired { get; set; } - public string ImplementationDetails { get; set; } - public int ImpactOnEnvironment { get; set; } - public string ImpactOnEnvironmentDescription { get; set; } - public int ImpactOnCapacity { get; set; } - public string ImpactOnCapacityDescription { get; set; } - public bool IsMA { get; set; } - public bool IsRH { get; set; } - public bool IsAU { get; set; } - public bool IsIndustrial { get; set; } - public int MaterialConsumptionChangeRequired { get; set; } - public string MaterialConsumptionChangeDescription { get; set; } - public string ReasonForChange { get; set; } - public string DescriptionOfChange { get; set; } - public bool NotAFlowChange { get; set; } - public bool AttachECN_TECNToLots { get; set; } - public bool SPNFlowChangeAtSingleStep { get; set; } - public bool SPNFlowChangeAtMultipleSteps { get; set; } - public byte CurrentStep { get; set; } - public string Area { get; set; } - public string Technology { get; set; } - public DateTime? CancellationApprovalDate { get; set; } - public int? ConvertedToNumber { get; set; } - public int? ConvertedFromNumber { get; set; } - public int WorkFlowNumber { get; set; } - - public bool FIChangeRequired { get; set; } - public string NumberOfLotsAffected { get; set; } - public string RecipeChange { get; set; } - public string AffectedProductFamilies { get; set; } - - public bool IsDocEC { get; set; } - - public ECNPdf() - { - - Approvalog = new List(); - Attachments = new List(); - } - + [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] + public DateTime? CancellationDate { get; set; } + public bool AcknowledgementRequired { get; set; } + public bool TrainingRequired { get; set; } + public int? AreaID { get; set; } + public int? TechnologyID { get; set; } + public bool PCRBRequired { get; set; } + public string PCRBNumber { get; set; } + public bool TestProgramChangeRequired { get; set; } + public bool MetrologyChangeRequired { get; set; } + public bool SPCChangeRequired { get; set; } + public bool NewPartFlowRequired { get; set; } + public bool SPNChangeRequired { get; set; } + public string ImplementationDetails { get; set; } + public int ImpactOnEnvironment { get; set; } + public string ImpactOnEnvironmentDescription { get; set; } + public int ImpactOnCapacity { get; set; } + public string ImpactOnCapacityDescription { get; set; } + public bool IsMA { get; set; } + public bool IsRH { get; set; } + public bool IsAU { get; set; } + public bool IsIndustrial { get; set; } + public int MaterialConsumptionChangeRequired { get; set; } + public string MaterialConsumptionChangeDescription { get; set; } + public string ReasonForChange { get; set; } + public string DescriptionOfChange { get; set; } + public bool NotAFlowChange { get; set; } + public bool AttachECN_TECNToLots { get; set; } + public bool SPNFlowChangeAtSingleStep { get; set; } + public bool SPNFlowChangeAtMultipleSteps { get; set; } + public byte CurrentStep { get; set; } + public string Area { get; set; } + public string Technology { get; set; } + public DateTime? CancellationApprovalDate { get; set; } + public int? ConvertedToNumber { get; set; } + public int? ConvertedFromNumber { get; set; } + public int WorkFlowNumber { get; set; } + public bool FIChangeRequired { get; set; } + public string NumberOfLotsAffected { get; set; } + public string RecipeChange { get; set; } + public string AffectedProductFamilies { get; set; } + public bool IsDocEC { get; set; } + public ECNPdf() { + Approvalog = new List(); + Attachments = new List(); } +} - /// - /// - /// - public class ECNApprovalLog - { - public string FullName { get; set; } - public string Operation { get; set; } - public string SubRole { get; set; } - public string OperationTime { get; set; } +public class ECNApprovalLog { + public string FullName { get; set; } + public string Operation { get; set; } + public string SubRole { get; set; } + public string OperationTime { get; set; } + +} + +public class WorkRequestPdf { + + public int ID { get; set; } + public int SWRNumber { get; set; } + public bool RecordLockIndicator { get; set; } + public int RecordLockedBy { get; set; } + public string RecordLockByName { get; set; } + public byte CurrentStep { get; set; } + public int Revision { get; set; } + public bool IsCurrentRevision { get; set; } + public int OriginatorID { get; set; } + public DateTime? OriginatedDate { get; set; } + public DateTime? SubmitedDate { get; set; } + public DateTime? CloseDate { get; set; } + public int Status { get; set; } + public bool IsITAR { get; set; } + public string Title { get; set; } + public char? LotType { get; set; } + public string PCRBNumber { get; set; } + public int? EngLotStartRequired { get; set; } + public int? LotTypeConversion { get; set; } + public int? QualLot { get; set; } + public string PurposeOfRequest { get; set; } + public DateTime? PlannedLotStartDate { get; set; } + public DateTime? PlannedScheduledCloseDate { get; set; } + public string ChargeDepartment { get; set; } + public string AllocationToUse { get; set; } + public int? PredictedCyleTime { get; set; } + public string ChargesForRawWafers { get; set; } + public string DeptChargedForRawWafers { get; set; } + public string DeptOwnerForRawWafers { get; set; } + public string FabCost { get; set; } + public string DeptChargedForFabCost { get; set; } + public string SignOn { get; set; } + public string Verb1 { get; set; } + public DateTime? EstimatedBinCLoseDate { get; set; } + public int? StartQty { get; set; } + public int? TotalQty { get; set; } + public string Verb2 { get; set; } + public string WIPArea { get; set; } + public DateTime? LotStartDate { get; set; } + public string LotNumber { get; set; } + public string WIPPartNumber { get; set; } + public string PartDescription { get; set; } + public string DefaultEPISiliconPartNumber { get; set; } + public string ProcessFlow { get; set; } + public string EmployeeID { get; set; } + public string VerbComment { get; set; } + public int? RecordSiliconLotInSPNTapeTagTotrav { get; set; } + public string SiliconLotNoCassette1 { get; set; } + public bool SiliconOnHand { get; set; } + public bool ReticleOnHand { get; set; } + public bool SPNTransferOnHand { get; set; } + public bool ProbeCardOnHand { get; set; } + public bool ProbeRecipeOnHand { get; set; } + public bool ProcessChangeDetailsOnHand { get; set; } + public string LotStartCheckListComments { get; set; } + public List LTHoldStep { get; set; } + public string AffectedDepartments { get; set; } + public string AffectedModules { get; set; } + public string OriginatorName { get; set; } + public string RevisionComments { get; set; } + public List LTMaterial { get; set; } + public WorkRequestPdf() { + LTHoldStep = new List(); + LTMaterial = new List(); + } +} + +public class LotTravelerPdf { + + public int SWRNumber { get; set; } + public string LotNumber { get; set; } + public string Title { get; set; } // + public string Status { get; set; } // + public string Originator { get; set; } // + public string WIPPartNumber { get; set; } + public string PartDescription { get; set; } + public string BaseFlow { set; get; } + public bool IsITAR { set; get; } + public DateTime? LastUpdate { get; set; } + public string LastUpdatedBy { get; set; } + public string PurposeOfRequest { get; set; } + public int LotTravCurrentRevision { get; set; } + public List Tasklist { get; set; } + public LotTravelerPdf() { + Tasklist = new List(); } - /// - /// - /// - public class WorkRequestPdf - { - public int ID{ get; set; } - public int SWRNumber{ get; set; } - public bool RecordLockIndicator{ get; set; } - public int RecordLockedBy { get; set; } - public string RecordLockByName { get; set; } - public byte CurrentStep { get; set; } - public int Revision{ get; set; } - public bool IsCurrentRevision { get; set; } - public int OriginatorID{ get; set; } - public DateTime? OriginatedDate { get; set; } - public DateTime? SubmitedDate { get; set; } - public DateTime? CloseDate { get; set; } - public int Status{ get; set; } - public bool IsITAR{ get; set; } - public string Title{ get; set; } - public char? LotType{ get; set; } - public string PCRBNumber{ get; set; } - public int? EngLotStartRequired{ get; set; } - public int? LotTypeConversion{ get; set; } - public int? QualLot{ get; set; } - public string PurposeOfRequest{ get; set; } - public DateTime? PlannedLotStartDate{ get; set; } - public DateTime? PlannedScheduledCloseDate{ get; set; } - public string ChargeDepartment{ get; set; } - public string AllocationToUse{ get; set; } - public int? PredictedCyleTime{ get; set; } - public string ChargesForRawWafers{ get; set; } - public string DeptChargedForRawWafers{ get; set; } - public string DeptOwnerForRawWafers{ get; set; } - public string FabCost{ get; set; } - public string DeptChargedForFabCost{ get; set; } - public string SignOn{ get; set; } - public string Verb1{ get; set; } - public DateTime? EstimatedBinCLoseDate { get; set; } - public int? StartQty{ get; set; } - public int? TotalQty { get; set; } - public string Verb2{ get; set; } - public string WIPArea{ get; set; } - public DateTime? LotStartDate{ get; set; } - public string LotNumber { get; set; } - public string WIPPartNumber{ get; set; } - public string PartDescription { get; set; } - public string DefaultEPISiliconPartNumber { get; set; } - public string ProcessFlow{ get; set; } - public string EmployeeID{ get; set; } - public string VerbComment{ get; set; } - public int? RecordSiliconLotInSPNTapeTagTotrav { get;set;} - public string SiliconLotNoCassette1 { get; set; } - public bool SiliconOnHand { get; set; } - public bool ReticleOnHand { get; set; } - public bool SPNTransferOnHand { get; set; } - public bool ProbeCardOnHand { get; set; } - public bool ProbeRecipeOnHand { get; set; } - public bool ProcessChangeDetailsOnHand { get; set; } - - public string LotStartCheckListComments { get; set; } - - public List LTHoldStep { get; set; } - public string AffectedDepartments { get; set; } - public string AffectedModules { get; set; } - public string OriginatorName { get; set; } - public string RevisionComments { get; set; } - public List LTMaterial { get; set; } - - public WorkRequestPdf() - { - LTHoldStep = new List(); - LTMaterial = new List(); - } - } - - /// - /// - /// - public class LotTravelerPdf - { - - public int SWRNumber { get; set; } - public string LotNumber { get; set; } - public string Title { get; set; } // - public string Status { get; set; } // - public string Originator { get; set; } // - public string WIPPartNumber { get; set; } - public string PartDescription { get; set; } - public string BaseFlow { set; get; } - public bool IsITAR { set; get; } - public DateTime? LastUpdate { get; set; } - public string LastUpdatedBy { get; set; } - public string PurposeOfRequest { get; set; } - public int LotTravCurrentRevision { get; set; } - public List Tasklist { get; set; } - - public LotTravelerPdf() - { - Tasklist = new List(); - } - - } - - } \ No newline at end of file diff --git a/Fab2ApprovalSystem/ViewModels/ReportsViewModels.cs b/Fab2ApprovalSystem/ViewModels/ReportsViewModels.cs index 93addc2..46bb933 100644 --- a/Fab2ApprovalSystem/ViewModels/ReportsViewModels.cs +++ b/Fab2ApprovalSystem/ViewModels/ReportsViewModels.cs @@ -1,32 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using System.Collections.Generic; -namespace Fab2ApprovalSystem.ViewModels +namespace Fab2ApprovalSystem.ViewModels; + +public enum ParameterControlTypes { + Textbox, DatePicker, Dropdown, Multiselect +} + +public class ReportParameterViewModel // => System.Web.Mvc.SelectListItem { - public enum ParameterControlTypes - { - Textbox, DatePicker, Dropdown, Multiselect - } - public class ReportParameterViewModel - { - public bool Visible { get; set; } - public string Prompt { get; set; } - public string Name { get; set; } - public string HtmlID { get; set; } - public string DefaultValue { get; set; } - public ParameterControlTypes ControlType { get; set; } - public IEnumerable SelectList { get; set; } - } - public class ReportViewModel - { - public String ReportID { get; set; } - public String ReportName { get; set; } - public String Description { get; set; } - public String DocType { get; set; } + public bool Visible { get; set; } + public string Prompt { get; set; } + public string Name { get; set; } + public string HtmlID { get; set; } + public string DefaultValue { get; set; } + public ParameterControlTypes ControlType { get; set; } + public IEnumerable SelectList { get; set; } + +} + +public class ReportViewModel { + + public string ReportID { get; set; } + public string ReportName { get; set; } + public string Description { get; set; } + public string DocType { get; set; } + public IEnumerable> Parameters { get; set; } - public IEnumerable Parameters { get; set; } - } } \ No newline at end of file diff --git a/Fab2ApprovalTests/.editorconfig b/Fab2ApprovalTests/.editorconfig new file mode 100644 index 0000000..730dc4d --- /dev/null +++ b/Fab2ApprovalTests/.editorconfig @@ -0,0 +1,379 @@ +[*.md] +end_of_line = crlf +file_header_template = unset +indent_size = 2 +indent_style = space +insert_final_newline = false +root = true +tab_width = 2 +[*.csproj] +end_of_line = crlf +file_header_template = unset +indent_size = 2 +indent_style = space +insert_final_newline = false +root = true +tab_width = 2 +[*.cs] +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true +csharp_new_line_before_catch = false +csharp_new_line_before_else = false +csharp_new_line_before_finally = false +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = none +csharp_new_line_between_query_expression_clauses = true +csharp_prefer_braces = false +csharp_prefer_qualified_reference = true:error +csharp_prefer_simple_default_expression = true:warning +csharp_prefer_simple_using_statement = true:warning +csharp_prefer_static_local_function = true:warning +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = false +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true +csharp_style_allow_embedded_statements_on_same_line_experimental = true +csharp_style_conditional_delegate_call = true +csharp_style_deconstructed_variable_declaration = false +csharp_style_expression_bodied_accessors = when_on_single_line:warning +csharp_style_expression_bodied_constructors = when_on_single_line:warning +csharp_style_expression_bodied_indexers = when_on_single_line:warning +csharp_style_expression_bodied_lambdas = when_on_single_line:warning +csharp_style_expression_bodied_local_functions = when_on_single_line:warning +csharp_style_expression_bodied_methods = when_on_single_line:warning +csharp_style_expression_bodied_operators = when_on_single_line:warning +csharp_style_expression_bodied_properties = when_on_single_line:warning +csharp_style_implicit_object_creation_when_type_is_apparent = true:warning +csharp_style_inlined_variable_declaration = false +csharp_style_namespace_declarations = file_scoped:warning +csharp_style_pattern_local_over_anonymous_function = true:warning +csharp_style_pattern_matching_over_as_with_null_check = true:warning +csharp_style_pattern_matching_over_is_with_cast_check = true:warning +csharp_style_prefer_index_operator = true:warning +csharp_style_prefer_not_pattern = true:warning +csharp_style_prefer_null_check_over_type_check = true +csharp_style_prefer_pattern_matching = true:warning +csharp_style_prefer_range_operator = true:warning +csharp_style_prefer_switch_expression = true:warning +csharp_style_throw_expression = true +csharp_style_unused_value_assignment_preference = discard_variable:warning +csharp_style_unused_value_expression_statement_preference = discard_variable:warning +csharp_style_var_elsewhere = false:warning +csharp_style_var_for_built_in_types = false:warning +csharp_style_var_when_type_is_apparent = false:warning +csharp_using_directive_placement = outside_namespace +dotnet_analyzer_diagnostic.category-Design.severity = error +dotnet_analyzer_diagnostic.category-Documentation.severity = error +dotnet_analyzer_diagnostic.category-Globalization.severity = none +dotnet_analyzer_diagnostic.category-Interoperability.severity = error +dotnet_analyzer_diagnostic.category-Maintainability.severity = error +dotnet_analyzer_diagnostic.category-Naming.severity = none +dotnet_analyzer_diagnostic.category-Performance.severity = none +dotnet_analyzer_diagnostic.category-Reliability.severity = error +dotnet_analyzer_diagnostic.category-Security.severity = error +dotnet_analyzer_diagnostic.category-SingleFile.severity = error +dotnet_analyzer_diagnostic.category-Style.severity = error +dotnet_analyzer_diagnostic.category-Usage.severity = error +dotnet_code_quality_unused_parameters = all +dotnet_code_quality_unused_parameters = non_public +dotnet_code_quality.CAXXXX.api_surface = private, internal +dotnet_diagnostic.CA1001.severity = error # CA1001: Types that own disposable fields should be disposable +dotnet_diagnostic.CA1051.severity = error # CA1051: Do not declare visible instance fields +dotnet_diagnostic.CA1511.severity = warning # CA1511: Use 'ArgumentException.ThrowIfNullOrEmpty' instead of explicitly throwing a new exception instance +dotnet_diagnostic.CA1513.severity = warning # Use 'ObjectDisposedException.ThrowIf' instead of explicitly throwing a new exception instance +dotnet_diagnostic.CA1825.severity = warning # CA1825: Avoid zero-length array allocations +dotnet_diagnostic.CA1829.severity = error # CA1829: Use Length/Count property instead of Count() when available +dotnet_diagnostic.CA1834.severity = warning # CA1834: Consider using 'StringBuilder.Append(char)' when applicable +dotnet_diagnostic.CA1860.severity = error # CA1860: Prefer comparing 'Count' to 0 rather than using 'Any()', both for clarity and for performance +dotnet_diagnostic.CA1862.severity = warning # CA1862: Prefer using 'string.Equals(string, StringComparison)' to perform a case-insensitive comparison, but keep in mind that this might cause subtle changes in behavior, so make sure to conduct thorough testing after applying the suggestion, or if culturally sensitive comparison is not required, consider using 'StringComparison.OrdinalIgnoreCase' +dotnet_diagnostic.CA1869.severity = none # CA1869: Avoid creating a new 'JsonSerializerOptions' instance for every serialization operation. Cache and reuse instances instead. +dotnet_diagnostic.CA2201.severity = none # CA2201: Exception type System.NullReferenceException is reserved by the runtime +dotnet_diagnostic.CA2254.severity = none # CA2254: The logging message template should not vary between calls to 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])' +dotnet_diagnostic.IDE0001.severity = warning # IDE0001: Simplify name +dotnet_diagnostic.IDE0002.severity = warning # Simplify (member access) - System.Version.Equals("1", "2"); Version.Equals("1", "2"); +dotnet_diagnostic.IDE0004.severity = warning # IDE0004: Cast is redundant. +dotnet_diagnostic.IDE0005.severity = error # Using directive is unnecessary +dotnet_diagnostic.IDE0010.severity = none # Add missing cases to switch statement (IDE0010) +dotnet_diagnostic.IDE0028.severity = error # IDE0028: Collection initialization can be simplified +dotnet_diagnostic.IDE0031.severity = warning # Use null propagation (IDE0031) +dotnet_diagnostic.IDE0047.severity = warning # IDE0047: Parentheses can be removed +dotnet_diagnostic.IDE0048.severity = none # Parentheses preferences (IDE0047 and IDE0048) +dotnet_diagnostic.IDE0049.severity = warning # Use language keywords instead of framework type names for type references (IDE0049) +dotnet_diagnostic.IDE0051.severity = error # Private member '' is unused [, ] +dotnet_diagnostic.IDE0058.severity = error # IDE0058: Expression value is never used +dotnet_diagnostic.IDE0060.severity = error # IDE0060: Remove unused parameter +dotnet_diagnostic.IDE0074.severity = warning # IDE0074: Use compound assignment +dotnet_diagnostic.IDE0130.severity = none # Namespace does not match folder structure (IDE0130) +dotnet_diagnostic.IDE0270.severity = warning # IDE0270: Null check can be simplified +dotnet_diagnostic.IDE0290.severity = none # Use primary constructor [Distance]csharp(IDE0290) +dotnet_diagnostic.IDE0300.severity = error # IDE0300: Collection initialization can be simplified +dotnet_diagnostic.IDE0301.severity = error #IDE0301: Collection initialization can be simplified +dotnet_diagnostic.IDE0305.severity = none # IDE0305: Collection initialization can be simplified +dotnet_diagnostic.IDE2000.severity = error # IDE2000: Allow multiple blank lines +dotnet_naming_rule.abstract_method_should_be_pascal_case.severity = warning +dotnet_naming_rule.abstract_method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.abstract_method_should_be_pascal_case.symbols = abstract_method +dotnet_naming_rule.class_should_be_pascal_case.severity = warning +dotnet_naming_rule.class_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.class_should_be_pascal_case.symbols = class +dotnet_naming_rule.delegate_should_be_pascal_case.severity = warning +dotnet_naming_rule.delegate_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.delegate_should_be_pascal_case.symbols = delegate +dotnet_naming_rule.enum_should_be_pascal_case.severity = warning +dotnet_naming_rule.enum_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.enum_should_be_pascal_case.symbols = enum +dotnet_naming_rule.event_should_be_pascal_case.severity = warning +dotnet_naming_rule.event_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.event_should_be_pascal_case.symbols = event +dotnet_naming_rule.interface_should_be_begins_with_i.severity = warning +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.method_should_be_pascal_case.severity = warning +dotnet_naming_rule.method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.method_should_be_pascal_case.symbols = method +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = warning +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.private_method_should_be_pascal_case.severity = warning +dotnet_naming_rule.private_method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.private_method_should_be_pascal_case.symbols = private_method +dotnet_naming_rule.private_or_internal_field_should_be_private_of_internal_field.severity = warning +dotnet_naming_rule.private_or_internal_field_should_be_private_of_internal_field.style = private_of_internal_field +dotnet_naming_rule.private_or_internal_field_should_be_private_of_internal_field.symbols = private_or_internal_field +dotnet_naming_rule.private_or_internal_static_field_should_be_private_of_internal_field.severity = warning +dotnet_naming_rule.private_or_internal_static_field_should_be_private_of_internal_field.style = private_of_internal_field +dotnet_naming_rule.private_or_internal_static_field_should_be_private_of_internal_field.symbols = private_or_internal_static_field +dotnet_naming_rule.property_should_be_pascal_case.severity = warning +dotnet_naming_rule.property_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.property_should_be_pascal_case.symbols = property +dotnet_naming_rule.public_or_protected_field_should_be_private_of_internal_field.severity = warning +dotnet_naming_rule.public_or_protected_field_should_be_private_of_internal_field.style = private_of_internal_field +dotnet_naming_rule.public_or_protected_field_should_be_private_of_internal_field.symbols = public_or_protected_field +dotnet_naming_rule.static_field_should_be_pascal_case.severity = warning +dotnet_naming_rule.static_field_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.static_field_should_be_pascal_case.symbols = static_field +dotnet_naming_rule.static_method_should_be_pascal_case.severity = warning +dotnet_naming_rule.static_method_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.static_method_should_be_pascal_case.symbols = static_method +dotnet_naming_rule.struct_should_be_pascal_case.severity = warning +dotnet_naming_rule.struct_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.struct_should_be_pascal_case.symbols = struct +dotnet_naming_rule.types_should_be_pascal_case.severity = warning +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_style.begins_with_i.capitalization = pascal_case +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.private_of_internal_field.capitalization = pascal_case +dotnet_naming_style.private_of_internal_field.required_prefix = _ +dotnet_naming_style.private_of_internal_field.required_suffix = +dotnet_naming_style.private_of_internal_field.word_separator = +dotnet_naming_symbols.abstract_method.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.abstract_method.applicable_kinds = method +dotnet_naming_symbols.abstract_method.required_modifiers = abstract +dotnet_naming_symbols.class.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.class.applicable_kinds = class +dotnet_naming_symbols.class.required_modifiers = +dotnet_naming_symbols.delegate.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.delegate.applicable_kinds = delegate +dotnet_naming_symbols.delegate.required_modifiers = +dotnet_naming_symbols.enum.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.enum.applicable_kinds = enum +dotnet_naming_symbols.enum.required_modifiers = +dotnet_naming_symbols.event.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.event.applicable_kinds = event +dotnet_naming_symbols.event.required_modifiers = +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.required_modifiers = +dotnet_naming_symbols.method.applicable_accessibilities = public +dotnet_naming_symbols.method.applicable_kinds = method +dotnet_naming_symbols.method.required_modifiers = +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.required_modifiers = +dotnet_naming_symbols.private_method.applicable_accessibilities = private +dotnet_naming_symbols.private_method.applicable_kinds = method +dotnet_naming_symbols.private_method.required_modifiers = +dotnet_naming_symbols.private_or_internal_field.applicable_accessibilities = internal, private, private_protected +dotnet_naming_symbols.private_or_internal_field.applicable_kinds = field +dotnet_naming_symbols.private_or_internal_field.required_modifiers = +dotnet_naming_symbols.private_or_internal_static_field.applicable_accessibilities = internal, private, private_protected +dotnet_naming_symbols.private_or_internal_static_field.applicable_kinds = field +dotnet_naming_symbols.private_or_internal_static_field.required_modifiers = static +dotnet_naming_symbols.property.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.property.applicable_kinds = property +dotnet_naming_symbols.property.required_modifiers = +dotnet_naming_symbols.public_or_protected_field.applicable_accessibilities = public, protected +dotnet_naming_symbols.public_or_protected_field.applicable_kinds = field +dotnet_naming_symbols.public_or_protected_field.required_modifiers = +dotnet_naming_symbols.static_field.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.static_field.applicable_kinds = field +dotnet_naming_symbols.static_field.required_modifiers = static +dotnet_naming_symbols.static_method.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.static_method.applicable_kinds = method +dotnet_naming_symbols.static_method.required_modifiers = static +dotnet_naming_symbols.struct.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.struct.applicable_kinds = struct +dotnet_naming_symbols.struct.required_modifiers = +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.required_modifiers = +dotnet_remove_unnecessary_suppression_exclusions = 0 +dotnet_separate_import_directive_groups = true +dotnet_sort_system_directives_first = true +dotnet_style_allow_multiple_blank_lines_experimental = false:warning +dotnet_style_allow_statement_immediately_after_block_experimental = true +dotnet_style_coalesce_expression = true +dotnet_style_collection_initializer = true:warning +dotnet_style_explicit_tuple_names = true:warning +dotnet_style_namespace_match_folder = true +dotnet_style_null_propagation = true:warning +dotnet_style_object_initializer = true:warning +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_operators = never_if_unnecessary +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity +dotnet_style_predefined_type_for_locals_parameters_members = true +dotnet_style_predefined_type_for_member_access = true:warning +dotnet_style_prefer_auto_properties = true:warning +dotnet_style_prefer_compound_assignment = true:warning +dotnet_style_prefer_conditional_expression_over_assignment = false +dotnet_style_prefer_conditional_expression_over_return = false +dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning +dotnet_style_prefer_inferred_tuple_names = true:warning +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning +dotnet_style_prefer_simplified_boolean_expressions = true:warning +dotnet_style_prefer_simplified_interpolation = true +dotnet_style_qualification_for_event = false:error +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_method = false:error +dotnet_style_qualification_for_property = false:error +dotnet_style_readonly_field = true:warning +dotnet_style_require_accessibility_modifiers = for_non_interface_members +end_of_line = crlf +file_header_template = unset +indent_size = 4 +indent_style = space +insert_final_newline = false +root = true +tab_width = 4 +# https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1822 +# https://github.com/dotnet/aspnetcore/blob/main/.editorconfig +# https://github.com/dotnet/project-system/blob/main/.editorconfig + +# Question +csharp_prefer_simple_using_statement = false # Question +csharp_style_expression_bodied_constructors = when_on_single_line:none # Question +csharp_style_expression_bodied_properties = true # Question +csharp_style_implicit_object_creation_when_type_is_apparent = true:warning # Question +csharp_style_pattern_matching_over_as_with_null_check = false # Question +csharp_style_prefer_pattern_matching = false # Question +csharp_style_prefer_range_operator = false # Question +csharp_style_prefer_switch_expression = false # Question +csharp_style_unused_value_assignment_preference = unused_local_variable # Question +csharp_style_unused_value_expression_statement_preference = false # Question +csharp_style_var_elsewhere = false:none # Question +csharp_style_var_for_built_in_types = false:none # Question +csharp_style_var_when_type_is_apparent = false:warning # Question +dotnet_diagnostic.CA1001.severity = none # Question - Types that own disposable fields should be disposable +dotnet_diagnostic.CA1051.severity = none # Question - Do not declare visible instance fields +dotnet_diagnostic.CA1416.severity = none # Question - This call site is reachable on all platforms. +dotnet_diagnostic.CA1510.severity = none # Question - Use +dotnet_diagnostic.CA1834.severity = none # CA1834: Consider using 'StringBuilder.Append(char)' when applicable +dotnet_diagnostic.CA1860.severity = none # Question - Avoid using +dotnet_diagnostic.CA1862.severity = none # Question - Prefer using +dotnet_diagnostic.CA2208.severity = none # Question - Instantiate argument exceptions correctly +dotnet_diagnostic.CA2211.severity = none # Question - Non-constant fields should not be visible +dotnet_diagnostic.CA2249.severity = none # Question - Use +dotnet_diagnostic.CA2253.severity = none # Question - Named placeholders should not be numeric values +dotnet_diagnostic.CS0103.severity = none # Question - The name +dotnet_diagnostic.CS0168.severity = none # Question - The variable +dotnet_diagnostic.CS0219.severity = none # Question - The variable +dotnet_diagnostic.CS0612.severity = none # Question - is obsolete +dotnet_diagnostic.CS0618.severity = none # Question - Compiler Warning (level 2) +dotnet_diagnostic.CS0659.severity = none # Question - Compiler Warning (level 3) +dotnet_diagnostic.CS8019.severity = warning # Question - Unnecessary using directive. +dotnet_diagnostic.CS8600.severity = none # Question - Converting null literal or possible null value to non-nullable type +dotnet_diagnostic.CS8602.severity = none # Question - Dereference of a possibly null reference. +dotnet_diagnostic.CS8603.severity = none # Question - Possible null reference return +dotnet_diagnostic.CS8604.severity = none # Question - Possible null reference argument for parameter. +dotnet_diagnostic.CS8618.severity = none # Question - Non-nullable variable must contain a non-null value when exiting constructor +dotnet_diagnostic.CS8625.severity = none # Question - Cannot convert null literal to non-nullable reference type. +dotnet_diagnostic.CS8629.severity = none # Question - Nullable value type may be null +dotnet_diagnostic.CS8765.severity = none # Question - Nullability of type of parameter +dotnet_diagnostic.IDE0005.severity = none # Question - Remove unnecessary using directives +dotnet_diagnostic.IDE0008.severity = warning # Question - Use explicit type instead of +dotnet_diagnostic.IDE0017.severity = none # Question - Object initialization can be simplified +dotnet_diagnostic.IDE0019.severity = none # Question - Use pattern matching +dotnet_diagnostic.IDE0021.severity = none # Question - Use expression body for constructor +dotnet_diagnostic.IDE0022.severity = none # Question - Use expression body for method +dotnet_diagnostic.IDE0025.severity = none # Question - Use expression body for property +dotnet_diagnostic.IDE0027.severity = none # Question - Use expression body for accessor +dotnet_diagnostic.IDE0028.severity = none # Question - Use collection initializers or expressions +dotnet_diagnostic.IDE0031.severity = none # Question - Null check can be simplified +dotnet_diagnostic.IDE0032.severity = none # Question - Use auto property +dotnet_diagnostic.IDE0037.severity = none # Question - Member name can be simplified +dotnet_diagnostic.IDE0041.severity = none # Question - Null check can be simplified +dotnet_diagnostic.IDE0047.severity = none # Question - Parentheses preferences +dotnet_diagnostic.IDE0049.severity = warning # Question - Name can be simplified +dotnet_diagnostic.IDE0051.severity = none # Question - Remove unused private member +dotnet_diagnostic.IDE0053.severity = none # Question - Use expression body for lambdas +dotnet_diagnostic.IDE0054.severity = none # Question - Use compound assignment +dotnet_diagnostic.IDE0055.severity = none # Question - Formatting rule +dotnet_diagnostic.IDE0057.severity = none # Question - Substring can be simplified +dotnet_diagnostic.IDE0058.severity = none # Question - Remove unnecessary expression value +dotnet_diagnostic.IDE0059.severity = none # Question - Unnecessary assignment of a value to +dotnet_diagnostic.IDE0060.severity = none # Question - Remove unused parameter +dotnet_diagnostic.IDE0063.severity = none # Question - Use simple +dotnet_diagnostic.IDE0065.severity = none # Question - +dotnet_diagnostic.IDE0066.severity = none # Question - Use +dotnet_diagnostic.IDE0078.severity = none # Question - Use pattern matching (may change code meaning) +dotnet_diagnostic.IDE0090.severity = warning # Question - Simplify new expression +dotnet_diagnostic.IDE0160.severity = warning # Question - Use block-scoped namespace +dotnet_diagnostic.IDE0161.severity = warning # Question - Namespace declaration preferences +dotnet_diagnostic.IDE0270.severity = none # Question - Null check can be simplified +dotnet_diagnostic.IDE0300.severity = none # Question - Collection initialization can be simplified +dotnet_diagnostic.IDE1006.severity = none # Question - Use collection expression for builder dotnet_style_prefer_collection_expression +dotnet_style_null_propagation = false # Question +dotnet_style_object_initializer = false # Question +dotnet_style_prefer_auto_properties = false # Question +dotnet_style_prefer_is_null_check_over_reference_equality_method = false # Question +dotnet_style_prefer_inferred_anonymous_type_member_names = false:warning # Question \ No newline at end of file diff --git a/Fab2ApprovalTests/.vscode/format-report.json b/Fab2ApprovalTests/.vscode/format-report.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/Fab2ApprovalTests/.vscode/format-report.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/Fab2ApprovalTests/.vscode/launch.json b/Fab2ApprovalTests/.vscode/launch.json new file mode 100644 index 0000000..aff00e5 --- /dev/null +++ b/Fab2ApprovalTests/.vscode/launch.json @@ -0,0 +1,30 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + "program": "${workspaceFolder}/bin/Debug/net8.0/win-x64/FabApprovalWorkerServiceTests.dll", + "args": [], + "cwd": "${workspaceFolder}", + "console": "integratedTerminal", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + }, + { + "type": "node", + "request": "launch", + "name": "node Launch Current Opened File", + "program": "${file}" + } + ] +} \ No newline at end of file diff --git a/Fab2ApprovalTests/.vscode/mklink.md b/Fab2ApprovalTests/.vscode/mklink.md new file mode 100644 index 0000000..6e220d3 --- /dev/null +++ b/Fab2ApprovalTests/.vscode/mklink.md @@ -0,0 +1,6 @@ +# mklink + +```bash 1731711780354 = 638673085803540000 = Fri Nov 15 2024 16:02:59 GMT-0700 (Mountain Standard Time) +# mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalTests\.vscode\.UserSecrets" "C:\Users\phares\AppData\Roaming\Microsoft\UserSecrets\3942d1fb-d585-40ae-8985-d276d1b94b77" +mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalTests\.vscode\.UserSecrets" "C:\Users\phares\AppData\Roaming\Microsoft\UserSecrets\f2da5035-aba9-4676-9f8d-d6689f84663d" +``` diff --git a/Fab2ApprovalTests/.vscode/settings.json b/Fab2ApprovalTests/.vscode/settings.json new file mode 100644 index 0000000..f05d843 --- /dev/null +++ b/Fab2ApprovalTests/.vscode/settings.json @@ -0,0 +1,424 @@ +{ + "[markdown]": { + "editor.wordWrap": "off" + }, + "files.exclude": { + "**/.git": false, + "**/node_modules": true + }, + "files.watcherExclude": { + "**/node_modules": true + }, + "cSpell.words": [ + "abutton", + "accessibilities", + "accodingly", + "acknowledgmentby", + "Acks", + "actionsheet", + "Additonal", + "Addtional", + "againm", + "agendaview", + "Antlr", + "Appover", + "Appprrovers", + "Approvalog", + "Aprovers", + "Aproverslist", + "asax", + "aspnetmvc", + "Assignedto", + "Atachments", + "Attachemnt", + "Attachemnts", + "Attchment", + "auditee", + "Auditee", + "Auditees", + "automaically", + "Autthorized", + "beacuase", + "beforeunload", + "Belguim", + "bfound", + "bgcolor", + "Bies", + "binded", + "blackbackground", + "blackhover", + "blackpressed", + "blueenergy", + "blueopal", + "buttongroup", + "BYMRB", + "bytesgot", + "CAID", + "casection", + "CAXXXX", + "CCPCR", + "CCPCRB", + "cellspacing", + "Cheeso's", + "chkbx", + "Clib", + "colorpicker", + "columnmenu", + "columnsreorder", + "columnsresize", + "comming", + "Containmen", + "Copmments", + "correctiv", + "Correctivet", + "Creat", + "currentd", + "Cyle", + "dadada", + "darkbluehover", + "darkbluepressed", + "darkred", + "datafields", + "datasource", + "dataviz", + "datepicker", + "datetimepicker", + "dayview", + "Deletet", + "Delgation", + "DENITED", + "Deparmtent", + "departmentids", + "Descirption", + "devprog", + "dfeffc", + "Disp", + "Dispo", + "Dispoitio", + "Dispos", + "Dispositon", + "Dispostion", + "Dispostions", + "dispotypevalidation", + "Docbase", + "Documentum", + "Documetum", + "dont", + "downlaoded", + "draganddrop", + "dragcancel", + "dropdownlist", + "Eamils", + "ECNPCRB", + "Ecns", + "edmx", + "EECN", + "emai", + "emailparams", + "Emergrncy", + "energyblue", + "Eran", + "Esql", + "ETECN", + "EXCELOPENXML", + "existinglocation", + "Expando", + "extrafield", + "fadc", + "fbec", + "fcfdfd", + "fdff", + "fece", + "feeebd", + "ffdc", + "ffdd", + "fieldset", + "FILIPE", + "filtermenu", + "Fldr", + "flintstone", + "FLOWLOCS", + "FMEA", + "ftplib", + "FTPSPN", + "GETDATE", + "gitea", + "globaldocudms", + "glyphicons", + "groupable", + "Guids", + "halflings", + "Hexsize", + "highcontrast", + "Hmac", + "holdsteps", + "hostspecific", + "icenium", + "IECN", + "imagebrowser", + "IMRB", + "Infineon", + "Insertd", + "inverseicons", + "IPCRB", + "ISADMIN", + "islast", + "ISNULL", + "ITAR", + "jquery", + "jqueryval", + "jqwidgets", + "jqxbuttongroup", + "jqxbuttons", + "jqxcalendar", + "jqxchart", + "jqxcheckbox", + "jqxcolorpicker", + "jqxcombobox", + "jqxcore", + "jqxdata", + "jqxdatatable", + "jqxdatetimeinput", + "jqxdocking", + "jqxdockpanel", + "jqxdragdrop", + "jqxdropdownbutton", + "jqxdropdownlist", + "jqxexpander", + "jqxgauge", + "jqxgrid", + "jqxinput", + "jqxknockout", + "jqxlistbox", + "jqxlistmenu", + "jqxmaskedinput", + "jqxmenu", + "jqxnavigationbar", + "jqxnumberinput", + "jqxpanel", + "jqxpasswordinput", + "jqxprogressbar", + "jqxradiobutton", + "jqxrangeselector", + "jqxrating", + "jqxresponse", + "jqxscrollbar", + "jqxscrollview", + "jqxslider", + "jqxsplitter", + "jqxswitchbutton", + "jqxtabs", + "jqxtooltip", + "jqxtouch", + "jqxtree", + "jqxtreegrid", + "jqxtreemap", + "jqxvalidator", + "jqxwindow", + "kendogridcustom", + "kendoui", + "labelelement", + "labelledby", + "Leanred", + "lightgray", + "linkbutton", + "Linq", + "Listdiv", + "listview", + "Lnks", + "localfilename", + "loclist", + "logis", + "logtext", + "loopmis", + "lotdispo", + "LOTDISPSITION", + "Lotfile", + "lotlist", + "lotstatusoption", + "LTRIM", + "MADUREIRA", + "mailrelay", + "MDTM", + "meego", + "meetingid", + "menubutton", + "mesafi", + "metroblack", + "metrodark", + "miliseconds", + "modalview", + "modernizr", + "Modernizr", + "monthview", + "MRBIs", + "Mrbs", + "msecs", + "multipleextended", + "Navigatable", + "nbsp", + "newbase", + "newchange", + "newdi", + "newfilename", + "newsource", + "Newtonsoft", + "notications", + "Notifcation", + "Notifyf", + "NTLM", + "Nullcc", + "numerictextbox", + "objdata", + "OCAP", + "occured", + "odata", + "oldfilename", + "OLHOLD", + "onclick", + "onmousemove", + "OPDESC", + "OPENQUERY", + "Oper", + "operationslist", + "Orginator", + "Originatorname", + "Ouellette", + "Owin", + "pageable", + "Pageable", + "panelbar", + "parentid", + "parminput", + "parms", + "Parms", + "particula", + "pasv", + "PASV", + "PATINDEX", + "PCRB", + "PCRBID", + "pcrvalues", + "pdbonly", + "Preventitive", + "preventivet", + "Prevetative", + "proces", + "Processedl", + "procs", + "productfamilies", + "progess", + "progressbar", + "qrcode", + "Quanityt", + "rangebar", + "Recep", + "Recepient", + "recieved", + "recordlock", + "remotefilename", + "reorderable", + "reportform", + "reportslist", + "reportslistdiv", + "Reqquired", + "Reqs", + "Requiest", + "Responsibles", + "RETR", + "Revisioing", + "Revisioned", + "Revison", + "rgba", + "rkotian", + "RNFR", + "RNTO", + "Roless", + "roundbg", + "RTRIM", + "SAMDB", + "scroller", + "scrollview", + "seleced", + "selectionlog", + "Selectpart", + "sess", + "Sfisharepoint", + "shinyblack", + "showpassword", + "SIGNON", + "simpleparser", + "slddrw", + "sldprt", + "sortasc", + "sortascbutton", + "sortdesc", + "sortdescbutton", + "sortremove", + "sparkline", + "splitview", + "SPNMRB", + "SPNPDB", + "SSRS", + "Sssign", + "Staus", + "stylesheet", + "Submited", + "subrole", + "subroles", + "Succefully", + "Succesfully", + "sucessfully", + "SURP", + "Swashbuckle", + "SWRN", + "tabindex", + "tabstrip", + "Tahoma", + "taskcompleted", + "Tasklist", + "Taveler", + "TECN", + "TECNs", + "TEMIRWAP", + "tempecd", + "tempimplement", + "templabel", + "tempvalue", + "TEMSA", + "timepicker", + "Tobe", + "Toplevel", + "Totrav", + "trainingby", + "Traininglist", + "traininglistdiv", + "transanction", + "Trav", + "Traveller", + "Traverler", + "TRAVLELER", + "Travler", + "TREEVIEW", + "trigerred", + "ttinclude", + "Uhandled", + "Updat", + "Uplaod", + "Upto", + "userevents", + "userids", + "userlist", + "Validatable", + "valueelement", + "Variabls", + "Verdana", + "vgrid", + "viewmodel", + "vsdoc", + "whethere", + "windowsphone", + "Winsock", + "worlflow" + ] +} \ No newline at end of file diff --git a/Fab2ApprovalTests/.vscode/tasks.json b/Fab2ApprovalTests/.vscode/tasks.json new file mode 100644 index 0000000..46ca4ab --- /dev/null +++ b/Fab2ApprovalTests/.vscode/tasks.json @@ -0,0 +1,135 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "User Secrets Init", + "command": "dotnet", + "type": "process", + "args": [ + "user-secrets", + "-p", + "${workspaceFolder}/Fab2ApprovalTests.csproj", + "init" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "User Secrets Set", + "command": "dotnet", + "type": "process", + "args": [ + "user-secrets", + "-p", + "${workspaceFolder}/Fab2ApprovalTests.csproj", + "set", + "_UserSecretsId", + "3942d1fb-d585-40ae-8985-d276d1b94b77" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "Format", + "command": "dotnet", + "type": "process", + "args": [ + "format", + "--report", + ".vscode", + "--verbosity", + "detailed", + "--severity", + "warn" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "Format-Whitespaces", + "command": "dotnet", + "type": "process", + "args": [ + "format", + "whitespace" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/Fab2ApprovalTests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "testDebug", + "command": "dotnet", + "type": "process", + "args": [ + "test", + "${workspaceFolder}/Fab2ApprovalTests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "testRelease", + "command": "dotnet", + "type": "process", + "args": [ + "test", + "${workspaceFolder}/Fab2ApprovalTests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary", + "-c", + "Release" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/Fab2ApprovalTests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/Fab2ApprovalTests.csproj" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "Publish AOT", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "-r", + "win-x64", + "-c", + "Release", + "-p:PublishAot=true", + "${workspaceFolder}/Fab2ApprovalTests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/Fab2ApprovalTests/Controller/HomeControllerTests.cs b/Fab2ApprovalTests/Controller/HomeControllerTests.cs new file mode 100644 index 0000000..15b253b --- /dev/null +++ b/Fab2ApprovalTests/Controller/HomeControllerTests.cs @@ -0,0 +1,96 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.ViewModels; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.Controller; + +[TestClass] +public class HomeControllerTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void GetMyOpenActionItems(ILogger? logger, AppSettings appSettings) { + SetGlobalVars(logger, appSettings); + LotDispositionDMO lotDispositionDMO = new(appSettings); + OpenActionItemViewModel[] openActionItemViewModels = lotDispositionDMO.GetMyOpenActionItems(appSettings.UserId).ToArray(); + if (openActionItemViewModels.Length == 0) { } + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void GetMyOpenActionItemsIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + GetMyOpenActionItems(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + + private static void GetTaskList(ILogger? logger, AppSettings appSettings) { + SetGlobalVars(logger, appSettings); + LotDispositionDMO lotDispositionDMO = new(appSettings); + IssuesViewModel[] issuesViewModels = lotDispositionDMO.GetTaskList(appSettings.UserId).ToArray(); + if (issuesViewModels.Length == 0) { } + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void GetTaskListIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + GetTaskList(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/AccountDMOTests.cs b/Fab2ApprovalTests/DMO/AccountDMOTests.cs new file mode 100644 index 0000000..25909ae --- /dev/null +++ b/Fab2ApprovalTests/DMO/AccountDMOTests.cs @@ -0,0 +1,63 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class AccountDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void AccountDMO(AppSettings appSettings, HttpClient httpClient) { +#pragma warning disable IDE0059, CS8625 + UserAccountDMO userAccountDMO = new(); + LoginModel loginModel = userAccountDMO.GetUserByID(appSettings.UserId); + Task loginResultTask = Fab2ApprovalSystem.DMO.AccountDMO.LoginAsync(httpClient, loginModel: loginModel); + loginResultTask.Wait(); + Task loginResultTaskB = Fab2ApprovalSystem.DMO.AccountDMO.ExternalAuthSetupAsync(httpClient, authAttempt: null); + loginResultTaskB.Wait(); + if (loginModel is null) { } +#pragma warning restore IDE0059, CS8625 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void AccountDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + HttpClient? httpClient = _WebApplicationFactory?.CreateClient(); + Assert.IsTrue(httpClient is not null); + httpClient.BaseAddress = new Uri(appSettings.ApiBaseUrl); + if (System.Diagnostics.Debugger.IsAttached) + AccountDMO(appSettings, httpClient); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/AdminDMOTests.cs b/Fab2ApprovalTests/DMO/AdminDMOTests.cs new file mode 100644 index 0000000..bcc9e81 --- /dev/null +++ b/Fab2ApprovalTests/DMO/AdminDMOTests.cs @@ -0,0 +1,93 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class AdminDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void AdminDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + AdminDMO adminDMO = new(); + // void AddNewTrainingGroup(string groupName); + // void AddUserRoles(int subRole, string userids); + // void AddUserToGroup(int userId, int groupId); + // void DeleteFromGroup(int userId, int groupId); + // void DeleteTrainingGroup(int groupID); + // adminDMO.DeleteUserFromAllTrainingGroups(appSettings.UserId); + // void DeleteUserRoles(int subRole, string userids); + // IEnumerable GetAllUsersBySubRole(int subRole); + Role[] roles = adminDMO.GetSubRoles().ToArray(); + ParentChildModel[] newRoles = adminDMO.GetAllSubRoles().ToArray(); + // TECNNotificationsUser[] tECNNotificationsUsers = adminDMO.GetTECNNotificationUsers().ToArray(); + // List GetTrainingGroupMembers(int GroupID); + // TrainingGroup[] trainingGroups = adminDMO.GetTrainingGroups().ToArray(); + TrainingReportUser[] trainingReportUsers = adminDMO.GetTrainingReportUsers().ToArray(); + UserSubRoles[] userSubRoless = adminDMO.GetUserSubRoles(appSettings.UserId).ToArray(); + // adminDMO.TECNExpirationAddUser(appSettings.UserId); + // adminDMO.TECNExpirationDeleteUser(appSettings.UserId); + // adminDMO.TrainingReportAddUser(appSettings.UserId); + // adminDMO.TrainingReportDeleteUser(appSettings.UserId); + if (adminDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void AdminDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + AdminDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/AuditDMOTests.cs b/Fab2ApprovalTests/DMO/AuditDMOTests.cs new file mode 100644 index 0000000..0ec17e1 --- /dev/null +++ b/Fab2ApprovalTests/DMO/AuditDMOTests.cs @@ -0,0 +1,100 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class AuditDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void AuditDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + AuditDMO auditDMO = new(appSettings); + // void DeleteAuditReportAttachment(int attachmentID); + // void DeleteCAFindingsItem(int caFindingsID); + int[] ints = auditDMO.Get8DQA().ToArray(); + AuditedArea[] auditedAreas = auditDMO.GetAuditAreaList().ToArray(); + // IEnumerable GetAuditFindingCategoryIdsByFindingId(int auditFindingsID); + // AuditFindings GetAuditFindingsByID(int auditFindingsID); + // IEnumerable GetAuditFindingsList(int auditNo); + // Audit GetAuditItem(int auditNo, int userID); + // Audit GetAuditItemReadOnly(int auditNo, int userID); + Auditor[] auditors = auditDMO.GetAuditorList().ToArray(); + // IEnumerable GetAuditReportAttachments(int auditNo); + // C_8DAuditedStandard[] c_8DAuditedStandards = auditDMO.GetAuditStandardList().ToArray(); + AuditType[] auditTypes = auditDMO.GetAuditTypeList().ToArray(); + // CAFindings GetCAFindingsItem(int caFindingsID); + // IEnumerable GetCAFindingsItemAttachments(int caFindingsID); + // IEnumerable GetCAFindingsList(int auditNo); + CANoList[] cANoLists = auditDMO.GetCorrectiveActionNoList().ToArray(); + // int GetOpenCACountByAuditNo(int auditNo); + CAUserList[] cAUserLists = auditDMO.GetUserList().ToArray(); + // Audit InsertAudit(Audit audit); + // void InsertAuditReportAttachment(AuditReportAttachment attach); + // void InsertCAFindings(CAFindings model); + // int IsCAAssignedToAudit(int CANo, int auditNo); + // void ReleaseLockOnDocument(int userID, int issueID); + // void UpdateAudit(Audit audit, int userID); + // void UpdateCAFindings(CAFindings model); + if (auditDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void AuditDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + AuditDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/ChangeControlDMOTests.cs b/Fab2ApprovalTests/DMO/ChangeControlDMOTests.cs new file mode 100644 index 0000000..2b2ae46 --- /dev/null +++ b/Fab2ApprovalTests/DMO/ChangeControlDMOTests.cs @@ -0,0 +1,79 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class ChangeControlDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void ChangeControlDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + ChangeControlDMO changeControlDMO = new(appSettings); + // IEnumerable GetCCAttachment(int planNumber); + // IEnumerable GetMeetingAttachments(int meetingID); + // IEnumerable GetMeetingDecisionSummaryList(int planNumber); + // IEnumerable GetMeetingList(int planNumber); + // void ReassignOwner(int planNumber, int newOwnerID, string comments, int userID); + if (changeControlDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void ChangeControlDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + ChangeControlDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/CorrectiveActionDMOTests.cs b/Fab2ApprovalTests/DMO/CorrectiveActionDMOTests.cs new file mode 100644 index 0000000..d5e32a1 --- /dev/null +++ b/Fab2ApprovalTests/DMO/CorrectiveActionDMOTests.cs @@ -0,0 +1,123 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.ViewModels; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class CorrectiveActionDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void CorrectiveActionDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + CorrectiveActionDMO correctiveActionDMO = new(appSettings); + // void ApproveSection(int issueID, int userID, string DSection); + // void DeleteCAAttachment(int attachmentID); + // void DeleteD3ContainmentActionItem(int d3ContainmentActionID); + // void DeleteD5D6CorrectivetAction(int d5d6CAID); + // void DeleteD7PreventiveActionItem(int D7PAID); + int[] ints = correctiveActionDMO.Get8DQA().ToArray(); + CAUserList[] cAUserLists = correctiveActionDMO.GetAllUserList().ToArray(); + // string GetCAAttachmentFileName(string fileGUID); + // IEnumerable GetCAAttachmentsList(int caNo, string section); + CAD3D5D7Due[] cAD3D5D7Dues = correctiveActionDMO.GetCAD3D5D7Due().ToArray(); + // IEnumerable GetCAFindingsItemAttachments(int caFindingsID); + // CorrectiveAction GetCAItem(int caNo, int userID); + // CorrectiveAction GetCAItemReadOnly(int caNo, int userID); + // IEnumerable GetCASectionApprovalLog(int caNo); + CASource[] cASources = correctiveActionDMO.GetCASourceList().ToArray(); + // IEnumerable GetD3ContainmentActions(int caNo); + RiskAssessmentArea[] riskAssessmentAreas = correctiveActionDMO.GetD3RiskAssessmentAreas().ToArray(); + // D5D6CorrectivetAction GetD5D5CAItem(int d5d6CAID); + // IEnumerable GetD5D6CorrectivetActions(int caNo); + D5D6Improvement[] d5D6Improvements = correctiveActionDMO.GetD5D6Improvement().ToArray(); + // IEnumerable GetD5D6ItemAttachments(int d5d6CAID); + // IEnumerable GetD7ItemAttachments(int d7PAID); + // D7PreventiveAction GetD7PAItem(int d7PAID); + // IEnumerable GetD7PreventiveActions(int caNo); + IssuesViewModel[] issuesViewModels = correctiveActionDMO.GetECNList().ToArray(); + Module[] modules = correctiveActionDMO.GetModuleList().ToArray(); + // List GetRejectionAssigneeEmailList(int caNo); + CAUserList[] cAUserListsB = correctiveActionDMO.GetUserList().ToArray(); + // CorrectiveAction InsertCA(CorrectiveAction ca); + // void InsertCAAttachment(CA_Attachment attach); + // void InsertD3ContainmentAction(D3ContainmentAction model); + // void InsertD5D6CorrectivetAction(D5D6CorrectivetAction model); + // void InsertD7PreventiveAction(D7PreventiveAction model); + // bool IsAIAssignee(int userId, int caId); + // bool IsLastSectionApprover(int caNo, string dSection); + // bool IsUserSectionApprover(int issueId, int userId); + // void RejectSection(int issueID, int userID, string DSection, string comments); + // void ReleaseLockOnDocument(int userID, int issueID); + // DateTime SetCAComplete(int issueID); + // DateTime SetCAD3DueDate(int issueID); + // DateTime SetCAD5D7DueDate(int issueID); + // void SetD3D5D7NotificationDate(int caNo, string section); + // int StartApproval(int issueID, int userID, int worlflowNumber); + // void StartSectionApproval(int issueID, int userID, string DSection); + // void UpdateCorrectiveAction(CorrectiveAction model); + // void UpdateD3ContainmentAction(D3ContainmentAction model); + // void UpdateD5D6CorrectivetAction(D5D6CorrectivetAction model); + // void UpdateD7PreventiveAction(D7PreventiveAction model); + if (correctiveActionDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void CorrectiveActionDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + CorrectiveActionDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/EngChangeNoticeDMOTests.cs b/Fab2ApprovalTests/DMO/EngChangeNoticeDMOTests.cs new file mode 100644 index 0000000..8954726 --- /dev/null +++ b/Fab2ApprovalTests/DMO/EngChangeNoticeDMOTests.cs @@ -0,0 +1,103 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.ViewModels; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class EngChangeNoticeDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void EngChangeNoticeDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + ECN_DMO ecnDMO = new(); + // void CancelECN(int? ecnNumber); + // bool CanSubmitECN(int ecnNumber); + // void DeleteDocument(int ecnNumber, int userid, string ecnTypeString); + // void DeleteECNAttachment(int attachmentID); + // bool ECNApproveCancelled_ExpiredDocument(int issueID, byte step, string comments, out bool lastStep, int userID, int documentType); + // void ECNResetTECNAtRejection(int ecnNumber, int userID, int docType); + IssuesViewModel[] issuesViewModels = ecnDMO.GetAllTECNs().ToArray(); + // IEnumerable GetECNApprovalLogHistory(int ecnNumber); + // IEnumerable GetECNAttachments(int ecnNumber); + IssuesViewModel[] issuesViewModelsB = ecnDMO.GetECN_TECNPendingApprovals(appSettings.UserId).ToArray(); + // string GetFileName(string attachmentID); + // IEnumerable GetMyConvertedTECNsToECNs(int userID, int maxDays); + // IEnumerable GetMyExpiredTECNs(int userID, int maxDays); + // IEnumerable GetMyExpiringTECNs(int userID, int maxDays); + // List GetRejectionOrginatorEmailList(int ecnNumber); + int[] ints = ecnDMO.GetTECNNotificationUsers().ToArray(); + // void InsertECNAttachment(ECNAttachment attach); + // int PCRBExists(int pcrb); + // void ReassignOriginatorECN(int ecnNumber, int newOriginatorID, string comments, int userID); + // void ReleaseLockOnDocument(int userID, int issueID); + // int ReSubmitDocument(int issueID, int userID, int documentType, out int allowedITAR, string descriptionOfChange, string reasonForChange, string ecnTypeString, out int newECNNumber, int categoryId); + // void SaveAfterSubmitByApprover(int ecnNumber, string implementationDetails); + // void SetToExecutionStep(int ecnNumber, int userid, int documentType, string ecnTypeString); + // int SubmitDocument(int issueID, int userID, int documentType, out int allowedITAR); + // int SubmitForCancellation(int issueID, byte currentStep, int userID, int documentType, string ecnType, int TECNOperationType); + // int SubmitTECNExtensionDocument(int issueID, int userID, int documentType, DateTime extensionDate); + // void TECNExtensionLog(int ecnNumber, DateTime extensionDate); + // void UpdateECNType(int ecnNumber, string ecnType); + if (ecnDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void EngChangeNoticeDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + EngChangeNoticeDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/LotDispositionDMOTests.cs b/Fab2ApprovalTests/DMO/LotDispositionDMOTests.cs new file mode 100644 index 0000000..0a0728f --- /dev/null +++ b/Fab2ApprovalTests/DMO/LotDispositionDMOTests.cs @@ -0,0 +1,119 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.ViewModels; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests; + +[TestClass] +public class LotDispositionDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void LotDispositionDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + LotDispositionDMO lotDispositionDMO = new(appSettings); + // void DeleteAllLotDispoLot(int issueID); + // void DeleteCADocument(int CANo, int userID, string caTypeString); + // void DeleteLotDispoAttachment(int attachmentID); + // void DeleteLotDispoLot(int lotID); + AuditList[] auditLists = lotDispositionDMO.GetAuditList(appSettings.UserId).ToArray(); + // Errors! // ChangeControlList[] changeControlLists = lotDispositionDMO.GetChangeControls(appSettings.UserId).ToArray(); + CorrectiveAction[] correctiveActions = lotDispositionDMO.GetCorrectiveActionList(appSettings.UserId).ToArray(); + LotDispoDepartment[] lotDispoDepartments = lotDispositionDMO.GetDepartments().ToArray(); + IssuesViewModel[] issuesViewModels = lotDispositionDMO.GetDocuments().ToArray(); + IssuesViewModel[] issuesViewModelsB = lotDispositionDMO.GetECNList(appSettings.UserId).ToArray(); + // string GetFileName(string attachmentID); + // Attachment[] GetLotDispoAttachments(int issueID); + // LotDisposition GetLotDispositionItem(int issueID, out int isITAR, int userID); + // LotDisposition GetLotDispositionItemForRead(int issueID, out int isITAR, int userID); + IssuesViewModel[] issuesViewModelsC = lotDispositionDMO.GetLotDispositionList(appSettings.UserId).ToArray(); + // Lot[] GetLotDispositionLots(int issueID); + // LotDispositionLotSummaryViewModel GetLotDispositionLotSummary(int issueID); + IssuesViewModel[] issuesViewModelsD = lotDispositionDMO.GetLotDispositions().ToArray(); + LotStatusOptionViewModel[] lotStatusOptionViewModels = lotDispositionDMO.GetLotStatusOptions().ToArray(); + // ScrapLot GetLotStausDetail(int issueID, string lotNumber); + IssuesViewModel[] issuesViewModelsE = lotDispositionDMO.GetMRBList(appSettings.UserId).ToArray(); + // SPN_MRB[] GetMRBsFromSPN(string lotNumber); + OpenActionItemViewModel[] openActionItemViewModels = lotDispositionDMO.GetMyOpenActionItems(appSettings.UserId).ToArray(); + // string[] GetRejectionOrginatorEmailList(int issueID).ToArray(); + // ResponsibilityIssue[] GetResponsibilityIssueList(int responsibilityID); + Responsibility[] responsibilities = lotDispositionDMO.GetResponsibilityList().ToArray().ToArray(); + // int GetRHLotCount(int issueID); + IssuesViewModel[] issuesViewModelsF = lotDispositionDMO.GetTaskList(appSettings.UserId).ToArray(); + Users[] users = lotDispositionDMO.GetUserList().ToArray(); + IssuesViewModel[] issuesViewModelsG = lotDispositionDMO.GetWorkRequests().ToArray(); + // void InsertChildLot_NotInTheMRB(string lotNumber); + // void InsertComments(int issueID, string comments, int commentedBy); + // int InsertLot(Lot lot, bool getLotInfo); + // LotDisposition InsertLotDisposition(LotDisposition lotDispo); + // void InsertLotDispositionAttachment(Attachment attach); + // void ReleaseLockOnDocument(int userID, int issueID); + // Lot[] SearchLots(string searchText); + // int SubmitDocument(int issueID, bool peRequired, bool mrbRequired, int userID); + // void UpdateLotDispoLot(Lot lot); + // void UpdateLotDisposition(LotDisposition lotDispo); + // void UpdateLotScrapReleaseStatus(ScrapLot scrap); + // void UpdateLotStatus(ScrapLot lotStatus); + // void UpdateLotStatusAll(ScrapLot scrap, int lotStatus); + // void UpdateReasonForDisposition(int issueID, string reasonForDisposition); + if (lotDispositionDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void LotDispositionDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + LotDispositionDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/LotTravelerDMOTests.cs b/Fab2ApprovalTests/DMO/LotTravelerDMOTests.cs new file mode 100644 index 0000000..d95bb02 --- /dev/null +++ b/Fab2ApprovalTests/DMO/LotTravelerDMOTests.cs @@ -0,0 +1,105 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class LotTravelerDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void LotTravelerDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + LotTravelerDMO lotTravelerDMO = new(appSettings); + // int CanAddLocationOperation(LTLotTravelerHoldSteps model); + // int CreateLotTravelerRevision(LTLotTravelerHoldSteps model, int userID); + // void CreateTraveler(int ltLotID, int workRequestID, int UserID); + // int CreateWorkRequestRevision(LTWorkRequest data, int userID); + // void DeleteLot(int ltLotID); + // IEnumerable GetLotList(int workRequestID); + // IEnumerable GetLotListBasedOnSWRNumber(int swrNumber); + // IEnumerable GetLotsWithTraveler(int workRequestID); + // LTLotTravelerHeaderViewModel GetLotTravelerHeaderForReadOnly(int ltLotID, int revisionNumber); + // LTLotTravelerHeaderViewModel GetLotTravelerHeaderForUpdate(int ltLotID, int UserID); + // IEnumerable GetLotTravelerHolStepsByRevision(int ltLotID, int revisionNumber); + // IEnumerable GetLotTravelerRevisionHistory(int lotID); + // IEnumerable GetLotTravHoldSteps(int ltLotID); + // IEnumerable GetLotTravHoldStepsCompleted(int ltLotID); + // IEnumerable GetLotTravHoldStepsPending(int ltLotID); + // LotTravelerPdf GetLotTravlerPdf(int ltLotID, int revisionNumber); + // List GetLotTravRevisions(int ltLotID); + // List GetRejectionOrginatorEmailList(int workRequestID); + // IEnumerable GetWorkReqApprovalLogHistory(int swrNumber); + // IEnumerable GetWorkReqRevisionHistory(int swrNumber); + // List GetWorkReqRevisions(int swrNumber); + // void InsertLot(LTLot lot); + // int InsertLotTravelerHoldStep(LTLotTravelerHoldSteps model, int userID); + // void ReassignOriginator(int workRequestID, int newOriginatorID, string comments, int userID); + // void ReleaseLockOnDocument(int userID, int workRequestID); + // void ReleaseLockOnLotTravelerUpdateDoc(int userID, int ltLotID); + // void RestoreLotTravToPrevRevision(int prevLotTravRevID, int newLotTravRevID); + // int SubmitDocument(int workRequestID, int userID, int documentType, out int allowedITAR); + // int UpdateLotTravelerHoldStep(LTLotTravelerHoldSteps model, int userID); + // void UpdateLotTravlerExecution(int lotTravHoldStepID, string taskComments, bool CompletedFlag, int userID); + // int UpdateRevisedLotTravelerHoldStep(LTLotTravelerHoldSteps model, int userID); + if (lotTravelerDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void LotTravelerDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + LotTravelerDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/MatReviewBoardDMOTests.cs b/Fab2ApprovalTests/DMO/MatReviewBoardDMOTests.cs new file mode 100644 index 0000000..a871615 --- /dev/null +++ b/Fab2ApprovalTests/DMO/MatReviewBoardDMOTests.cs @@ -0,0 +1,77 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class MatReviewBoardDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void MatReviewBoardDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + MRB_DMO matReviewBoardDMO = new(appSettings); + // MRBAttachment GetMRBAttachment(int attachmentID); + CAUserList[] cAUserLists = matReviewBoardDMO.GetUserList().ToArray(); + // void UpdateContainmentAction(ContainmentActionObj model); + if (matReviewBoardDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void MatReviewBoardDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + MatReviewBoardDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/MiscDMOTests.cs b/Fab2ApprovalTests/DMO/MiscDMOTests.cs new file mode 100644 index 0000000..c3c88e1 --- /dev/null +++ b/Fab2ApprovalTests/DMO/MiscDMOTests.cs @@ -0,0 +1,76 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class MiscDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void MiscDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + MiscDMO miscDMO = new(); + ApproveListModel[] approveListModels = miscDMO.GetApprovalReminderList().ToArray(); + // void UpdateApprovalNotifyDate(int approvalId); + if (miscDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void MiscDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + MiscDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/PartsRequestDMOTests.cs b/Fab2ApprovalTests/DMO/PartsRequestDMOTests.cs new file mode 100644 index 0000000..13a445e --- /dev/null +++ b/Fab2ApprovalTests/DMO/PartsRequestDMOTests.cs @@ -0,0 +1,86 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class PartsRequestDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void PartsRequestDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + PartsRequestDMO partsRequestDMO = new(appSettings); + // void DeleteAttachment(int attachmentID); + // void DeleteDocument(int prNumber, int userid); + // PartsRequest Get(int PRNumber); + // IEnumerable GetApprovalLogHistory(int prNumber); + // IEnumerable GetAttachments(int prNumber); + // string GetFileName(string attachmentID); + MyPartsRequestList[] myPartsRequestLists = partsRequestDMO.GetMyPartsRequests(appSettings.UserId).ToArray(); + PartsRequestList[] partsRequestLists = partsRequestDMO.GetPartsRequestList().ToArray(); + // void Insert(PartsRequest pr); + // void InsertAttachment(PartsRequestAttachment attach); + // void Submit(int prNumber, int userID); + // void Update(PartsRequest pr); + if (partsRequestDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void PartsRequestDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + PartsRequestDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/TrainingDMOTests.cs b/Fab2ApprovalTests/DMO/TrainingDMOTests.cs new file mode 100644 index 0000000..3c1712e --- /dev/null +++ b/Fab2ApprovalTests/DMO/TrainingDMOTests.cs @@ -0,0 +1,108 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class TrainingDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void TrainingDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + TrainingDMO trainingDMO = new(); + // void AcknowledgeDocument(int trainingDocAckID); + // void AddTrainingGroupToECN(int ECNNumber, int groupId); + // bool CheckTrainingAssignmentStatus(int trainingAssignmentID); + // bool CheckTrainingStatus(int trainingAssignmentID); + // bool CheckValidDocAck(int docAckId); + // int Create(int issueId); + // int CreateAssignment(int trainingId, int userId); + // void DeleteAssignmentByUserId(int userId); + // void DeleteTraining(int trainingId); + // void DeleteTrainingAssignment(int trainingAssignmentId); + // void DeleteTrainingDocAck(int trainingAssignmentId); + // Training[] trainings = trainingDMO.GetAllOpenTrainings().ToArray(); + // List GetAllTrainingAssignments(int TrainingID); + // Training[] trainingsB = trainingDMO.GetAllTrainings().ToArray(); + // List GetAssignedDocs(int trainingAssignmentId); + // TrainingAssignment GetAssignment(int assignmentId); + // List GetECNAssignedTrainingGroups(int ECNNumber); + // List GetOpenAssignmentsByTrainingID(int trainingID); + // List GetTrainees(int groupId); + // Training GetTraining(int trainingId); + // List GetTrainingAssignments(int TrainingID); + // List GetTrainingAssignmentsByUser(int TrainingID, int userID); + // List GetTrainingAssignmentsByUserID(int userID); + // TrainingGroup GetTrainingGroupByID(int groupId); + // TrainingGroup[] trainingGroups = trainingDMO.GetTrainingGroups().ToArray(); + // int GetTrainingId(int issueId); + // int GetTrainingIdByAssignment(int trainingAssignmentID); + // Training[] trainingsC = trainingDMO.GetTrainings().ToArray(); + // bool IsUserAssigned(int userId, int trainingId); + // bool isUserTrainingMember(int groupId, int userId); + // void reOpenTraining(int trainingId); + // void SetTrainingFlag(int ECNNumber); + // void UpdateAssignmentStatus(int trainingAssignmentID); + // void UpdateTrainingStatus(int trainingId); + if (trainingDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void TrainingDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + TrainingDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/UserAccountDMOTests.cs b/Fab2ApprovalTests/DMO/UserAccountDMOTests.cs new file mode 100644 index 0000000..b7f007f --- /dev/null +++ b/Fab2ApprovalTests/DMO/UserAccountDMOTests.cs @@ -0,0 +1,79 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class UserAccountDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void UserAccountDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + UserAccountDMO userAccountDMO = new(); + LoginModel[] loginModels = userAccountDMO.GetAllActiveUsers().ToArray(); + LoginModel[] loginModelsB = userAccountDMO.GetAllUsers().ToArray(); + LoginModel loginModel = userAccountDMO.GetUserByID(appSettings.UserId); + LoginModel loginModelB = userAccountDMO.GetUser(loginModel.LoginID); + string userEmail = userAccountDMO.GetUserEmailByID(appSettings.UserId); + if (userAccountDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void UserAccountDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + UserAccountDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/DMO/WorkflowDMOTests.cs b/Fab2ApprovalTests/DMO/WorkflowDMOTests.cs new file mode 100644 index 0000000..30b2d1f --- /dev/null +++ b/Fab2ApprovalTests/DMO/WorkflowDMOTests.cs @@ -0,0 +1,86 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.DMO; + +[TestClass] +public class WorkflowDMOTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void WorkflowDMO(ILogger? logger, AppSettings appSettings) { +#pragma warning disable IDE0059 + SetGlobalVars(logger, appSettings); + WorkflowDMO workflowDMO = new(); + // string AddAdditionalApproval(int issueID, string userIDs, byte step, int documentType); + // string AddEECNApproval(int ecnNumber, byte step, int documentType, string engUserIDs, string opUserIDs); + // bool Approve(int issueID, byte step, string comments, out bool lastStep, int userID, int documentType, int workFlowNumber); + // string DelegateDocumentApproval(int issueID, int delegateFromUser, int delegateToUser); + // string GetApproversForCancelled_ExpiredTECNDocs(int ecnNumber); + // string GetSubRoleItems(int issueID, int docType); + // string GetSubRolesForPartsRequestNextStep(int prNumber); + // WorkflowSteps GetWorkflowStep(int docTypeID, int wfNumber, int stepNumber); + // string ReAssignApproval(int issueID, int assignedFromUser, int assignedToUser, byte step, int docType); + // bool Recall(int issueID, byte step, string comments, int userID, int docType); + // bool Reject(int issueID, byte step, string comments, int userID, int docType); + // void RejectTECNExtension(int ecnNumber, byte step, string comments, int userID, int docType); + if (workflowDMO is null) { } +#pragma warning restore IDE0059 + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void WorkflowDMOIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + WorkflowDMO(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/Fab2ApprovalTests.csproj b/Fab2ApprovalTests/Fab2ApprovalTests.csproj new file mode 100644 index 0000000..6561ca6 --- /dev/null +++ b/Fab2ApprovalTests/Fab2ApprovalTests.csproj @@ -0,0 +1,50 @@ + + + enable + false + true + enable + net8.0 + + + true + true + true + + + Windows + + + OSX + + + Linux + + + Debug + + + Release + + + trx + XPlat Code Coverage + ../.vscode/TestResults + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Fab2ApprovalTests/General/CorrectiveActionTests.cs b/Fab2ApprovalTests/General/CorrectiveActionTests.cs new file mode 100644 index 0000000..a6d8b78 --- /dev/null +++ b/Fab2ApprovalTests/General/CorrectiveActionTests.cs @@ -0,0 +1,129 @@ +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Models; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.General; + +[TestClass] +public class CorrectiveActionTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + private static DateTime? SetD3DueDate(int cANo) => throw new NotImplementedException(); + private static DateTime? SetD5D7DueDate(int cANo) => throw new NotImplementedException(); + private static void NotifyApprovers(int cANo, int v) => throw new NotImplementedException(); + private static void NotifySectionApprover(int cANo, int qAID, string sectionApproval) => throw new NotImplementedException(); + private static void NotifyAssignee(int cANo, int d1AssigneeID, string v, DateTime? d3DueDate, DateTime? d5D7DueDate) => throw new NotImplementedException(); + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void Edit(int currentUserId, CorrectiveActionDMO caDMO, CorrectiveAction model) { + CorrectiveAction caPrevious = caDMO.GetCAItemReadOnly(model.CANo, currentUserId); + if (currentUserId != caPrevious.D1AssigneeID && currentUserId != caPrevious.QAID && currentUserId != caPrevious.RequestorID) + throw new Exception("User is not authorized to save the CA."); + try { + if (model.TriggerApproval) { + //model.FollowUpDate = DateTime.Now.AddMonths(6); + } + caDMO.UpdateCorrectiveAction(model); + if ((model.D1AssigneeID != model.CurrentD1AssigneeID && model.CASubmitted) || (model.CASubmitted && !caPrevious.CASubmitted)) { + //Set Due Dates here: + DateTime? D3DueDate = null; + DateTime? D5D7DueDate = null; + if (model.CAType != "D0") { + D3DueDate = SetD3DueDate(model.CANo); + if (model.CAType != "D3") { + D5D7DueDate = SetD5D7DueDate(model.CANo); + } + } + NotifyAssignee(model.CANo, model.D1AssigneeID, "CorrectiveActionAssignee.txt", D3DueDate, D5D7DueDate); + } + if (model.TriggerSectionApproval) { + if (model.SectionApproval == "D5D6D7Validation") { + caDMO.StartSectionApproval(model.CANo, model.RequestorID, model.SectionApproval); + throw new Exception("Successfully Saved...Validation initiated!"); + } + caDMO.StartSectionApproval(model.CANo, model.QAID, model.SectionApproval); + caDMO.StartSectionApproval(model.CANo, model.RequestorID, model.SectionApproval); + NotifySectionApprover(model.CANo, model.QAID, model.SectionApproval); + NotifySectionApprover(model.CANo, model.RequestorID, model.SectionApproval); + //NotifyApprovers(model.CANo, 1); + throw new Exception("Successfully Saved...Approval initiated!"); + } + if (model.TriggerApproval) { + _ = caDMO.StartApproval(model.CANo, currentUserId, model.WorkFlowNumber); + NotifyApprovers(model.CANo, 1); + throw new Exception("Successfully Saved...Approval initiated!"); + } + } catch (Exception ex) { + throw new Exception(ex.Message); + } + } + + internal static void TestCorrectiveAction(ILogger? logger, AppSettings appSettings, int caNo) { + SetGlobalVars(logger, appSettings); + CorrectiveAction ca; + CorrectiveActionDMO caDMO = new(appSettings); + ca = caDMO.GetCAItemReadOnly(caNo, appSettings.UserId); + if (ca is null) + throw new Exception($"{nameof(ca)}"); + ca = caDMO.GetCAItem(caNo, appSettings.UserId); + if (ca is null) + throw new Exception($"{nameof(ca)}"); + Edit(appSettings.UserId, caDMO, ca); + } + +#if Release + [Ignore] +#endif + [DataTestMethod] + [DataRow(295)] + public void TestCorrectiveActionIsAttachedOnly(int caNo) { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + TestCorrectiveAction(_Logger, appSettings, caNo); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/General/ScheduleTests.cs b/Fab2ApprovalTests/General/ScheduleTests.cs new file mode 100644 index 0000000..473d1ad --- /dev/null +++ b/Fab2ApprovalTests/General/ScheduleTests.cs @@ -0,0 +1,90 @@ +using Fab2ApprovalSystem.Models; + +using Fab2ApprovalSystem.Workers; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +using Quartz; +using Quartz.Impl; + +namespace Fab2ApprovalTests.General; + +[TestClass] +public class ScheduleTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + public static void SetGlobalVars(ILogger? logger, AppSettings appSettings) { + logger?.LogDebug("Starting to set Fab2ApprovalSystem.Misc.GlobalVars"); + Fab2ApprovalSystem.Misc.GlobalVars.AppSettings = appSettings; + Fab2ApprovalSystem.Misc.GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + Fab2ApprovalSystem.Misc.GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + Fab2ApprovalSystem.Misc.GlobalVars.DBConnection = appSettings.DBConnection; + Fab2ApprovalSystem.Misc.GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + Fab2ApprovalSystem.Misc.GlobalVars.hostURL = appSettings.HostURL; + Fab2ApprovalSystem.Misc.GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + Fab2ApprovalSystem.Misc.GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + Fab2ApprovalSystem.Misc.GlobalVars.NDriveURL = appSettings.NDriveURL; + Fab2ApprovalSystem.Misc.GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ID = appSettings.UserId; + Fab2ApprovalSystem.Misc.GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + Fab2ApprovalSystem.Misc.GlobalVars.WSR_URL = appSettings.WSR_URL; + logger?.LogDebug("Finished setting Fab2ApprovalSystem.Misc.GlobalVars"); + } + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + + private static void Init(ILogger? logger, AppSettings appSettings) { + SetGlobalVars(logger, appSettings); + + ISchedulerFactory schedulerFactory = new StdSchedulerFactory(); + + IScheduler scheduler = schedulerFactory.GetScheduler(_TestContext.CancellationTokenSource.Token).GetAwaiter().GetResult(); + + IJobDetail oooTrainingReportJob = JobBuilder.Create() + .WithIdentity("oooTrainingReportJob", "trainingReportGroup") + .Build(); + + ITrigger oooTrainingReportTrigger = TriggerBuilder.Create() + .WithIdentity("oooTrainingReportTrigger", "trainingReportGroup") + .WithCronSchedule("15 13 * * MON") + .ForJob(oooTrainingReportJob) + .Build(); + + _ = scheduler.ScheduleJob(oooTrainingReportJob, oooTrainingReportTrigger, _TestContext.CancellationTokenSource.Token); + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void InitIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + Init(_Logger, appSettings); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/Usings.cs b/Fab2ApprovalTests/Usings.cs new file mode 100644 index 0000000..ab67c7e --- /dev/null +++ b/Fab2ApprovalTests/Usings.cs @@ -0,0 +1 @@ +global using Microsoft.VisualStudio.TestTools.UnitTesting; \ No newline at end of file diff --git a/Fab2ApprovalTests/Utilities/EmailUtilitiesTests.cs b/Fab2ApprovalTests/Utilities/EmailUtilitiesTests.cs new file mode 100644 index 0000000..0e9b180 --- /dev/null +++ b/Fab2ApprovalTests/Utilities/EmailUtilitiesTests.cs @@ -0,0 +1,49 @@ +using Fab2ApprovalSystem.Models; + +using Fab2ApprovalSystem.Utilities; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.Utilities; + +[TestClass] +public class EmailUtilitiesTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void EmailUtilitiesIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) + EmailUtilities.SendNotification("mike.phares@infineon.com", [], "Test: Subject", "Body"); + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file diff --git a/Fab2ApprovalTests/Utilities/UserUtilitiesTests.cs b/Fab2ApprovalTests/Utilities/UserUtilitiesTests.cs new file mode 100644 index 0000000..db935f9 --- /dev/null +++ b/Fab2ApprovalTests/Utilities/UserUtilitiesTests.cs @@ -0,0 +1,50 @@ +using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.Utilities; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalTests.Utilities; + +[TestClass] +public class UserUtilitiesTests { + +#pragma warning disable CS8618 + + private static ILogger? _Logger; + private static TestContext _TestContext; + private static WebApplicationFactory _WebApplicationFactory; + +#pragma warning restore + + [ClassInitialize] + public static void ClassInitAsync(TestContext testContext) { + _TestContext = testContext; + _WebApplicationFactory = new WebApplicationFactory(); + IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; + _Logger = serviceProvider.GetRequiredService>(); + } + + private static void NonThrowTryCatch() { + try { throw new Exception(); } catch (Exception) { } + } + +#if Release + [Ignore] +#endif + [TestMethod] + public void UserUtilitiesIsAttachedOnly() { + _Logger?.LogInformation("Starting Web Application"); + IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; + AppSettings? appSettings = serviceProvider?.GetRequiredService(); + Assert.IsTrue(appSettings is not null); + if (System.Diagnostics.Debugger.IsAttached) { + List allUserModels = UserUtilities.GetMesaUsers(); + Assert.IsNotNull(allUserModels); + } + _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); + NonThrowTryCatch(); + } + +} \ No newline at end of file