Advertisement
Guest User

Untitled

a guest
Apr 17th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 57.90 KB | None | 0 0
  1. class PrescriptionsService
  2.  
  3.   def self.get_sql_for_role(user_id)
  4.     joins = "
  5.              --check if activate allowed
  6.              LEFT JOIN (
  7.                          SELECT
  8.                            DISTINCT
  9.                            p.id AS prescription_id
  10.                          FROM users
  11.                            INNER JOIN user_permissions AS up ON up.user_id = users.id
  12.                            INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id
  13.                            INNER JOIN prescription_general_permission_actions AS pgpa
  14.                              ON pgpa.id = pgp.prescription_general_permission_action_id
  15.                            CROSS JOIN prescriptions AS p
  16.                            LEFT JOIN user_business_units AS ubu ON ubu.user_id = users.id
  17.                          WHERE users.id = #{user_id} AND pgpa.id_name = '_activate' AND ( users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id )
  18.                        ) AS perms_activate ON perms_activate.prescription_id = prescriptions.id
  19.              --check if access allowed
  20.              LEFT JOIN (
  21.                          SELECT
  22.                            DISTINCT
  23.                            pgpa.id_name AS pgpa_id_name
  24.                          FROM users
  25.                            INNER JOIN user_permissions AS up ON up.user_id = users.id
  26.                            INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id
  27.                            INNER JOIN prescription_general_permission_actions AS pgpa
  28.                              ON pgpa.id = pgp.prescription_general_permission_action_id
  29.                          WHERE users.id = #{user_id}
  30.                        ) AS perms_access ON perms_access.pgpa_id_name = '_access'
  31.              --check if create allowed
  32.              LEFT JOIN (
  33.                          SELECT
  34.                            DISTINCT
  35.                            pgpa.id_name AS pgpa_id_name
  36.                          FROM users
  37.                            INNER JOIN user_permissions AS up ON up.user_id = users.id
  38.                            INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id
  39.                            INNER JOIN prescription_general_permission_actions AS pgpa
  40.                              ON pgpa.id = pgp.prescription_general_permission_action_id
  41.                          WHERE users.id = #{user_id}
  42.                        ) AS perms_create ON perms_create.pgpa_id_name = '_create'
  43.              --check if doctor_access_edit allowed
  44.              LEFT JOIN (
  45.                          SELECT
  46.                            DISTINCT
  47.                            p.id AS prescription_id
  48.                          FROM users
  49.                            INNER JOIN user_permissions AS up ON up.user_id = users.id
  50.                            INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id
  51.                            INNER JOIN prescription_general_permission_actions AS pgpa
  52.                              ON pgpa.id = pgp.prescription_general_permission_action_id
  53.                            CROSS JOIN prescriptions AS p
  54.                            LEFT JOIN user_business_units AS ubu ON ubu.user_id = users.id
  55.                          WHERE users.id = #{user_id} AND pgpa.id_name = '_doctor_access_edit' AND ( users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id )
  56.                        ) AS perms_doctor_access_edit ON perms_doctor_access_edit.prescription_id = prescriptions.id
  57.              --check if cancel allowed
  58.              LEFT JOIN (
  59.                          SELECT
  60.                            DISTINCT
  61.                            p.id AS prescription_id
  62.                          FROM users
  63.                            INNER JOIN user_permissions AS up ON up.user_id = users.id
  64.                            INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id
  65.                            INNER JOIN prescription_general_permission_actions AS pgpa
  66.                              ON pgpa.id = pgp.prescription_general_permission_action_id
  67.                            INNER JOIN user_options AS uo ON uo.id = users.user_option_id
  68.                            INNER JOIN prescription_statuses AS ps ON ps.id = pgp.prescription_status_id
  69.                            INNER JOIN prescriptions AS p ON p.status_id = ps.id
  70.                            LEFT JOIN prescription_shares AS pshare ON pshare.prescription_id = p.id
  71.                            LEFT JOIN prescription_permission_group_types AS ppgt ON ppgt.id = pgp.group_type_id
  72.                            LEFT JOIN user_business_units AS ubu ON ubu.user_id = users.id
  73.                            LEFT JOIN user_option_employees AS uoe ON uoe.user_id = users.id
  74.                          WHERE
  75.                            users.id = #{user_id} AND pgpa.id_name = '_cancel' AND (
  76.                              (ppgt.id_name = '_full' OR uo.id_name = 'all_employees') AND (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id) OR
  77.                              ppgt.id_name = '_by_access' AND (
  78.                                (uo.id_name = 'own' OR uo.id_name = 'all_employees') AND pshare.doctor_id = users.employee_id OR
  79.                                uo.id_name = 'employees_list' AND uoe.employee_id = pshare.doctor_id
  80.                              ) OR
  81.                              ppgt.id_name = '_by_doctor_prescription' AND (
  82.                                (uo.id_name = 'own' OR uo.id_name = 'all_employees') AND p.doctor_id = users.employee_id AND
  83.                                pshare.doctor_id = users.employee_id AND (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id) OR
  84.                                uo.id_name = 'employees_list' AND p.doctor_id = uoe.employee_id AND pshare.doctor_id = uoe.employee_id AND
  85.                                (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id)
  86.                              )
  87.                            )
  88.                        ) AS perms_cancel ON perms_cancel.prescription_id = prescriptions.id
  89.              --check if edit allowed
  90.              LEFT JOIN (
  91.                          SELECT
  92.                            DISTINCT
  93.                            p.id AS prescription_id
  94.                          FROM users
  95.                            INNER JOIN user_permissions AS up ON up.user_id = users.id
  96.                            INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id
  97.                            INNER JOIN prescription_general_permission_actions AS pgpa
  98.                              ON pgpa.id = pgp.prescription_general_permission_action_id
  99.                            INNER JOIN user_options AS uo ON uo.id = users.user_option_id
  100.                            INNER JOIN prescription_statuses AS ps ON ps.id = pgp.prescription_status_id
  101.                            INNER JOIN prescriptions AS p ON p.status_id = ps.id
  102.                            LEFT JOIN prescription_shares AS pshare ON pshare.prescription_id = p.id
  103.                            LEFT JOIN prescription_permission_group_types AS ppgt ON ppgt.id = pgp.group_type_id
  104.                            LEFT JOIN user_business_units AS ubu ON ubu.user_id = users.id
  105.                            LEFT JOIN user_option_employees AS uoe ON uoe.user_id = users.id
  106.                          WHERE
  107.                            users.id = #{user_id} AND pgpa.id_name = '_edit' AND (
  108.                              (ppgt.id_name = '_full' OR uo.id_name = 'all_employees') AND (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id) OR
  109.                              ppgt.id_name = '_by_access' AND (
  110.                                (uo.id_name = 'own' OR uo.id_name = 'all_employees') AND pshare.doctor_id = users.employee_id OR
  111.                                uo.id_name = 'employees_list' AND uoe.employee_id = pshare.doctor_id
  112.                              ) OR
  113.                              ppgt.id_name = '_by_doctor_prescription' AND (
  114.                                (uo.id_name = 'own' OR uo.id_name = 'all_employees') AND p.doctor_id = users.employee_id AND
  115.                                pshare.doctor_id = users.employee_id AND (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id) OR
  116.                                uo.id_name = 'employees_list' AND p.doctor_id = uoe.employee_id AND pshare.doctor_id = uoe.employee_id AND
  117.                                (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id)
  118.                              )
  119.                            )
  120.                        ) AS perms_edit ON perms_edit.prescription_id = prescriptions.id
  121.              --check if view allowed
  122.              LEFT JOIN (
  123.                          SELECT
  124.                            DISTINCT
  125.                            p.id AS prescription_id
  126.                          FROM users
  127.                            INNER JOIN user_permissions AS up ON up.user_id = users.id
  128.                            INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id
  129.                            INNER JOIN prescription_general_permission_actions AS pgpa
  130.                              ON pgpa.id = pgp.prescription_general_permission_action_id
  131.                            INNER JOIN user_options AS uo ON uo.id = users.user_option_id
  132.                            INNER JOIN prescription_statuses AS ps ON ps.id = pgp.prescription_status_id
  133.                            INNER JOIN prescriptions AS p ON p.status_id = ps.id
  134.                            LEFT JOIN patients ON patients.id = p.patient_id
  135.                            LEFT JOIN prescription_shares AS pshare ON pshare.prescription_id = p.id
  136.                            LEFT JOIN prescription_permission_group_types AS ppgt ON ppgt.id = pgp.group_type_id
  137.                            LEFT JOIN user_business_units AS ubu ON ubu.user_id = users.id
  138.                            LEFT JOIN user_option_employees AS uoe ON uoe.user_id = users.id
  139.                          WHERE
  140.                            users.id = #{user_id} AND pgpa.id_name = '_view' AND (
  141.                              patients.patient_consent = 1 OR
  142.                              (ppgt.id_name = '_full' OR uo.id_name = 'all_employees') AND (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id) OR
  143.                              ppgt.id_name = '_by_access' AND (
  144.                                (uo.id_name = 'own' OR uo.id_name = 'all_employees') AND pshare.doctor_id = users.employee_id OR
  145.                                uo.id_name = 'employees_list' AND uoe.employee_id = pshare.doctor_id
  146.                              ) OR
  147.                              ppgt.id_name = '_by_doctor_prescription' AND (
  148.                                (uo.id_name = 'own' OR uo.id_name = 'all_employees') AND p.doctor_id = users.employee_id AND
  149.                                  pshare.doctor_id = users.employee_id AND (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id) OR
  150.                                uo.id_name = 'employees_list' AND p.doctor_id = uoe.employee_id AND pshare.doctor_id = uoe.employee_id AND
  151.                                (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id)
  152.                              )
  153.                            )
  154.                        ) AS perms_view ON perms_view.prescription_id = prescriptions.id
  155.              --check if manual_cancel allowed
  156.              LEFT JOIN (
  157.                          SELECT
  158.                            DISTINCT
  159.                            p.id AS prescription_id
  160.                          FROM users
  161.                            INNER JOIN user_permissions AS up ON up.user_id = users.id
  162.                            INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id
  163.                            INNER JOIN prescription_general_permission_actions AS pgpa
  164.                              ON pgpa.id = pgp.prescription_general_permission_action_id
  165.                            CROSS JOIN prescriptions AS p
  166.                            LEFT JOIN user_business_units AS ubu ON ubu.user_id = users.id
  167.                          WHERE users.id = #{user_id} AND pgpa.id_name = '_manual_cancel' AND ( users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id )
  168.                        ) AS perms_manual_cancel ON perms_manual_cancel.prescription_id = prescriptions.id
  169.  
  170.      "
  171.  
  172.     columns = '
  173.              CASE WHEN perms_activate.prescription_id IS NOT NULL THEN 1 ELSE 0 END AS _activate,
  174.              CASE WHEN perms_access.pgpa_id_name IS NOT NULL THEN 1 ELSE 0 END AS _access,
  175.              CASE WHEN perms_create.pgpa_id_name IS NOT NULL THEN 1 ELSE 0 END AS _create,
  176.              CASE WHEN perms_cancel.prescription_id IS NOT NULL THEN 1 ELSE 0 END AS _cancel,
  177.              CASE WHEN perms_edit.prescription_id IS NOT NULL THEN 1 ELSE 0 END AS _edit,
  178.              CASE WHEN perms_view.prescription_id IS NOT NULL THEN 1 ELSE 0 END AS _view,
  179.              CASE WHEN perms_doctor_access_edit.prescription_id IS NOT NULL THEN 1 ELSE 0 END AS _doctor_access_edit,
  180.              CASE WHEN perms_manual_cancel.prescription_id IS NOT NULL THEN 1 ELSE 0 END AS _manual_cancel'
  181.  
  182.  
  183.     { joins: joins, columns: columns }
  184.  
  185.   end
  186.  
  187.   def self.get_only_own(user_id, remote_ip)
  188.     user = User.find(user_id)
  189.     user.request_ip = remote_ip
  190.  
  191.     business_units_by_ip =
  192.       if user.business_and_legal_unit_by_ip.present?
  193.         if bu_unit = user.business_and_legal_unit_by_ip[:business_unit]
  194.           bu_unit[:id]
  195.         end
  196.       else
  197.         ''
  198.       end
  199.  
  200.     join_string = "LEFT JOIN (
  201.              SELECT
  202.                DISTINCT
  203.                p.id AS prescription_id
  204.              FROM users
  205.                INNER JOIN user_permissions AS up ON up.user_id = users.id
  206.                INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id
  207.                INNER JOIN user_options AS uo ON uo.id = users.user_option_id
  208.                INNER JOIN prescription_statuses AS ps ON ps.id = pgp.prescription_status_id
  209.                INNER JOIN prescriptions AS p ON p.status_id = ps.id
  210.                LEFT JOIN prescription_shares AS pshare ON pshare.prescription_id = p.id
  211.                LEFT JOIN user_option_employees AS uoe ON uoe.user_id = users.id
  212.              WHERE
  213.                users.id = #{user_id} AND(
  214.                    (uo.id_name = 'own' OR uo.id_name = 'all_employees') AND pshare.doctor_id = users.employee_id AND p.doctor_id = users.employee_id OR
  215.                    uo.id_name = 'employees_list' AND uoe.employee_id = pshare.doctor_id AND p.doctor_id = uoe.employee_id
  216.                )
  217.            ) AS own_only ON own_only.prescription_id = prescriptions.id"
  218.  
  219.     { filter_string: "prescriptions.business_unit_id = N'#{business_units_by_ip}' AND own_only.prescription_id IS NOT NULL", join_string: join_string  }
  220.   end
  221.  
  222.   def self.user_is_allowed(user_id, action_name, prescription_id = nil, is_view = false)
  223.     if prescription_id.nil?
  224.       User.
  225.           joins('INNER JOIN user_permissions AS up ON up.user_id = users.id').
  226.           joins('INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id').
  227.           joins('INNER JOIN prescription_general_permission_actions AS pgpa ON pgpa.id = pgp.prescription_general_permission_action_id').
  228.           where(id: user_id).
  229.           where('pgpa.id_name = :action_name', action_name: action_name).
  230.           select('pgpa.id_name').
  231.           distinct.
  232.           any?
  233.     elsif is_view
  234.       User.
  235.           joins('INNER JOIN user_permissions AS up ON up.user_id = users.id').
  236.           joins('INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id').
  237.           joins('INNER JOIN prescription_general_permission_actions AS pgpa ON pgpa.id = pgp.prescription_general_permission_action_id').
  238.           joins('INNER JOIN user_options AS uo ON uo.id = users.user_option_id').
  239.           joins('INNER JOIN prescription_statuses AS ps ON ps.id = pgp.prescription_status_id').
  240.           joins('INNER JOIN prescriptions AS p ON p.status_id = ps.id').
  241.           joins('LEFT JOIN patients ON patients.id = p.patient_id').
  242.           joins('LEFT JOIN prescription_shares AS pshare ON pshare.prescription_id = p.id').
  243.           joins('LEFT JOIN prescription_permission_group_types AS ppgt ON ppgt.id = pgp.group_type_id').
  244.           joins('LEFT JOIN user_business_units AS ubu ON ubu.user_id = users.id').
  245.           joins('LEFT JOIN user_option_employees AS uoe ON uoe.user_id = users.id').
  246.           where(id: user_id).
  247.           where('pgpa.id_name = :action_name', action_name: action_name).
  248.           where('p.id = :prescription_id', prescription_id: prescription_id).
  249.           where("patients.patient_consent = 1 OR
  250.                    (ppgt.id_name = '_full' OR uo.id_name = 'all_employees') AND (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id) OR
  251.                    ppgt.id_name = '_by_access' AND (
  252.                                                     (uo.id_name = 'own' OR uo.id_name = 'all_employees') AND pshare.doctor_id = users.employee_id OR
  253.                                                     uo.id_name = 'employees_list' AND uoe.employee_id = pshare.doctor_id
  254.                                                     ) OR
  255.                    ppgt.id_name = '_by_doctor_prescription' AND (
  256.                                                                  (uo.id_name = 'own' OR uo.id_name = 'all_employees') AND p.doctor_id = users.employee_id AND
  257.                                                                  pshare.doctor_id = users.employee_id AND (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id) OR
  258.                                                                  uo.id_name = 'employees_list' AND p.doctor_id = uoe.employee_id AND pshare.doctor_id = uoe.employee_id AND
  259.                                                                  (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id)
  260.                                                                  )").
  261.           select('p.id').
  262.           distinct.
  263.           any?
  264.  
  265.     else
  266.       if action_name == '_activate' || action_name == '_doctor_access_edit'
  267.         User.
  268.             joins('INNER JOIN user_permissions AS up ON up.user_id = users.id').
  269.             joins('INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id').
  270.             joins('INNER JOIN prescription_general_permission_actions AS pgpa ON pgpa.id = pgp.prescription_general_permission_action_id').
  271.             joins('CROSS JOIN prescriptions AS p').
  272.             joins('LEFT JOIN user_business_units AS ubu ON ubu.user_id = users.id').
  273.             where(id: user_id).
  274.             where('pgpa.id_name = :action_name', action_name: action_name).
  275.             where('users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id').
  276.             where('p.id = :prescription_id', prescription_id: prescription_id).
  277.             select('p.id').
  278.             distinct.
  279.             any?
  280.       else
  281.         User.
  282.             joins('INNER JOIN user_permissions AS up ON up.user_id = users.id').
  283.             joins('INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id').
  284.             joins('INNER JOIN prescription_general_permission_actions AS pgpa ON pgpa.id = pgp.prescription_general_permission_action_id').
  285.             joins('INNER JOIN user_options AS uo ON uo.id = users.user_option_id').
  286.             joins('INNER JOIN prescription_statuses AS ps ON ps.id = pgp.prescription_status_id').
  287.             joins('INNER JOIN prescriptions AS p ON p.status_id = ps.id').
  288.             joins('LEFT JOIN prescription_shares AS pshare ON pshare.prescription_id = p.id').
  289.             joins('LEFT JOIN prescription_permission_group_types AS ppgt ON ppgt.id = pgp.group_type_id').
  290.             joins('LEFT JOIN user_business_units AS ubu ON ubu.user_id = users.id').
  291.             joins('LEFT JOIN user_option_employees AS uoe ON uoe.user_id = users.id').
  292.             where(id: user_id).
  293.             where('pgpa.id_name = :action_name', action_name: action_name).
  294.             where('p.id = :prescription_id', prescription_id: prescription_id).
  295.             where("
  296.                    (ppgt.id_name = '_full' OR uo.id_name = 'all_employees') AND (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id) OR
  297.                    ppgt.id_name = '_by_access' AND (
  298.                                                     (uo.id_name = 'own' OR uo.id_name = 'all_employees') AND pshare.doctor_id = users.employee_id OR
  299.                                                     uo.id_name = 'employees_list' AND uoe.employee_id = pshare.doctor_id
  300.                                                     ) OR
  301.                    ppgt.id_name = '_by_doctor_prescription' AND (
  302.                                                                  (uo.id_name = 'own' OR uo.id_name = 'all_employees') AND p.doctor_id = users.employee_id AND
  303.                                                                  pshare.doctor_id = users.employee_id AND (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id) OR
  304.                                                                  uo.id_name = 'employees_list' AND p.doctor_id = uoe.employee_id AND pshare.doctor_id = uoe.employee_id AND
  305.                                                                  (users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id)
  306.                                                                  )").
  307.             select('p.id').
  308.             distinct.
  309.             any?
  310.       end
  311.     end
  312.  
  313.   end
  314.  
  315.   def self.prescription_json_object
  316.     {
  317.         user_name: { only: [:id, :name] },
  318.         medical_card: { only: [:id, :number] },
  319.         patient: { only: [:id, :name, :pin ] },
  320.         prescription_preliminary_icd10s: {only: [ :id, :icd10_id], include: { icd10: { only: [:id, :name, :code] }}},
  321.         prescription_type: { only: [:id, :name, :id_name]},
  322.         prescription_medications: {
  323.           only: [:id, :quantity, :pharmacy_medication_id, :method_of_use, :need_recipe, :print_title_by_market_name, :recipe_number, :recipe_date, :valid_until, :dose, :form, :can_change_dose,
  324.                  :transferred_to_paper, :transferred_count, :cancelled, :cancelled_count, :recipe_generated_by_clinic, :recipe_number],
  325.           include: { pharmacy_medication: { only: [:id, :name] },
  326.                      prescription_appointment_type: { only: [:id, :name] }
  327.           },
  328.           methods: [:get_moh_integration]
  329.         },
  330.         prescription_products: { only: [ :id, :code_id, :code_type, :other_business_unit, :business_unit_id, :product_id ], include: { product: { only: [:id, :name] }, code: {only: [:id, :name] } }, methods: [:business_unit]},
  331.         status: { only: [ :id, :name, :id_name]},
  332.         prescription_shares: { only: [ :id, :doctor_id, :created_at ] }
  333.     }
  334.   end
  335.  
  336.   def self.get_ncsp_lab_ncsp_elements(filter)
  337.     sql = <<~SQL
  338.       SELECT (CAST(id AS NVARCHAR(16)) + '_' + type) AS item_id, id, name, type
  339.         FROM (
  340.                SELECT id, name, 'NcspElement' AS type, code
  341.                FROM ncsp_elements
  342.                WHERE mark_for_deletion = 0 AND (is_group = 0 OR group_available = 1)
  343.                UNION ALL
  344.                SELECT id, name, 'Lab' AS type, code
  345.                FROM labs
  346.                WHERE mark_for_deletion = 0 AND (is_group = 0 OR group_available = 1)
  347.               )
  348.           AS codes
  349.         WHERE name LIKE N'%#{filter[:name]}%'
  350.         ORDER BY CASE WHEN type = 'NcspElement' THEN 1
  351.                       WHEN type = 'Lab' THEN 2
  352.                       ELSE 3 END, code, name
  353.       OFFSET #{ (filter[:page] - 1) * filter[:page_limit] } ROWS FETCH NEXT #{ filter[:page_limit] } ROWS ONLY
  354.     SQL
  355.  
  356.     Ncsp.find_by_sql(sql)
  357.  
  358.   end
  359.  
  360.   def self.get_business_units(filter)
  361.     base_name = Rails.configuration.database_configuration['hr_backend']['database']
  362.     table_name = '_' + TABLE['Справочник.Подразделения']
  363.     code_id = filter[:code_id]
  364.     code_table = filter[:code_type].tableize
  365.       sql = <<~SQL
  366.           SELECT DISTINCT business_unit_id, business_unit._Description AS name
  367.           FROM business_unit_settings
  368.           LEFT JOIN [#{base_name}].[dbo].[#{table_name}] AS business_unit ON convert(char(34), business_unit._IDRRef,1) = business_unit_settings.business_unit_id
  369.           WHERE price_type_id IN (
  370.                 SELECT DISTINCT price_type_id
  371.                 FROM product_prices
  372.                 INNER JOIN products ON products.id = product_prices.product_id
  373.                 LEFT JOIN ncsps ON ncsps.id = products.ncsp_id
  374.                 LEFT JOIN labs ON labs.id = products.lab_id
  375.                 LEFT JOIN ncsp_analytics AS ncsp_many ON ncsp_many.id = products.ncsp_analytic_id
  376.                 LEFT JOIN ncsp_analytics_elements ON ncsp_many.id = ncsp_analytics_elements.ncsp_analytic_id
  377.                 LEFT JOIN ncsp_elements ON ncsp_elements.id = ncsp_analytics_elements.ncsp_element_id
  378.                 INNER JOIN (
  379.                               SELECT MAX(record_date) AS r_date, price_type_id AS price_type, product_id AS product
  380.                               FROM product_prices
  381.                               WHERE record_date <= '#{filter[:prescription_date].to_s(:db)}'
  382.                               GROUP BY price_type_id, product_id
  383.                            ) AS a ON price_type_id = a.price_type AND product_id = a.product AND record_date = a.r_date
  384.                 WHERE products.mark_for_deletion = 0 AND #{code_table}.id = #{code_id} AND product_prices.price_not_used = 0
  385.                 ) AND business_unit._Description LIKE N'%#{filter[:name]}%'
  386.       ORDER BY business_unit_id
  387.       OFFSET #{ (filter[:page] - 1) * filter[:page_limit]} ROWS FETCH NEXT #{filter[:page_limit]} ROWS ONLY
  388.       SQL
  389.  
  390.     BusinessUnitSetting.find_by_sql(sql)
  391.  
  392.   end
  393.  
  394.   def self.get_products(filter)
  395.     code_id = filter[:code_id]
  396.     code_table = filter[:code_type].tableize
  397.     sql = <<~SQL
  398.       SELECT *
  399.       FROM products
  400.         INNER JOIN
  401.         (
  402.           SELECT
  403.             DISTINCT products.id, product_prices.price_type_id
  404.           FROM product_prices
  405.             INNER JOIN products ON products.id = product_prices.product_id
  406.             LEFT JOIN ncsps ON ncsps.id = products.ncsp_id
  407.             LEFT JOIN labs ON labs.id = products.lab_id
  408.             LEFT JOIN ncsp_analytics AS ncsp_many ON ncsp_many.id = products.ncsp_analytic_id
  409.             LEFT JOIN ncsp_analytics_elements ON ncsp_many.id = ncsp_analytics_elements.ncsp_analytic_id
  410.             LEFT JOIN ncsp_elements ON ncsp_elements.id = ncsp_analytics_elements.ncsp_element_id
  411.             INNER JOIN (
  412.                          SELECT
  413.                            MAX(record_date) AS r_date,
  414.                            price_type_id AS price_type,
  415.                            product_id AS product
  416.                          FROM product_prices
  417.                          WHERE record_date <= '#{filter[:prescription_date].to_s(:db)}'
  418.                          GROUP BY price_type_id, product_id
  419.                        ) AS a ON price_type_id = a.price_type AND product_id = a.product AND record_date = a.r_date
  420.               WHERE products.mark_for_deletion = 0 AND #{code_table}.id = #{code_id} AND product_prices.price_not_used = 0
  421.         ) AS priced_products ON priced_products.id = products.id
  422.       WHERE priced_products.price_type_id IN (
  423.         SELECT price_type_id
  424.         FROM business_unit_settings
  425.         WHERE business_unit_id = '#{filter[:business_unit_id]}'
  426.       ) AND name LIKE N'%#{filter[:name]}%'
  427.       ORDER BY products.id
  428.       OFFSET #{ (filter[:page] - 1) * filter[:page_limit]} ROWS FETCH NEXT #{filter[:page_limit]} ROWS ONLY
  429.     SQL
  430.  
  431.     Product.find_by_sql(sql)
  432.  
  433.   end
  434.  
  435.   def self.get_prescription_shares(prescription_id)
  436.  
  437.     base_name = Rails.configuration.database_configuration['hr_backend']['database']
  438.     table_name_doctor = '_' + TABLE['Справочник.Сотрудники']
  439.  
  440.     data = PrescriptionShare.
  441.         joins("LEFT JOIN [#{base_name}].[dbo].[#{table_name_doctor}] AS doctor ON convert(char(34), doctor._IDRRef,1) = prescription_shares.doctor_id").
  442.         where(prescription_id: prescription_id).as_json(
  443.         only: [:id, :prescription_id, :doctor_id, :created_at],
  444.         include: {user_name: { only: [:id, :name]} },
  445.         methods: [:doctor]
  446.         )
  447.  
  448.     { data: data }
  449.   end
  450.  
  451.   def self.add_prescription_share(prescription_id, doctor_ids, user_id)
  452.     ActiveRecord::Base.transaction do
  453.       doctor_ids.each do |id|
  454.         next if PrescriptionShare.where(prescription_id: prescription_id, doctor_id: id).any?
  455.         PrescriptionShare.create!(prescription_id: prescription_id, doctor_id: id, created_by: user_id)
  456.       end
  457.     end
  458.     { result: 'ok' }
  459.   rescue
  460.     { result: 'failed' }
  461.   end
  462.  
  463.   def self.remove_prescription_share(prescription_id, doctor_ids)
  464.     ActiveRecord::Base.transaction do
  465.       PrescriptionShare.where(prescription_id: prescription_id, doctor_id: doctor_ids).delete_all
  466.     end
  467.     { result: 'ok' }
  468.   rescue
  469.     { result: 'failed' }
  470.   end
  471.  
  472.   def self.remove_prescription_share_by_id(prescription_share_id)
  473.     ActiveRecord::Base.transaction do
  474.       PrescriptionShare.where(id: prescription_share_id).delete_all
  475.     end
  476.     { result: 'ok' }
  477.   rescue
  478.     { result: 'failed' }
  479.   end
  480.  
  481.   def self.check_moh_sync(prescription)
  482.     if self.prescription_sync_done(prescription)
  483.       # Rails.logger.warn("checking sync time ")
  484.       seconds_to_wait = self.sync_time_left(prescription)
  485.       if seconds_to_wait > 0
  486.         # Rails.logger.warn("ERROR - seconds to wait #{seconds_to_wait}")
  487.         prescription.errors[:base] << I18n.t("wait_for_sync", seconds: (seconds_to_wait.to_int).to_s)
  488.         return  { error: prescription.errors }
  489.       end
  490.     else
  491.       # Rails.logger.warn("prescription sync not done ")
  492.       prescription.errors[:base] << I18n.t('not_all_medicament_in_sync')
  493.       return  { error: prescription.errors }
  494.     end
  495.   end
  496.  
  497.   def self.check_sync(prescription)
  498.     unless prescription.transferred_to_paper
  499.       result = check_moh_sync(prescription)
  500.       if result.present?
  501.         return  { error: prescription.errors }
  502.       end
  503.     end
  504.  
  505.     moh_integration = IntegrationService.get_enum('moh').id
  506.     prescription_medications = prescription.prescription_medications.where(need_recipe: 1, cancelled: 0).select('prescription_medications.*, medication_integrations.integration_status_id, medication_integrations.rec_n')
  507.                                    .joins("LEFT JOIN medication_integrations ON medication_integrations.prescription_medication_id = prescription_medications.id AND medication_integrations.integration_service_id = #{moh_integration.to_s}")
  508.  
  509.     has_prescription_medication = false
  510.     if prescription_medications.detect{|e| e.need_recipe}
  511.       has_prescription_medication = true
  512.     end
  513.     unless has_prescription_medication
  514.       prescription.errors[:base] << I18n.t('no_recipe_needed')
  515.  
  516.       return { error: prescription.errors }
  517.     end
  518.  
  519.     nil
  520.   end
  521.  
  522.   def self.transfer_to_paper(prescription, current_user)
  523.  
  524.     result =  self.check_sync(prescription)
  525.     if result.present?
  526.         return { error: prescription.errors } #added return errors because at the end of this method someone returned nil (instead of prescription)
  527.     end
  528.  
  529.     integration_id = IntegrationService.find_by(id_name: 'moh').try('id')
  530.     integration_status_id = IntegrationStatus.find_by(id_name: 'success').try('id')
  531.  
  532.     medication_for_tranfer = prescription.prescription_medications
  533.                                  .joins("LEFT JOIN medication_integrations ON prescription_medications.id = medication_integrations.prescription_medication_id
  534.                                                      AND integration_service_id = #{integration_id}")
  535.                                  .where('prescription_medications.need_recipe = 1 AND prescription_medications.transferred_to_paper = 0 AND prescription_medications.cancelled = 0')
  536.                                  .select('prescription_medications.id,
  537.                                          prescription_medications.quantity,
  538.                                          prescription_medications.recipe_number,
  539.                                          prescription_medications.transferred_to_paper,
  540.                                          prescription_medications.prescription_appointment_type_id,
  541.                                          prescription_medications.recipe_date,
  542.                                          prescription_medications.valid_until,
  543.                                          medication_integrations.rec_n,
  544.                                          medication_integrations.unid,
  545.                                          medication_integrations.integration_status_id')
  546.                                  .order("CASE WHEN medication_integrations.integration_status_id = #{integration_status_id} THEN 0 ELSE 1 END")
  547.  
  548.     medication_with_success = []
  549.     medication_for_tranfer.each do |medication|
  550.       if medication['integration_status_id'] == integration_status_id
  551.         medication_with_success << {medicament: medication, rec_n: medication['rec_n'], unid: medication['unid']}
  552.       else
  553.         begin
  554.           ActiveRecord::Base.transaction do
  555.             PrescriptionNumerator.generate_prescription_number(prescription, medication)
  556.             medication.update!(transferred_to_paper: true, transferred_count: medication['quantity'], recipe_generated_by_clinic: true)
  557.             set_transferred_to_paper_in_prescription(prescription) if medication_with_success.empty?
  558.             #call moh integration for create_prescription_copy, rabbit mq
  559.             Integrations::Moh.call_prescription_copy(medication.id, prescription.confirmation_user_id)
  560.           end
  561.         rescue => e
  562.           Rails.logger.warn("ERROR - transfer_to_paper_not_sync: #{e}")
  563.           return { error: prescription.errors }
  564.         end
  565.       end
  566.     end
  567.  
  568.     unless medication_with_success.empty?
  569.       moh_service_result = get_recipe_from_moh(prescription, medication_with_success)
  570.  
  571.       if moh_service_result[:errs].present?
  572.         prescription.errors[:base] << moh_service_result[:errs]
  573.         return { error: prescription.errors }
  574.       end
  575.  
  576.       operation_type_id = MedicamentSynchronizationOperation.find_by(id_name: 'transfer_to_paper').try('id')
  577.       integration_status_id = IntegrationStatus.find_by(id_name: 'needed').try('id')
  578.       integration_service_id = IntegrationService.find_by(id_name: 'moh').try('id')
  579.  
  580.       moh_service_result[:data].each_with_index do |med_el, index|
  581.         begin
  582.           ActiveRecord::Base.transaction do
  583.             if med_el[:status] == 'აქტიური'
  584.               create_attr = {
  585.                               operation_id: operation_type_id,
  586.                               prescription_medication: med_el[:medicament],
  587.                               cancelled_amount: med_el[:prod_left],
  588.                               synch_status_id: integration_status_id,
  589.                               integration_service_id: integration_service_id,
  590.                               doctor_id: prescription.doctor_id,
  591.                               created_at: DateTime.server_time,
  592.                               user: current_user
  593.                             }
  594.               medicament_synchronization_log = MedicamentSynchronizationLog.create!(create_attr)
  595.  
  596.               result = materialize_recipe_from_moh(prescription, med_el[:rec_n], medicament_synchronization_log)
  597.               if result[:errs].present?
  598.                 prescription.errors[:base] << result[:errs]
  599.                 return { error: prescription.errors }
  600.               end
  601.             end
  602.  
  603.             prescription_medication = med_el[:medicament]
  604.             prescription_medication.update!(transferred_to_paper: true, transferred_count: med_el[:prod_left])
  605.             set_transferred_to_paper_in_prescription(prescription) if index == (moh_service_result[:data].length - 1)
  606.           end
  607.         rescue => e
  608.           Rails.logger.warn("ERROR - transfer_to_paper_sync: #{e}")
  609.           prescription.errors[:base] << I18n.t('error_in_moh_transfer_to_paper')
  610.           return { error: prescription.errors }
  611.         end
  612.       end
  613.     end
  614.  
  615.     nil
  616.   end
  617.  
  618.   def self.set_transferred_to_paper_in_prescription(prescription)
  619.  
  620.     unless PrescriptionMedication.where(prescription: prescription, need_recipe: 1, transferred_to_paper: 0, cancelled: 0).any?
  621.       prescription.update!(transferred_to_paper: true)
  622.     end
  623.   end
  624.  
  625.   def self.prescription_data(id, prescription_medication_ids, prescription)
  626.     #used to be generate_medication_number
  627.  
  628.     # prescription = Prescription.find(id)
  629.     # result =  self.check_sync(prescription)
  630.     # unless result.nil?
  631.     #   return result
  632.     # end
  633.     # sync_status = IntegrationStatus.get_enum('success').id
  634.     moh_integration = IntegrationService.get_enum('moh').id
  635.     prescription_medications = PrescriptionMedication.where(:id => prescription_medication_ids, cancelled: false).select('prescription_medications.*, medication_integrations.integration_status_id, medication_integrations.rec_n')
  636.                                    .joins("LEFT JOIN medication_integrations ON medication_integrations.prescription_medication_id = prescription_medications.id AND medication_integrations.integration_service_id = #{moh_integration.to_s}")
  637.  
  638.     has_prescription_medication = false
  639.  
  640.  
  641.     # if prescription_medications.detect{|e| e.integration_status_id != sync_status}
  642.     #   prescription.errors[:base] << 'მედიკამენტის სინქრონიზაცია პროცესშია. სცადეთ რეცეპტის ბეჭდვა მოგვიანებით'
  643.     #   return { error: prescription.errors }
  644.     # end
  645.     #
  646.     if prescription_medications.detect{|e| e.need_recipe}
  647.       has_prescription_medication = true
  648.     end
  649.     unless has_prescription_medication
  650.       prescription.errors[:base] << I18n.t('no_recipe_needed')
  651.       return { error: prescription.errors }
  652.     end
  653.  
  654.     # ActiveRecord::Base.transaction do
  655.     #   prescription_medications.each do |prescription_medication|
  656.     #     PrescriptionNumerator.generate_prescription_number(prescription, prescription_medication)
  657.     #   end
  658.     # end
  659.  
  660.     base_name = Rails.configuration.database_configuration['hr_backend']['database']
  661.     table_name = "_#{ TABLE['Справочник.Подразделения'] }"
  662.     doctor_table_name  = "_#{ TABLE['Справочник.Сотрудники'] }"
  663.     doctor_pin_column = "_#{ COLUMN['Справочник.Сотрудники.ЛичныйНомер'] }"
  664.     description_column = COLUMN["Справочник.Подразделения.ОфициальноеНазвание"]
  665.  
  666.     prescription_info = Prescription.
  667.           select("legal_unit._#{description_column} as legal_unit_name,
  668.            doctor._Description as doctor_name,
  669.            doctor.#{ doctor_pin_column } as doctor_pid,
  670.            patients.name as patient_name,
  671.            patients.pin as patient_pin,
  672.            patients.birth_date as patient_birth_date
  673.          ").
  674.           joins('LEFT JOIN patients ON patients.id = prescriptions.patient_id').
  675.           joins("LEFT JOIN [#{ base_name }].[dbo].[#{ table_name }] as legal_unit ON convert(char(34), legal_unit._IDRRef, 1) = prescriptions.legal_unit_id").
  676.           joins("LEFT OUTER JOIN [#{base_name}].[dbo].[#{ doctor_table_name }] as doctor on convert(char(34), doctor._IDRRef, 1) = prescriptions.doctor_id").
  677.           where('prescriptions.id = ?', id).first
  678.  
  679.     # updated_prescription_medications = PrescriptionMedication.where(:id => prescription_medications.ids)
  680.  
  681.     result = {
  682.       legal_unit_name: prescription_info.legal_unit_name,
  683.       doctor_name: prescription_info.doctor_name,
  684.       doctor_pid: prescription_info.doctor_pid,
  685.       patient_pin: prescription_info.patient_pin,
  686.       patient_name: prescription_info.patient_name,
  687.       patient_birth_date: prescription_info.patient_birth_date,
  688.       prescription_medications: prescription_medications.as_json(:include => {
  689.           pharmacy_medication: { only: [:id, :name, :dose, :form, :generic], methods: [:current_name]},
  690.           prescription_appointment_type: { only: [:id, :name, :id_name] }
  691.       }, methods: [:medication_name,  :get_moh_integration])
  692.     }
  693.  
  694.     result
  695.   rescue => e
  696.     { error: prescription.errors }
  697.   end
  698.  
  699.   def self.check_permission_and_update(prescription, user_id)
  700.  
  701.     model_changes = prescription.changed
  702.     model_changes.delete('updated_by')
  703.  
  704.     prescription_status = PrescriptionStatus.find(prescription.status_id)
  705.     cancel_allowed = PrescriptionsService.user_is_allowed(user_id, '_cancel', prescription.id)
  706.     activate_allowed = PrescriptionsService.user_is_allowed(user_id, '_activate', prescription.id)
  707.     edit_allowed = PrescriptionsService.user_is_allowed(user_id, '_edit', prescription.id)
  708.  
  709.     if model_changes.size > 1 || model_changes.size == 0 || (model_changes.size == 1 && model_changes[0] != 'status_id')
  710.       unless edit_allowed
  711.         return { success: false, errs: [I18n.t(:prescription_not_allow_access)], status: :forbidden }
  712.       end
  713.  
  714.       if model_changes.include?('status_id')
  715.  
  716.         if prescription_status[:id_name] == 'canceled'
  717.           unless cancel_allowed
  718.             raise 'rollback'
  719.           end
  720.         else
  721.           unless activate_allowed
  722.             raise 'rollback'
  723.           end
  724.         end
  725.       end
  726.  
  727.       return { success: prescription.save, prescription: prescription }
  728.     end
  729.  
  730.     if model_changes[0].inquiry.status_id?
  731.       ActiveRecord::Base.transaction do
  732.         prescription.save
  733.         what_changed = prescription.what_changed?
  734.         if what_changed.changes.size > 1
  735.           unless edit_allowed
  736.             raise 'rollback'
  737.           end
  738.           return { success: true, prescription: prescription }
  739.         end
  740.  
  741.         if prescription_status[:id_name] == 'canceled'
  742.           unless cancel_allowed
  743.             raise 'rollback'
  744.           end
  745.         else
  746.           unless activate_allowed
  747.             raise 'rollback'
  748.           end
  749.         end
  750.  
  751.         { success: true, prescription: prescription }
  752.       end
  753.     end
  754.  
  755.   rescue ActiveRecord::StaleObjectError
  756.     prescription.reload
  757.  
  758.     { success: false, errs: [ I18n.t(:prescription_edited_locked) ], status: :internal_server_error }
  759.   rescue ActiveRecord::RecordNotUnique
  760.     { success: false, errs: [I18n.t('record_is_not_unique')], status: :internal_server_error}
  761.   rescue => e
  762.     if e.to_s == 'rollback'
  763.       return { success: false, errs: [I18n.t(:prescription_not_allow_access)], status: :forbidden }
  764.     else
  765.       return { success: false, errs: [e.to_s], status: :internal_server_error }
  766.     end
  767.   end
  768.  
  769.   def self.prescription_sync_done(prescription)
  770.     ActiveRecord::Base.transaction do
  771.       status_id = IntegrationStatus.get_enum('no_need').id
  772.       not_synced_medications = PrescriptionMedication.where(prescription_id: prescription.id).
  773.           select('prescription_medications.*, medication_integrations.integration_status_id, medication_integrations.rec_n')
  774.           .joins("LEFT JOIN medication_integrations
  775.                  ON medication_integrations.prescription_medication_id = prescription_medications.id")
  776.                                    .where("prescription_medications.need_recipe = 1 AND (medication_integrations.id IS NULL OR integration_status_id = #{status_id})")
  777.       if not_synced_medications.present?
  778.         # Rails.logger.warn("ERROR - not synced medications: ")
  779.         return false
  780.       end
  781.       # medications = prescription.prescription_medications
  782.       # synced = medications.inject(true) do |result, medication|
  783.       #   is_sync = (medication.need_recipe and medication.medication_integration.present? and medication.medication_integration.integration_status != 'no_need')
  784.       #   result and is_sync
  785.     end
  786.     # Rails.logger.warn("every medication is synced")
  787.     return true
  788.  
  789.   end
  790.  
  791.   def self.sync_time_left(prescription)
  792.     medication_integrations = MedicationIntegration.
  793.         joins('INNER JOIN prescription_medications ON prescription_medications.id = prescription_medication_id
  794.               INNER JOIN integration_statuses ON medication_integrations.integration_status_id = integration_statuses.id').
  795.         where("prescription_medications.prescription_id = #{prescription.id} AND integration_statuses.id_name IN ('in_progress', 'needed')").order('medication_integrations.created_at')
  796.  
  797.     if medication_integrations.present?
  798.       last_integration = medication_integrations.last
  799.       last_integration_time = last_integration.created_at
  800.       time = SystemSetting.moh_synchronize_waiting_time.try(:first).try(:number_value)
  801.       waiting_time = time.present? ? time : 120
  802.       end_time = last_integration_time + waiting_time.seconds
  803.       # Rails.logger.warn("end time is: #{end_time}")
  804.       if end_time > DateTime.server_time
  805.         return end_time - DateTime.server_time
  806.       end
  807.     end
  808.     # Rails.logger.warn("medications not present")
  809.     return 0
  810.   end
  811.  
  812.   def self.get_recipe_from_moh(prescription, object)
  813.  
  814.     errors = []
  815.  
  816.     integrated_user = MohIntegration.first_employee_moh_user(prescription.doctor_id)
  817.  
  818.     patient = Patient.find(prescription.patient_id)
  819.  
  820.     if integrated_user.present?
  821.       body = {
  822.           UserName: integrated_user.user_name,
  823.           UserPass: integrated_user.integration_password,
  824.           UserType: 0,
  825.           PatientID: patient.pin,
  826.           BDate: patient.birth_date.to_s,
  827.           Status: 1
  828.       }
  829.     else
  830.       return { errs: I18n.t('user_is_not_integrated'), status_code: 500, has_error: true }
  831.     end
  832.  
  833.     log_object = {
  834.         id: prescription.id,
  835.         type: "Prescription"
  836.     }
  837.  
  838.     result = MohIntegration.web_service(:get_recipes_by_id, body, prescription.doctor_id, log_object)
  839.     if result[:diffgram].present? && result[:diffgram][:document_element].blank?
  840.       return { errs: I18n.t('there_is_not_medicaments_for_patient'), status_code: 500, has_error: true}
  841.     elsif result[:error_message]
  842.       return { errs: result[:error_message].as_json, status_code: 500, has_error: true }
  843.     end
  844.  
  845.     result = result[:diffgram][:document_element][:recipes]
  846.  
  847.     if result.class == Hash
  848.       object.each do |obj|
  849.         if obj[:unid] == result[:unid] && obj[:rec_n] == result[:recipe_no]
  850.           obj[:prod_left] = result[:prod_left]
  851.           obj[:status] = result[:status]
  852.         end
  853.       end
  854.     elsif result.class == Array
  855.       object.each do |obj|
  856.         result.each do |result_obj|
  857.           if obj[:unid] == result_obj[:unid] && obj[:rec_n] == result_obj[:recipe_no]
  858.             obj[:prod_left] = result_obj[:prod_left]
  859.             obj[:status] = result_obj[:status]
  860.           end
  861.         end
  862.       end
  863.     end
  864.  
  865.     object.each do |obj|
  866.       unless obj[:prod_left].present?
  867.         errors << I18n.t('one_of_the_medicaments_doesnt_exist')
  868.         break
  869.       end
  870.     end
  871.  
  872.  
  873.  
  874.     if errors.present?
  875.       { errs: errors.as_json, status_code: 500, has_error: true}
  876.     else
  877.       { data: object }
  878.     end
  879.   end
  880.  
  881.   def self.materialize_recipe_from_moh(prescription, rec_no, synch_log_object)
  882.     integrated_user = MohIntegration.first_employee_moh_user(prescription.doctor_id)
  883.  
  884.     if integrated_user.present?
  885.       body = {
  886.           UserName: integrated_user.user_name,
  887.           UserPass: integrated_user.integration_password,
  888.           RecipeNo: rec_no
  889.       }
  890.     else
  891.       return { errs: I18n.t('user_is_not_integrated'), status_code: 500, has_error: true }
  892.     end
  893.  
  894.  
  895.     synch_status_id = IntegrationStatus.find_by_id_name(:in_progress).try(:id)
  896.     synch_log_object.update(synch_start_date: DateTime.server_time, synch_status_id: synch_status_id)
  897.  
  898.     log_object = {
  899.         id: prescription.id,
  900.         type: "Prescription"
  901.     }
  902.  
  903.     result = MohIntegration.web_service(:materialize_recipe, body, prescription.doctor_id, log_object)
  904.     if result.class == Hash
  905.        synch_status_id = IntegrationStatus.find_by_id_name(:error).try(:id)
  906.        error = I18n.t('moh_error_while_transferring_to_paper', error: result[:error_message] )
  907.        synch_log_object.update(error_message: error, synch_status_id: synch_status_id )
  908.        return { errs: error , status_code: 500, has_error: true }
  909.     else
  910.       result_hash = Hash.from_xml(result)
  911.       if result_hash['Result']['Status'] == "0"
  912.         synch_status_id = IntegrationStatus.find_by_id_name(:success).try(:id)
  913.         synch_log_object.update(synch_date: DateTime.server_time, synch_status_id: synch_status_id )
  914.         return { status: true , message: result_hash['Result']['Description'] }
  915.       else
  916.         synch_status_id = IntegrationStatus.find_by_id_name(:error).try(:id)
  917.         synch_log_object.update(error_message: result_hash['Result']['Description'] , synch_status_id: synch_status_id )
  918.         return { status: false, errs: result_hash['Result']['Description'] }
  919.       end
  920.     end
  921.   end
  922.  
  923.   def self.disable_recipe_in_moh(prescription, rec_no, synch_log_object)
  924.     integrated_user = MohIntegration.first_employee_moh_user(prescription.doctor_id)
  925.  
  926.     if integrated_user.present?
  927.       body = {
  928.           UserName: integrated_user.user_name,
  929.           UserPass: integrated_user.integration_password,
  930.           UserType: 0,
  931.           RecipeNo: rec_no,
  932.           DisableReason: 'reccured'
  933.       }
  934.     else
  935.       return { errs: I18n.t('user_is_not_integrated'), status_code: 500, has_error: true }
  936.     end
  937.  
  938.  
  939.     synch_status_id = IntegrationStatus.find_by_id_name(:in_progress).try(:id)
  940.     synch_log_object.update(synch_start_date: DateTime.server_time, synch_status_id: synch_status_id)
  941.  
  942.     log_object = {
  943.         id: prescription.id,
  944.         type: "Prescription"
  945.     }
  946.  
  947.     result = MohIntegration.web_service(:disable_recipe, body, prescription.doctor_id, log_object)
  948.     if result.class == Hash
  949.       synch_status_id = IntegrationStatus.find_by_id_name(:error).try(:id)
  950.       error = I18n.t('moh_error_while_transferring_to_paper', error: result[:error_message] )
  951.       synch_log_object.update(error_message: error, synch_status_id: synch_status_id )
  952.       return { errs: error , status_code: 500, has_error: true }
  953.     else
  954.       result_hash = Hash.from_xml(result)
  955.       if result_hash['Result']['Status'] == "0"
  956.         synch_status_id = IntegrationStatus.find_by_id_name(:success).try(:id)
  957.         synch_log_object.update(synch_date: DateTime.server_time, synch_status_id: synch_status_id )
  958.         return { status: true , message: result_hash['Result']['ResultValue'] }
  959.       else
  960.         synch_status_id = IntegrationStatus.find_by_id_name(:error).try(:id)
  961.         synch_log_object.update(error_message: result_hash['Result']['ResultValue'] , synch_status_id: synch_status_id )
  962.         return { status: false, errs: result_hash['Result']['ResultValue'] }
  963.       end
  964.     end
  965.   end
  966.  
  967.   def self.disable_recipe_in_gepha(prescription, recipe_no, synch_log_object)
  968.  
  969.     doctor = Employee1c.employee_info(prescription.doctor_id)
  970.  
  971.  
  972.     body = {
  973.         receptis_nomeri: recipe_no,
  974.         eq_k: 0,
  975.         eq_pn: doctor.pin
  976.     }
  977.  
  978.     synch_status_id = IntegrationStatus.find_by_id_name(:in_progress).try(:id)
  979.     synch_log_object.update(synch_start_date: DateTime.server_time, synch_status_id: synch_status_id)
  980.  
  981.     log_object = {
  982.         id: prescription.id,
  983.         type: "Prescription",
  984.         doctor_id: prescription.doctor_id
  985.     }
  986.  
  987.     result = GephaIntegration.web_service(:er_recc_gauq_wb, body, log_object)
  988.  
  989.     if result == "ok"
  990.       synch_status_id = IntegrationStatus.find_by_id_name(:success).try(:id)
  991.       synch_log_object.update(synch_date: DateTime.server_time, synch_status_id: synch_status_id )
  992.       return { status: true , message: result }
  993.     else
  994.       synch_status_id = IntegrationStatus.find_by_id_name(:error).try(:id)
  995.       error = I18n.t('moh_error_while_transferring_to_paper', error: result.class == Hash ? result[:error_message] : nil )
  996.       synch_log_object.update(error_message: result.class == Hash ? error : result, synch_status_id: synch_status_id )
  997.       return { errs: error , status_code: 500, has_error: true }
  998.     end
  999.   end
  1000.  
  1001.   def self.get_user_employees(user)
  1002.     UserOptionEmployee.select(:employee_id).where(user_id: user.id)
  1003.   end
  1004.  
  1005.   def self.collect_all_users(user_id)
  1006.     user = User.find_by_id(user_id)
  1007.     case user.user_option.id_name
  1008.       when 'employees_list'
  1009.         get_user_employees(user).pluck(:employee_id)
  1010.       when 'all_employees'
  1011.         nil
  1012.       else [user.employee_id]
  1013.     end
  1014.   end
  1015.  
  1016.   def self.is_user_eligible_doctor(user_id, doctor_id)
  1017.     my_users = collect_all_users(user_id)
  1018.     if my_users.nil?
  1019.       return true
  1020.     end
  1021.     return my_users.include? doctor_id
  1022.   end
  1023.  
  1024.   def self.manual_cancel(prescription, prescription_medication, current_user)
  1025.  
  1026.     return { success: false, errs: [I18n.t(:prescription_medication_is_cancelled)], status_code: 500 } if prescription_medication.cancelled
  1027.     return { success: false, errs: [I18n.t(:prescription_not_allow_access)], status_code: 500 } unless user_has_permission_manual_cancel(prescription, prescription_medication, current_user)
  1028.  
  1029.     result =  self.check_moh_sync(prescription)
  1030.     if result.present?
  1031.       return result
  1032.     end
  1033.  
  1034.     moh_integration = prescription_medication.get_moh_integration
  1035.     cancelled_count = prescription_medication.quantity
  1036.     if prescription_medication.transferred_to_paper
  1037.       cancelled_count = prescription_medication.transferred_count
  1038.     elsif moh_integration.present? && moh_integration.id_name == 'success'
  1039.       medication_with_success = [{medicament: prescription_medication, rec_n: moh_integration['rec_n'], unid: moh_integration['unid']}]
  1040.       moh_service_result = get_recipe_from_moh(prescription, medication_with_success)
  1041.  
  1042.       if moh_service_result[:errs].present?
  1043.         moh_service_result[:success] = false
  1044.         return moh_service_result
  1045.       end
  1046.  
  1047.       if moh_service_result[:data][0][:status] == 'აქტიური'
  1048.         operation_type_id = MedicamentSynchronizationOperation.find_by(id_name: 'cancellation').try('id')
  1049.         integration_status_id = IntegrationStatus.find_by(id_name: 'needed').try('id')
  1050.         integration_service_id = IntegrationService.find_by(id_name: 'moh').try('id')
  1051.  
  1052.         create_attr = {
  1053.             operation_id: operation_type_id,
  1054.             prescription_medication: prescription_medication,
  1055.             cancelled_amount: moh_service_result[:data][0][:prod_left],
  1056.             synch_status_id: integration_status_id,
  1057.             integration_service_id: integration_service_id,
  1058.             doctor_id: prescription.doctor_id,
  1059.             created_at: DateTime.server_time,
  1060.             user: current_user
  1061.         }
  1062.         medicament_synchronization_log = MedicamentSynchronizationLog.create!(create_attr)
  1063.  
  1064.         result = disable_recipe_in_moh(prescription, moh_service_result[:data][0][:rec_n], medicament_synchronization_log)
  1065.         if result[:errs].present?
  1066.           result[:success] = false
  1067.           return result
  1068.         end
  1069.       end
  1070.  
  1071.       cancelled_count = moh_service_result[:data][0][:prod_left]
  1072.     end
  1073.  
  1074.     prescription_medication.update!(cancelled: true, cancelled_count: cancelled_count)
  1075.     Thread.new { PrescriptionsService.manual_cancel_gepha(prescription, prescription_medication, current_user) }
  1076.  
  1077.     return { success: true, cancelled: true, cancelled_count: cancelled_count }
  1078.   end
  1079.  
  1080.   def self.user_has_permission_manual_cancel(prescription, prescription_medication, current_user)
  1081.  
  1082.     return false if prescription.status.nil? || prescription.status.id_name != 'printed' || !is_user_eligible_doctor(current_user.id, prescription.doctor_id)
  1083.  
  1084.     sql = <<~SQL
  1085.             SELECT
  1086.               DISTINCT
  1087.               p.id AS prescription_id
  1088.             FROM users
  1089.               INNER JOIN user_permissions AS up ON up.user_id = users.id
  1090.               INNER JOIN prescription_general_permissions AS pgp ON pgp.permission_id = up.permission_id
  1091.               INNER JOIN prescription_general_permission_actions AS pgpa
  1092.                 ON pgpa.id = pgp.prescription_general_permission_action_id
  1093.               CROSS JOIN prescriptions AS p
  1094.               LEFT JOIN user_business_units AS ubu ON ubu.user_id = users.id
  1095.             WHERE users.id = #{current_user.id} AND pgpa.id_name = '_manual_cancel' AND ( users.limited_by_unit = 0 OR ubu.business_unit_id = p.business_unit_id ) AND p.id = #{prescription.id}
  1096.           SQL
  1097.  
  1098.     Prescription.find_by_sql(sql).any?
  1099.  
  1100.   end
  1101.  
  1102.   def self.manual_cancel_gepha(prescription, prescription_medication, current_user)
  1103.  
  1104.     gepha_integration = prescription_medication.get_gepha_integration
  1105.     return if gepha_integration.nil? || gepha_integration.id_name != 'success'
  1106.  
  1107.     operation_type_id = MedicamentSynchronizationOperation.find_by(id_name: 'cancellation').try('id')
  1108.     integration_status_id = IntegrationStatus.find_by(id_name: 'needed').try('id')
  1109.     integration_service_id = IntegrationService.find_by(id_name: 'GEPHA').try('id')
  1110.  
  1111.     create_attr = {
  1112.         operation_id: operation_type_id,
  1113.         prescription_medication: prescription_medication,
  1114.         cancelled_amount: prescription_medication.cancelled_count,
  1115.         synch_status_id: integration_status_id,
  1116.         integration_service_id: integration_service_id,
  1117.         doctor_id: prescription.doctor_id,
  1118.         created_at: DateTime.server_time,
  1119.         user: current_user
  1120.     }
  1121.     medicament_synchronization_log = MedicamentSynchronizationLog.create!(create_attr)
  1122.     disable_recipe_in_gepha(prescription, gepha_integration.unid, medicament_synchronization_log)
  1123.  
  1124.   end
  1125. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement