แสดงกระทู้

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - cil

หน้า: [1]
1
DFM

โค๊ด: [Select]
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Drug prescription blocker)'
  ClientHeight =550
  ClientWidth = 700
  Color = clWindow
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnShow = showdata
  PixelsPerInch = 96
  TextHeight = 13
  Position = poScreenCenter

  object Panel1: TPanel
    Left = 0
    Top = 0
    Width = 700
    Height = 50
    Align = alTop
    TabOrder = 1
    BevelInner = bvNone
    BevelOuter = bvNone
    object Shape1: TShape
      Left = 0
      Top = 0
      Width = 700
      Height = 50
      Brush.Color = $4763FF
      Pen.Style = psClear
    end
    object HeadLabel: TLabel
      Left = 270
      Top = 15
      Width = 100
      Height = 25
      Caption = 'ALERT:METFORMIN'
      Alignment = taCenter
      Font.Charset = DEFAULT_CHARSET
      Font.Color = clWhite
      Font.Height = -20
      Font.Name = 'Tahoma'
      Font.Style = [fsBold]
      ParentFont = False
    end
  end

  object Panel2: TPanel
    Left = 0
    Top = 50
    Width = 700
    Height = 50
    Align = alTop
     BevelInner = bvNone
    BevelOuter = bvNone
    TabOrder = 1

    object hnLabel: TLabel
      Left = 25
      Top = 5
      Width = 16
      Height = 16
      Caption = 'HN'
      Font.Charset = DEFAULT_CHARSET
      Font.Color = clWindowText
      Font.Height = -13
      Font.Name = 'Tahoma'
      Font.Style = []
      ParentFont = False
    end
      object hntxt: TLabel
      Left = 55
      Top = 5
      Width = 14
      Height = 16
      Caption = 'hn'
      Font.Charset = DEFAULT_CHARSET
      Font.Color = clWindowText
      Font.Height = -13
      Font.Name = 'Tahoma'
      Font.Style = []
      ParentFont = False
    end
      object Label2: TLabel
      Left = 168
      Top = 5
      Width = 70
      Height = 16
      Caption = 'ª×èÍ-Ê¡ØÅ'
      Font.Charset = DEFAULT_CHARSET
      Font.Color = clWindowText
      Font.Height = -13
      Font.Name = 'Tahoma'
      Font.Style = []
      ParentFont = False
    end
      object fullnametxt: TLabel
    Left = 230
    Top = 5
    Width = 49
    Height = 16
    Caption = 'Fullname'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end

  object Label3: TLabel
    Left = 400
    Top = 5
    Width = 35
    Height = 16
    Caption = 'ÍÒÂØ'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
  object Year: TLabel
    Left = 450
    Top = 5
    Width = 22
    Height = 16
    Caption = '»Õ'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end

  object age_yLabel: TLabel
    Left = 430
    Top = 5
    Width = 22
    Height = 16
    Caption = 'Years'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
  object Label13: TLabel
    Left = 500
    Top = 5
    Width = 100
    Height = 16
    Caption = 'ÊÔ·¸Ô¡ÒÃÃÑ¡ÉÒ'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end

  object pttypetxt: TLabel
    Left = 580
    Top = 5
    Width = 50
    Height = 16
    Caption = 'Pttype'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
    object Label4: TLabel
    Left = 25
    Top = 25
    Width = 54
    Height = 16
    Caption = 'Diagnosis'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end

  object pdxLabel: TLabel
    Left = 100
    Top = 25
    Width = 20
    Height = 16
    Caption = 'pdx'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
    object Label9: TLabel
    Left = 400
    Top = 25
    Width = 108
    Height = 16
    Caption = ''
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end

  end

  object Panel3: TPanel
    Left = 0
    Top = 50
    Width = 300
    Height = 135
    Align = alTop
    TabOrder = 1
    BevelInner = bvNone
    BevelOuter = bvNone
    object label11: TLabel
      Left = 25
      Top = 0
      Width = 100
      Height = 16
      Caption = '¤èÒ·Ò§Ëéͧ»¯ÔºÑµÔ¡ÒÃ'
      Font.Charset = DEFAULT_CHARSET
      Font.Color = clWindowText
      Font.Height = -13
      Font.Name = 'Tahoma'
      Font.Style = []
      ParentFont = False
      end
    object cxGrid2: TcxGrid
          Left = 25
          Top = 25
          Width = 655
          Height = 130
          TabOrder = 6
          LookAndFeel.Kind = lfOffice11

          object cxGrid2DBTableView1: TcxGridDBTableView
            DataController.DataSource = ds
            NavigatorButtons.ConfirmDelete = False
            DataController.Summary.DefaultGroupSummaryItems = <>
            DataController.Summary.FooterSummaryItems = <>
            DataController.Summary.SummaryGroups = <>
            OptionsData.CancelOnExit = False
            OptionsData.Deleting = False
            OptionsData.DeletingConfirmation = False
            OptionsData.Editing = False
            OptionsData.Inserting = False
            OptionsSelection.CellSelect = False
            OptionsView.CellAutoHeight = True
            OptionsView.ColumnAutoWidth = True
            OptionsView.GroupByBox = False
            OptionsView.Indicator = True
            object cxGrid2DBTableView1report_date: TcxGridDBColumn
              Caption = 'Çѹ·ÕèÃÒ§ҹ'
              DataBinding.FieldName = 'report_date'
              Width = 70
            end
            object cxGrid2DBTableView1creatinine: TcxGridDBColumn
              Caption = 'Creatinine'
              DataBinding.FieldName = 'creatinine'
              Width = 70
            end
            object cxGrid2DBTableView1eGFR: TcxGridDBColumn
              Caption = 'eGFR'
              DataBinding.FieldName = 'eGFR'
              Width = 70
            end
            object cxGrid2DBTableView1CrCl: TcxGridDBColumn
              Caption = 'CrCl'
              DataBinding.FieldName = 'crcl'
              Width = 70
            end
          end
          object cxGrid2Level1: TcxGridLevel
            GridView = cxGrid2DBTableView1
          end
  end

  end
  object Panel4: TPanel
    Left = 0
    Top = 50
    Width = 300
    Height = 100
    Align = alTop
    TabOrder = 1
    BevelInner = bvNone
    BevelOuter = bvNone
    object label12: TLabel
      Left = 25
      Top = 5
      Width = 100
      Height = 16
      Caption = 'ÂÒ·ÕèÊÑè§ãªé»Ñ¨¨ØºÑ¹'
      Font.Charset = DEFAULT_CHARSET
      Font.Color = clWindowText
      Font.Height = -13
      Font.Name = 'Tahoma'
      Font.Style = []
      ParentFont = False
      end
    object cxGrid3: TcxGrid
          Left = 25
          Top = 25
          Width = 655
          Height = 75
          TabOrder = 6
          LookAndFeel.Kind = lfOffice11

          object cxGrid3DBTableView1: TcxGridDBTableView
            DataController.DataSource = ds2
            NavigatorButtons.ConfirmDelete = False
            DataController.Summary.DefaultGroupSummaryItems = <>
            DataController.Summary.FooterSummaryItems = <>
            DataController.Summary.SummaryGroups = <>
            OptionsData.CancelOnExit = False
            OptionsData.Deleting = False
            OptionsData.DeletingConfirmation = False
            OptionsData.Editing = False
            OptionsData.Inserting = False
            OptionsSelection.CellSelect = False
            OptionsView.CellAutoHeight = True
            OptionsView.ColumnAutoWidth = True
            OptionsView.GroupByBox = False
            OptionsView.Indicator = True
            object cxGrid3DBTableView1report_date: TcxGridDBColumn
              Caption = 'Çѹ·ÕèÊÑè§ãªé'
              DataBinding.FieldName = 'vstdate'
              Width = 70
            end
            object cxGrid3DBTableView1creatinine: TcxGridDBColumn
              Caption = 'ª×èÍÂÒ'
              DataBinding.FieldName = 'name'
              Width = 70
            end
            object cxGrid3DBTableView1eGFR: TcxGridDBColumn
              Caption = 'ÇÔ¸Õãªé'
              DataBinding.FieldName = 'usage_or_sp_usage'
              Width = 70
            end
            object cxGrid3DBTableView1CrCl: TcxGridDBColumn
              Caption = '¨Ó¹Ç¹'
              DataBinding.FieldName = 'qty'
              Width = 70
            end
          end
          object cxGrid3Level1: TcxGridLevel
            GridView = cxGrid3DBTableView1
          end
  end

  end

  object Panel10: TPanel
    Left = 0
    Top = 50
    Width = 300
    Height = 250
    Align = alTop
    TabOrder = 1
    BevelInner = bvNone
    BevelOuter = bvNone
      object Checkfordelete: TcxCheckBox
          Left = 150
          Top = 5
          Caption = ' ËéÒÁÊÑè§ãªé eGFR < 30 (àÅ×Í¡à¾×èÍźÃÒ¡ÒÃÂÒ)'
          TabOrder = 1
          Transparent = True
          Width = 400


      end
      object Checkhalfx1: TcxCheckBox
          Left = 150
          Top = 25
          Caption = ' .51pt  ( 1/2 àÁç´ x1 PC) '
          TabOrder = 2
          Transparent = True
          Width = 400
          Visible = False


      end
        object Check1x1: TcxCheckBox
          Left = 150
          Top = 45
          Caption = ' 11pt (1 àÁç´ x 1 PC àªéÒ)'
          TabOrder = 3
          Transparent = True
          Width = 400
          Visible = False


      end
        object Check1x2: TcxCheckBox
          Left = 150
          Top = 65
          Caption = ' 12pt (1 àÁç´ x 2 PC àªéÒ-àÂç¹)'
          TabOrder = 4
          Transparent = True
          Width = 400
          Visible = False

      end
        object Check2x1: TcxCheckBox
          Left = 150
          Top = 85
          Caption = ' 21pt (2 àÁç´ x 1 PC)'
          TabOrder = 5
          Transparent = True
          Width = 400
          Visible = False

      end
        object Check110: TcxCheckBox
          Left = 150
          Top = 105
          Caption = ' 12pt ª· (1 àÁç´ x 2 PC àªéÒ-à·Õè§)'
          TabOrder = 6
          Transparent = True
          Width = 400
          Visible = False

      end
      object Checkforconfirm: TcxCheckBox
          Left = 150
          Top = 125
          Caption = ' Â×¹Âѹ¡ÒÃÊÑè§ãªé'
          TabOrder = 7
          Transparent = True
          Width = 400

      end


      object reclabel: TLabel
      Left = 25
      Top = 5
      Width = 100
      Height = 16
      Caption = '¢¹Ò´ÂÒ'
      Font.Charset = DEFAULT_CHARSET
      Font.Color = clWindowText
      Font.Height = -13
      Font.Name = 'Tahoma'
      Font.Style = []
      ParentFont = False
      end

         object btnConfirm: TButton
    Left = 550
    Top =  120
    Width = 100
    Height = 30
    Caption = 'ºÑ¹·Ö¡'
    TabOrder = 50
    OnClick = btnConfirmClick
    end

  end



  object Panel6: TPanel
    Left = 0
    Top = 200
    Width = 300
    Height = 300
    Align = alTop
    TabOrder = 1
    BevelInner = bvNone
    BevelOuter = bvNone

    object reclabel4: TLabel
      Left = 25
      Top = 5
      Width = 100
      Height = 16
      Caption = ''
      Font.Charset = DEFAULT_CHARSET
      Font.Color = clWindowText
      Font.Height = -13
      Font.Name = 'Tahoma'
      Font.Style = []
      ParentFont = False
      end
    object btnDelete: TButton
    Left = 550
    Top = 50
    Width = 100
    Height = 30
    Caption = 'źÃÒ¡ÒÃÂÒ'
    TabOrder = 3
    OnClick = btnDeleteClick
    end


  end


object cds: TClientDataSet
  Aggregates = <>
  Params = <>
  Left = 39
  Top = 6
end
object ds: TDataSource
  DataSet = cds
  Left = 78
  Top = 6
end
object cds3: TClientDataSet
  Aggregates = <>
  Params = <>
  Left = 39
  Top = 6
end
object ds3: TDataSource
  DataSet = cds3
  Left = 78
  Top = 6
end
object cds2: TClientDataSet
  Aggregates = <>
  Params = <>
  Left = 39
  Top = 6
end
object ds2: TDataSource
  DataSet = cds2
  Left = 78
  Top = 6
end
object TempCDS: TClientDataSet
  Aggregates = <>
  Params = <>
  Left = 39
  Top = 6
end



end

2
Drugblocker

โค๊ด: [Select]
unit DB;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, ActnList, DBCtrls, dblookup, DB, DBClient, Grids,
  DBGrids, SQLDB;


  type
  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    Button1: TButton;
    Button2: TButton;
    HeadLabel: TLabel;
    hnLabel: TLabel;
    hntxt: TLabel;
    pdxLabel: TLabel;
    Label1: TLabel;
    Shape1: TShape;
    Label8: TLabel;
    Label9: TLabel;
    fullnametxt: TLabel;
    Label13: TLabel;
    pttypetxt: TLabel;
    Panel1: TPanel;
    currentlabel: TLabel;
    Panel3: TPanel;
    Year: TLabel;
    age_yLabel: TLabel;
    ListBox2: TListBox;
    Shape2: TShape;
    DBGrid1: TDBGrid;
    DBGrid2: TDBGrid;
    DBGrid3: TDBGrid;
    cds: TClientDataSet;
    ds: TDataSource;
    cds2: TClientDataSet;
    ds2: TDataSource;
    cds3: TClientDataSet;
    ds3: TDataSource;
    TempCDS: TClientDataSet;
    reclabel1: TLabel;
    reclabel2: TLabel;
    reclabel3: TLabel;
    reclabel4: TLabel;
    procedure showdata(Sender: TObject);
    procedure LoadPatientData(vn: string);
    function GetVN: string;
    procedure FormCreate(Sender: TObject);
    procedure btnConfirmClick(Sender: TObject);
  private
    procedure DisplayPatientInfo(hn, fullname, pttype: string; age_y: Integer);
    procedure LoadLabData(hn: string);
    procedure LoadPrescriptionData(vn: string);
    procedure DeleteRecord(const RecordID: string);

  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

// GetVN retrieves the VN (visit number) or uses a default if none is found.
function TForm1.GetVN: string;
begin
  Result :=   GetGlobalValue('VN');// Uncomment if GetGlobalValue is available
end;

// Display patient information on the form.
procedure TForm1.DisplayPatientInfo(hn, fullname, pttype: string; age_y: Integer);
begin
  hntxt.Caption := hn;
  fullnametxt.Caption := fullname;
  pttypetxt.Caption := pttype;
  age_yLabel.Caption := IntToStr(age_y);
end;

// LoadPatientData retrieves and displays patient information based on the VN.
procedure TForm1.LoadPatientData(vn: string);
var
  hn, fullname, pttype, age_y_str: string;
  age_y, sex: Integer;
begin
  try
    hn := getsqldata('SELECT hn FROM vn_stat WHERE vn = "' + vn + '"');
    fullname := getsqldata('SELECT CONCAT(pname, fname, " ", lname) FROM patient WHERE hn = "' + hn + '"');
    sex := StrToInt(getsqldata('SELECT sex FROM patient WHERE hn = "' + hn + '"'));
    pttype := getsqldata('SELECT p.name FROM opitemrece o INNER JOIN pttype p ON o.pttype = p.pttype WHERE vn = "' + vn + '"');
    age_y_str := getsqldata('SELECT age_y FROM vn_stat WHERE vn = "' + vn + '"');
    age_y := StrToInt(age_y_str);
    pdxLabel.Caption := getsqldata('SELECT CONCAT(vs.pdx, " : ", i.name) FROM vn_stat vs INNER JOIN icd101 i ON vs.pdx = i.code WHERE vn = "' + vn + '"');

    DisplayPatientInfo(hn, fullname, pttype, age_y);
  except
    on E: Exception do
      ShowMessage('Error loading patient data: ' + E.Message);
  end;
end;

// Load lab data into cds.
procedure TForm1.LoadLabData(hn: string);
begin
  cds.Data := hosxp_getdataset(
    'SELECT DATE_FORMAT(DATE_ADD(lh.report_date, INTERVAL 543 YEAR), ''%d/%m/%Y'') AS report_date, ' +
    'lh.vn, lh.hn, os.bw AS weight, vs.age_y AS age, vs.sex, ' +
    'MAX(CASE WHEN lo.lab_items_code = ''231'' THEN lo.lab_order_result END) AS Creatinine, ' +
    'MAX(CASE WHEN lo.lab_items_code = ''660'' THEN lo.lab_order_result END) AS eGFR, ' +
    'CASE WHEN os.bw IS NULL OR os.bw = 0 OR os.bw > 150 THEN ''-'' ' +
    'WHEN vs.sex = ''1'' THEN ROUND(((140 - vs.age_y) * os.bw) / (72 * NULLIF(MAX(CASE WHEN lo.lab_items_code = ''231'' THEN lo.lab_order_result END), 0)), 2) ' +
    'WHEN vs.sex = ''2'' THEN ROUND(0.85 * ((140 - vs.age_y) * os.bw) / (72 * NULLIF(MAX(CASE WHEN lo.lab_items_code = ''231'' THEN lo.lab_order_result END), 0)), 2) ' +
    'END AS CrCl ' +
    'FROM lab_head lh ' +
    'INNER JOIN lab_order lo ON lh.lab_order_number = lo.lab_order_number ' +
    'INNER JOIN opdscreen os ON lh.vn = os.vn ' +
    'INNER JOIN vn_stat vs ON lh.vn = vs.vn ' +
    'WHERE lh.hn = "' + hn + '" ' +
    'AND lo.lab_items_code IN (''231'', ''660'') AND lo.lab_order_result > 0 ' +
    'AND lo.lab_order_result REGEXP ''^[0-9]+\.?[0-9]*$'' ' +
    'GROUP BY lh.report_date, lh.vn, lh.hn, os.bw, vs.age_y, vs.sex ' +
    'ORDER BY lh.report_date DESC LIMIT 5'
  );
end;




// Load prescription data into cds2.
procedure TForm1.LoadPrescriptionData(vn: string);
begin
  cds2.Data := hosxp_getdataset(
    'SELECT o.vstdate, CONCAT(d.name, " ", d.strength) AS name, o.icode, ' +
    'COALESCE(du.code, CONCAT(su.name1, su.name2, su.name3)) AS usage_or_sp_usage, o.qty ' +
    'FROM opitemrece o ' +
    'INNER JOIN drugitems d ON o.icode = d.icode ' +
    'LEFT OUTER JOIN drugusage du ON o.drugusage = du.drugusage ' +
    'LEFT OUTER JOIN sp_use su ON o.sp_use = su.sp_use ' +
    'WHERE o.vn = "' + vn + '" AND o.icode = "1000210"'
  );
end;


procedure TForm1.UpdateCheckboxVisibility(LatestEGFR: Double);
begin
  if LatestEGFR < 30 then
  begin
    // Show Checkfordelete and Checkforconfirm, hide other checkboxes
    Checkfordelete.Visible := True;
    Checkforconfirm.Visible := True;
    Checkforconfirm.Top := 25;
    Checkhalfx1.Visible := False;
    Check1x1.Visible := False;
    Check1x2.Visible := False;
    Check2x1.Visible := False;
    Check110.Visible := False;
  end
  else if (LatestEGFR >= 30)  then
  begin
    // Hide Checkfordelete and Checkforconfirm, show other checkboxes
    Checkfordelete.Visible := False;
    Checkforconfirm.Visible := true;
    Checkhalfx1.Visible := True;
    Checkhalfx1.Top := 5;
    Check1x1.Top := 25;
    Check1x2.Top := 45;
    Check2x1.Top := 65;
    Check110.Top := 85;
    Checkforconfirm.Top := 105;
    Check1x1.Visible := True;
    Check1x2.Visible := True;
    Check2x1.Visible := True;
    Check110.Visible := True;
  end
  else
  begin
    // If LatestEGFR >= 45, you can customize visibility as needed
    Checkfordelete.Visible := False;
    Checkforconfirm.Visible := False;
    Checkhalfx1.Visible := False;
    Check1x1.Visible := False;
    Check1x2.Visible := False;
    Check2x1.Visible := False;
    Check110.Visible := False;
  end;
end;




procedure TForm1.showdata(Sender: TObject);
var
  vn, hn: string;
  LatestEGFR: Double;
begin

  vn := GetVN;
  LoadPatientData(vn);
  hn := getsqldata('SELECT hn FROM vn_stat WHERE vn = "' + vn + '"');





  try
    LoadLabData(hn);
    LoadPrescriptionData(vn);


    // Calculate LatestEGFR based on loaded lab data
    if cds.RecordCount > 0 then
    begin
      cds.First; // Ensure the dataset is on the first record
      LatestEGFR := cds.FieldByName('eGFR').AsFloat;
      UpdateCheckboxVisibility(LatestEGFR); // Call the procedure to update checkbox visibility
    end;

  except
    on E: Exception do
      ShowMessage('Error loading dataset: ' + E.Message);
  end;
end;


// DeleteRecord deletes a specific record from cds2.
procedure TForm1.DeleteRecord(const RecordID: string);
procedure TForm1.UpdateRecord(const drugusage: string);
**********ต้องเขียนเองครับ*****************

procedure TForm1.btnConfirmClick(Sender: TObject);
var
  CheckedCount: Integer;
begin
  CheckedCount := 0;
 
  // Count the number of checked boxes
  if Checkhalfx1.Checked then CheckedCount := CheckedCount + 1;
  if Check1x1.Checked then CheckedCount := CheckedCount + 1;
  if Check1x2.Checked then CheckedCount := CheckedCount + 1;
  if Check2x1.Checked then CheckedCount := CheckedCount + 1;
  if Check110.Checked then CheckedCount := CheckedCount + 1;
  if Checkfordelete.Checked then CheckedCount := CheckedCount + 1;
  if Checkforconfirm.Checked then CheckedCount := CheckedCount + 1;

  // If no checkboxes or more than one are checked, show a message and exit
  if CheckedCount = 0 then
  begin
    ShowMessage('Please select one option to confirm.');
    Exit;
  end
  else if CheckedCount > 1 then
  begin
    ShowMessage('Please select only one option to confirm.');
    Exit;
  end;

  // If only one checkbox is selected, perform the appropriate action
  try
    if Checkhalfx1.Checked then
      UpdateRecord('0168')
    else if Check1x1.Checked then
      UpdateRecord('0011')
    else if Check1x2.Checked then
      UpdateRecord('0022')
    else if Check2x1.Checked then
      UpdateRecord('0154')
    else if Check110.Checked then
      UpdateRecord('0317')
    else if Checkfordelete.Checked then               
      DeleteRecord('1000210')
    else if Checkforconfirm.Checked then
      Close;  // Close the form if Checkforconfirm is checked

    Close; // Close the form after action

  except
    on E: Exception do
      ShowMessage('Error confirming action: ' + E.Message);
  end;
end;




procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  // Free resources like datasets and other allocated objects
  cds.Close;
  cds2.Close;
  cds3.Close;


  // Set the form to be released from memory
  Action := caFree;
end;


end.

procedure TForm1.DeleteRecord(const RecordID: string);

**********ต้องเขียนเองครับ*************** ผมไม่มั่นใจความถูกต้อง
ใช้ cds3.Data := hosxp_getdataset('SELECT * FROM ...... ');
  cds3.Delete;
if cds3.ChangeCount > 0 then
  begin
    hosxp_updatedelta(cds3.Delta, 'SELECT * FROM ....... ');
    ShowMessage('Record deleted successfully.');
  end


procedure TForm1.UpdateRecord(const drugusage: string);

cds3.Edit;
    cds3.FieldByName('drugusage').AsString := drugusage;
    cds3.Post;



3
ลองแกะดูครับ
เปลี่ยน icode ของ Metformin และ lo.lab_items_code ของ eGFR ให้ตรงกับของโรงพยาบาล
เปลี่ยน drugusage เป็นวิธีใช้ที่ไม่เกิน 1000 mg/day

SYS_VN_SCRIPT
โค๊ด: [Select]
var
  vn,hn: string;
  lasteGFR: Double;
  isMetforminOrder, isWrongMetforminUsageDose: Boolean;

begin

    vn := GetGlobalValue('VN');
    //vn := '671113080230';
    hn  := getsqldata('select hn from vn_stat where vn="' + vn + '"');

  //******** metformin popup ******
    isMetforminOrder := StrToInt(getsqldata('SELECT COUNT(*) FROM opitemrece o WHERE o.vn = "' + vn + '" ' +
                                        'AND o.icode = ''1000210'' AND o.qty > 0')) > 0;
    lasteGFR := getsqldata('SELECT lo.lab_order_result ' +
                       'FROM lab_head lh ' +
                       'INNER JOIN lab_order lo ON lh.lab_order_number = lo.lab_order_number ' +
                       'WHERE lh.hn = "' + hn + '" ' +
                       'AND lo.lab_items_code = "660" ' +
                       'AND lo.lab_order_result > 0 ' +
                       'AND lo.lab_order_result REGEXP ''^[0-9]+\.?[0-9]*$'' ' +
                       'ORDER BY lh.report_date DESC LIMIT 1');
   isWrongMetforminUsageDose := StrToInt(getsqldata('SELECT COUNT(*) FROM opitemrece o WHERE o.vn = "' + vn + '" ' +
                                                   'AND o.icode = ''1000210'' AND o.qty > 0 ' +
                                                   'AND o.drugusage NOT IN (''0002172'', ''0011'', ''0014'', ''0022'', ''0033'', ''0154'', ''0168'', ''0321'', ''0336'')')) > 0;
    //showmessage(isWrongMetforminUsageDose);
    //showmessage(lasteGFR);
    try
      if  (isMetforminOrder and (StrToFloat(lasteGFR) > 0) and (StrToFloat(lasteGFR) < 30)) or
          (isMetforminOrder and (StrToFloat(lasteGFR) > 30) and (StrToFloat(lasteGFR) < 45) and isWrongMetforminUsageDose) then
          begin
          runHOSxP_ScriptProgram('Drugblocker');
      end;
    except
      on E: EConvertError do
      showmessage('Invalid GFR value');
    end;
   //***************************

end;

4
ใน SYN_VN_SCRIPT
count icode ของยา metformin ใน opitemrece
ถ้า >=1 ให้ดึงค่า eGFR มาเช็คดูว่า <45 หรือไม่

ถ้า <45 เช็คดูว่า usage เป็น usage หรือ sp_usage
     usage -> ต้องเป็น 1x2 หรือ 1x1
     sp_usage -> ห้ามใช้ หรือถ้าจะใช้ให้ไป เขียน function regEx ถอดข้อความอีกไม่ได้เกิน 1000 mg/day
    -> แจ้งเตือนอะไรก็ว่าไป
ถ้า <30 ขึ้น popup ให้ติ๊ก check box แล้วกดปุ่มยืนยัน ถ้าไม่ติ๊กให้ลบรายการ icode นั้นออกหรือ update จำนวนเป็น 0
 


5
Delphi / Pascal / DUE Script
« เมื่อ: กันยายน 03, 2024, 15:33:25 PM »
ใช้แทน DUE  + UE-Form ที่ไม่ขึ้น pop-up auto ถ้า remed ครับ
เปลี่ยน icode และตั้งค่าให้ run ใน SYS_VN_SCRIPT ด้วยครับ

SYS_VN_SCRIPT
โค๊ด: [Select]
if getsqldata('SELECT COUNT(*) ' +
              'FROM opitemrece o ' +
              'INNER JOIN drugitems d ON o.icode = d.icode ' +
              'WHERE o.vn="' + vn + '" ' +
              'AND o.qty > 0 ' +
              'AND o.icode IN (' +
              '"1000013", /* CELECOXIB */ ' +
              '"1000014", /* DIACERINE */ ' +
              '"1000240", /* SODIUM HYALURONATE 1% */ ' +
              '"1000274", /* OCTREOTIDE */ ' +
              '"1000288", /* SULPROSTONE */ ' +
              '"1000291", /* FINASTERIDE */ ' +
              '"1000423", /* ENOXAPARIN */ ' +
              '"1000452", /* CLOMIPHENE */ ' +
              '"1000473", /* ALBUMIN HUMAN */ ' +
              '"1500038", /* CLOPIDOGREL */ ' +
              '"1500039", /* ENOXAPARIN */ ' +
              '"1510041", /* CEFDINIR */ ' +
              '"1510042", /* CEFDINIR */ ' +
              '"1510044", /* ACYCLOVIR */ ' +
              '"1510052", /* CIPROFLOXACIN */ ' +
              '"1520803", /* GABAPENTIN */ ' +
              '"1530304", /* AZITHROMYCIN */ ' +
              '"1540113", /* PREGABALIN */ ' +
              '"1540126", /* ACYCLOVIR */ ' +
              '"1510044", /* ACYCLOVIR */ ' +
              '"1540128", /* MEROPENEM */ ' +
              '"1550012", /* EPOETINBETA */ ' +
              '"1550132", /* ALTEPLASE */ ' +
              '"1550133", /* AZITHROMYCIN */ ' +
              '"1550134", /* MOMETASONE */ ' +
              '"1550137", /* CLARITHROMYCIN */ ' +
              '"1550138", /* VANCOMYCIN */ ' +
              '"1550147", /* ERTAPENEM */ ' +
              '"1550148", /* PIPERACILLIN+TAZOBACTAM */ ' +
              '"1550168", /* CIPROFLOXACIN */ ' +
              '"1550174", /* CEFIXIME */ ' +
              '"1560091", /* MOXIFLOXACIN */ ' +
              '"1560092", /* SODIUM HYALURONATE ED */ ' +
              '"1570044", /* COLISTIMETHATE */ ' +
              '"1570046", /* CEFOSULPERAZONE+SULBACTAM */ ' +
              '"1570052", /* LEVOFLOXACIN */ ' +
              '"1570082", /* PANTOPRAZOLE */ ' +
              '"1570085", /* LANTHANUM */ ' +
              '"1570092", /* DEFERIPRONE */ ' +
              '"1580083", /* BIPHASIC INSULIN ASPART */ ' +
              '"1580125", /* ALENDRONATE */ ' +
              '"1590084", /* LEVOFLOXACIN */ ' +
              '"1600159", /* QUETIAPINE */ ' +
              '"1600184", /* FILGRASTIM */ ' +
              '"1620178", /* BISMUTH SUBSALICYLATE */ ' +
              '"1620180", /* ETORICOXIB */ ' +
              '"1620182", /* SITAGLIPTIN */ ' +
              '"1620183", /* TIOTROPIUM + OLODETEROL */ ' +
              '"1620184", /* TIOTROPIUM + OLODETEROL */ ' +
              '"1630131", /* SODIUM HYALURONATE */ ' +
              '"1630133", /* TICAGRELOR */ ' +
              '"1640048", /* FLUCYTOSTINE */ ' +
              '"1640120", /* QUETIAPINE */ ' +
              '"1640131", /* TERIPARATIDE */ ' +
              '"1650034", /* ESCITALOPRAM */ ' +
              '"1650055", /* DENOSUMAB */ ' +
              '"1650149", /* BEVACIZUMAB */ ' +
              '"1650162", /* OLOPATADINE */ ' +
              '"1650182", /* LEVOFLOXACIN */ ' +
              '"1650184", /* FOSFOMYCIN */ ' +
              '"1650186", /* EMPAGLIFLOZIN */ ' +
              '"1650225", /* LIRAGLUTIDE */ ' +
              '"1650249", /* TIMOLOL+DORZOLAMIDE */ ' +
              '"1650256", /* DIOSMECTITE */ ' +
              '"1660062", /* TENOFOVIR ALAFENAMIDE */ ' +
              '"1660178", /* TENOFOVIR*/ ' +
              '"1660128", /* ENTECAVIR */ ' +
              '"1660164", /* VENLAFAXINE */ ' +
              '"1660166", /* EPOETINBETA */ ' +
              '"1660168", /* PREGABALIN */ ' +
              '"1660170", /* CELECOXIB */ ' +
              '"1660208", /* INSULIN GLARGINE */ ' +
              '"1660210", /* VALSARTAN + SACUBITRIL */ ' +
              '"1670041" /* LETROZOLE */ ' +
              ')') > 0 then
      begin
          //runHOSxP_ScriptProgram('DUE Complete');
          runHOSxP_ScriptProgram('DUE_Version2');
      end;

Source
โค๊ด: [Select]
[attachimg=1]
unit DUE;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, ActnList, DBCtrls, dblookup, DB, DBClient, Grids,
  DBGrids, SQLDB;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    pdxLabel: TLabel;
    Label1: TLabel;
    Shape1: TShape;
    Label8: TLabel;
    Label9: TLabel;
    Label10: TLabel;
    Label12: TLabel;
    Label13: TLabel;
    Label14: TLabel;
    Panel1: TPanel;
    Label5: TLabel;
    Label6: TLabel;
    Label7: TLabel;
    Year: TLabel;
    age_yLabel: TLabel;
    ListBox2: TListBox;
    Shape2: TShape;
    Button2: TButton;

  private
    procedure CheckBoxClick(Sender: TObject);
    procedure SaveCheckedItemsToDatabase;
    procedure showdata(Sender: TObject);
    procedure CreateCheckBoxesForGenericNames(tc: TClientDataSet);
    procedure LoadPatientData(vn: string);
    procedure LoadGenericNames(vn: string);
    function GetCheckBoxForGenericName(i: Integer): Boolean;
    function GetVN: string;
    function GetHN: string;
  public
    procedure showdata(Sender: TObject);
  end;

var
  Form1: TForm1;
  genericNameList, icodeList: TStringList;
  drugName,tradeName: TLabel;
  CheckBoxList: TStringList;


implementation

{$R *.dfm}


function GetVN: string;
begin
  Result := GetGlobalValue('VN');
  if Result = '' then
    Result := '670911151440'; // Default value
end;

function getHN: string;
begin
  Result := getsqldata('SELECT hn FROM vn_stat WHERE vn="' + getVN + '"');
end;


// ===========================================================
// Helper function to load patient data
procedure TForm1.LoadPatientData(vn: string);
var
  hn, fullname, pttype, age_y, pdx: string;
begin
  // Load patient's hn, full name, pttype, age, and pdx
  hn := getHN;//getsqldata('SELECT hn FROM vn_stat WHERE vn="' + vn + '"');
  fullname := getsqldata('SELECT CONCAT(pname, fname, " ", lname) FROM patient WHERE hn="' + hn + '"');
  pttype := getsqldata('SELECT p.name FROM opitemrece o inner join pttype p on o.pttype = p.pttype WHERE vn="' + vn + '"');
  age_y := getsqldata('SELECT age_y FROM vn_stat WHERE vn="' + vn + '"');
  pdx := getsqldata('SELECT CONCAT(vs.pdx," : ",i.name) FROM vn_stat vs inner join icd101 i on vs.pdx = i.code WHERE vn="' + vn + '"');

  // Assign retrieved data to labels
  Label10.Caption := hn;
  Label12.Caption := fullname;
  Label14.Caption := pttype;
  age_yLabel.Caption := age_y;
  pdxLabel.Caption := pdx;
end;



// ===========================================================
// Helper function to load generic names and initialize CheckBoxList
procedure TForm1.LoadGenericNames(vn: string);
var
  tc0: TClientDataSet;
begin
  // Initialize genericNameList and CheckBoxList
  genericNameList := TStringList.Create;
  CheckBoxList := TStringList.Create;
  icodeList := TStringList.Create;

  // Retrieve distinct generic names from the database
  tc0 := TClientDataset.Create(nil);
  try
      tc0.Data := hosxp_getdataset('SELECT DISTINCT d.generic_name,o.icode FROM opitemrece o ' +
          'INNER JOIN drugitems d ON o.icode = d.icode ' +
          'WHERE o.vn="' + vn + '" AND d.icode IN (' +
          '"1000013", /* CELECOXIB */ ' +
          '"1000014", /* DIACERINE */ ' +
          '"1000240", /* SODIUM HYALURONATE 1% */ ' +
          '"1000274", /* OCTREOTIDE */ ' +
          '"1000288", /* SULPROSTONE */ ' +
          '"1000291", /* FINASTERIDE */ ' +
          '"1000423", /* ENOXAPARIN */ ' +
          '"1000452", /* CLOMIPHENE */ ' +
          '"1000473", /* ALBUMIN HUMAN */ ' +
          '"1500038", /* CLOPIDOGREL */ ' +
          '"1500039", /* ENOXAPARIN */ ' +
          '"1510041", /* CEFDINIR */ ' +
          '"1510042", /* CEFDINIR */ ' +
          '"1510044", /* ACYCLOVIR */ ' +
          '"1510052", /* CIPROFLOXACIN */ ' +
          '"1520803", /* GABAPENTIN */ ' +
          '"1530304", /* AZITHROMYCIN */ ' +
          '"1540113", /* PREGABALIN */ ' +
          '"1540126", /* ACYCLOVIR */ ' +
          '"1540128", /* MEROPENEM */ ' +
          '"1550012", /* EPOETINBETA */ ' +
          '"1550132", /* ALTEPLASE */ ' +
          '"1550133", /* AZITHROMYCIN */ ' +
          '"1550134", /* MOMETASONE */ ' +
          '"1550137", /* CLARITHROMYCIN */ ' +
          '"1550138", /* VANCOMYCIN */ ' +
          '"1550147", /* ERTAPENEM */ ' +
          '"1550148", /* PIPERACILLIN+TAZOBACTAM */ ' +
          '"1550168", /* CIPROFLOXACIN */ ' +
          '"1550174", /* CEFIXIME */ ' +
          '"1560091", /* MOXIFLOXACIN */ ' +
          '"1560092", /* SODIUM HYALURONATE ED */ ' +
          '"1570044", /* COLISTIMETHATE */ ' +
          '"1570046", /* CEFOSULPERAZONE+SULBACTAM */ ' +
          '"1570052", /* LEVOFLOXACIN */ ' +
          '"1570082", /* PANTOPRAZOLE */ ' +
          '"1570085", /* LANTHANUM */ ' +
          '"1570092", /* DEFERIPRONE */ ' +
          '"1580083", /* BIPHASIC INSULIN ASPART */ ' +
          '"1580125", /* ALENDRONATE */ ' +
          '"1590084", /* LEVOFLOXACIN */ ' +
          '"1600159", /* QUETIAPINE */ ' +
          '"1600184", /* FILGRASTIM */ ' +
          '"1620178", /* BISMUTH SUBSALICYLATE */ ' +
          '"1620180", /* ETORICOXIB */ ' +
          '"1620182", /* SITAGLIPTIN */ ' +
          '"1620183", /* TIOTROPIUM + OLODETEROL */ ' +
          '"1620184", /* TIOTROPIUM + OLODETEROL */ ' +
          '"1630131", /* SODIUM HYALURONATE */ ' +
          '"1630133", /* TICAGRELOR */ ' +
          '"1640048", /* FLUCYTOSTINE */ ' +
          '"1640120", /* QUETIAPINE */ ' +
          '"1640131", /* TERIPARATIDE */ ' +
          '"1650034", /* ESCITALOPRAM */ ' +
          '"1650055", /* DENOSUMAB */ ' +
          '"1650149", /* BEVACIZUMAB */ ' +
          '"1650162", /* OLOPATADINE */ ' +
          '"1650182", /* LEVOFLOXACIN */ ' +
          '"1650184", /* FOSFOMYCIN */ ' +
          '"1650186", /* EMPAGLIFLOZIN */ ' +
          '"1650225", /* LIRAGLUTIDE */ ' +
          '"1650249", /* TIMOLOL+DORZOLAMIDE */ ' +
          '"1650256", /* DIOSMECTITE */ ' +
          '"1660062", /* TENOFOVIR ALAFENAMIDE */ ' +
          '"1660128", /* ENTECAVIR */ ' +
          '"1660164", /* VENLAFAXINE */ ' +
          '"1660166", /* EPOETINBETA */ ' +
          '"1660178", /* TDF */ ' +
          '"1660168", /* PREGABALIN */ ' +
          '"1660170", /* CELECOXIB */ ' +
          '"1660208", /* INSULIN GLARGINE */ ' +
          '"1660210", /* VALSARTAN + SACUBITRIL */ ' +
          '"1670041" /* LETROZOLE */' +
          ')');
    tc0.First;
    while not tc0.Eof do
    begin
      genericNameList.Add(tc0.FieldByName('generic_name').AsString);
      icodeList.Add(tc0.FieldByName('icode').AsString);
      tc0.Next;
    end;
  finally
    tc0.Free;
  end;
end;

procedure TForm1.CreateCheckBoxesForGenericNames(tc: TClientDataSet);
var
  CheckBoxTop, i: Integer;
  CheckBox: TCheckBox;
  LabelCaption,TT: TLabel;
  UniqueName: string;
  CaptionText: string;
  TextHeight, RequiredLines: Integer;
  ExistingDueList: TClientDataSet;
  RecordExists: Boolean;
begin
  CheckBoxTop := 150;
  ExistingDueList := TClientDataSet.Create(nil);
  try
    ExistingDueList.Data := hosxp_getdataset('SELECT generic_name, indication FROM drug_due_list WHERE vn = "' + GetVN + '"');
    ExistingDueList.Open;

  // Iterate over the generic names to create checkboxes
  for i := 0 to genericNameList.Count - 1 do
  begin
    // Create a label for the generic name
    drugName := TLabel.Create(Self);
    drugName.Parent := Self;
    drugName.Top := CheckBoxTop;
    drugName.Left := 30;
    drugName.Caption :={ QuotedStr(i+1)+'.'+}genericNameList[i];
    tradeName := TLabel.Create(Self);
    tradeName.Parent := Self;
    tradeName.Top := CheckBoxTop + 15;
    tradeName.Left := 30;
    tradeName.Caption := getsqldata('select trade_name from drugitems where icode = "'+ icodeList[i] +'"');


    // Retrieve associated items
    tc.Data := hosxp_getdataset('SELECT universal_item_value_name, universal_item_value_code FROM universal_item_value_list ' +
      'WHERE universal_item_value_code LIKE ' + QuotedStr(genericNameList[i] + '%'));

    // Create checkboxes for the associated values
    if not tc.IsEmpty then
    begin
      tc.First;
      while not tc.Eof do
      begin
        // Generate a unique name for each CheckBox
        UniqueName := Format('chk_%d_%d', [i, tc.RecNo]);
        //UniqueName := Format('chk_%s_%d', [genericNameList[i], tc.RecNo]);
        CaptionText := tc.FieldByName('universal_item_value_name').AsString;

        // Create the checkbox without a long caption
        CheckBox := TCheckBox.Create(Self);
        CheckBox.Parent := Self;
        CheckBox.Left := 200;
        CheckBox.Top := CheckBoxTop;
        CheckBox.Width := 15;  // Narrow checkbox without text
        CheckBox.Name := UniqueName; // Use the unique name
        CheckBox.OnClick := CheckBoxClick;
        CheckBox.Tag := i + 1;
        Checkbox.Caption := CaptionText;

          // Check if this checkbox should be marked as checked based on existing records
          ExistingDueList.First;
          RecordExists := False;
          while not ExistingDueList.Eof do
          begin
            if (ExistingDueList.FieldByName('generic_name').AsString = genericNameList[i]) and
               (ExistingDueList.FieldByName('indication').AsString = CheckBox.Caption) then
            begin
              RecordExists := True;
              Break;
            end;
            ExistingDueList.Next;
          end;

          // If the record exists, set the checkbox as checked
          if RecordExists then
            CheckBox.Checked := True;

        // Create a label for the checkbox caption
        LabelCaption := TLabel.Create(Self);
        LabelCaption.Parent := Self;
        LabelCaption.Left := CheckBox.Left + 30;  // Indent from the checkbox
        LabelCaption.Top := CheckBoxTop;
        LabelCaption.Width := 500;  // Set width for proper word wrapping
        LabelCaption.WordWrap := True;
        LabelCaption.Caption := CaptionText;
        LabelCaption.AutoSize := True;
        LabelCaption.Visible := False;

        TT := TLabel.Create(Self);
        TT.Parent := Self;
        TT.Caption :=  CaptionText;
        TT.WordWrap := True;
        TT.Width := 500;
        TT.Left := CheckBox.Left + 25;
        // Calculate the required height of the label
        TT.Top := CheckBoxTop ;
        TT.AutoSize := True;
        TT.Height := LabelCaption.Height;

        // Calculate the required number of lines for the wrapped text
        RequiredLines := (Length(CaptionText) + 99) div 100;
       
        // Set the label's height to accommodate all lines
        LabelCaption.Height := RequiredLines * 12;

        // Add the CheckBox to the list
        CheckBoxList.AddObject(CheckBox.Name, CheckBox);

        // Adjust the CheckBoxTop based on the label height
        CheckBoxTop := CheckBoxTop + LabelCaption.Height + 10;
        tc.Next;
      end;
    end
    else
      ShowMessage('No data found for ' + genericNameList[i]);
      CheckBoxTop := CheckBoxTop + 15;
    end;
  finally
    ExistingDueList.Free;
  end;
end;



// ===========================================================
// Procedure that gets called when any checkbox is clicked
procedure TForm1.CheckBoxClick(Sender: TObject);
var
  CheckBox: TCheckBox;
  CheckBoxName: string;
begin
  CheckBox := TCheckBox(Sender);
  CheckBoxName := CheckBox.Caption;

  if CheckBox.Checked then
  begin
    if CheckBoxList.IndexOf(CheckBoxName) = -1 then
      CheckBoxList.AddObject(CheckBoxName, CheckBox);
  end
  else
    CheckBoxList.Delete(CheckBoxList.IndexOf(CheckBoxName));
end;

// ===========================================================
// Helper function to validate that at least one checkbox is checked per generic name
function TForm1.GetCheckBoxForGenericName(i: Integer): Boolean;
var
  j: Integer;
  CheckBox: TCheckBox;
begin
  Result := False;

  for j := 0 to CheckBoxList.Count - 1 do
  begin
    CheckBox := TCheckBox(CheckBoxList.Objects[j]);

    if (CheckBox.Tag = i + 1) and CheckBox.Checked then
    begin
      Result := True;
      Break;
    end;
  end;
end;

// ===========================================================
// Main procedure that handles form data display
procedure TForm1.showdata(Sender: TObject);
var
  vn: string;
  tc: TClientDataSet;
begin
  vn := GetVN;

  LoadPatientData(vn);
  LoadGenericNames(vn);

  // Create and initialize the second dataset for checkboxes
  tc := TClientDataset.Create(nil);
  try
    CreateCheckBoxesForGenericNames(tc);
  finally
    tc.Free;
  end;
end;

// ===========================================================
// Procedure to save checked items to the database
procedure TForm1.SaveCheckedItemsToDatabase;
var
  i: Integer;
  vn, doctor: string;
  fcdsDUE: TClientDataSet;
  CheckBox: TCheckBox;
  OriginalName, ModifiedName: string;
  UnderscorePos: Integer;
  RecordExists: Boolean;
  ShouldInsert: Boolean;
  RecordsToDelete: TStringList; // Use TStringList for IDs
  DeleteID: string;
begin
  // Retrieve global values
  vn := GetVN;
  RecordsToDelete := TStringList.Create;

  try
    if CheckBoxList.Count > 0 then
    begin
      // Initialize and set up the TClientDataSet for inserting data
      fcdsDUE := TClientDataSet.Create(nil);
      try
        fcdsDUE.Data := hosxp_getdataset('SELECT * FROM drug_due_list WHERE vn = "' + vn + '"');
       
        if not fcdsDUE.Active then
          fcdsDUE.Open;

        // Collect records to delete
        fcdsDUE.First;
        while not fcdsDUE.Eof do
        begin
          RecordExists := False;
          for i := 0 to CheckBoxList.Count - 1 do
          begin
            CheckBox := TCheckBox(CheckBoxList.Objects[i]);

            if CheckBox.Checked then
            begin
              OriginalName := genericNameList[CheckBox.Tag - 1];
              UnderscorePos := Pos('_', OriginalName);
              if UnderscorePos > 0 then
                ModifiedName := Copy(OriginalName, 1, UnderscorePos - 1)
              else
                ModifiedName := OriginalName;

              if (fcdsDUE.FieldByName('generic_name').AsString = ModifiedName) and
                 (fcdsDUE.FieldByName('indication').AsString = CheckBox.Caption) then
              begin
                RecordExists := True;
                Break;
              end;
            end;
          end;

          if not RecordExists then
          begin
            DeleteID := fcdsDUE.FieldByName('drug_due_id').AsString;
            RecordsToDelete.Add(DeleteID); // Collect IDs to delete
          end;

          fcdsDUE.Next;
        end;

        // Delete the collected records
        fcdsDUE.First;
        while not fcdsDUE.Eof do
        begin
          if RecordsToDelete.IndexOf(fcdsDUE.FieldByName('drug_due_id').AsString) > -1 then
          begin
            fcdsDUE.Delete;
          end
          else
          begin
            fcdsDUE.Next;
          end;
        end;

        // Insert new records
        for i := 0 to CheckBoxList.Count - 1 do
        begin
          CheckBox := TCheckBox(CheckBoxList.Objects[i]);

          if CheckBox.Checked then
          begin
            OriginalName := genericNameList[CheckBox.Tag - 1];
            UnderscorePos := Pos('_', OriginalName);
            if UnderscorePos > 0 then
              ModifiedName := Copy(OriginalName, 1, UnderscorePos - 1)
            else
              ModifiedName := OriginalName;

            doctor := getsqldata('SELECT o.doctor FROM opitemrece o WHERE vn="' + vn + '" AND icode ="' + icodeList[CheckBox.Tag - 1] + '" LIMIT 1');
           
            // Check if the record already exists
            fcdsDUE.First;
            RecordExists := False;
            while not fcdsDUE.Eof do
            begin
              if (fcdsDUE.FieldByName('vn').AsString = vn) and
                 (fcdsDUE.FieldByName('generic_name').AsString = ModifiedName) and
                 (fcdsDUE.FieldByName('indication').AsString = CheckBox.Caption) then
              begin
                RecordExists := True;
                Break;
              end;
              fcdsDUE.Next;
            end;

            // Determine if the record should be inserted
            ShouldInsert := not RecordExists;

            if ShouldInsert then
            begin
              fcdsDUE.Insert;
              fcdsDUE.FieldByName('drug_due_id').AsString := getsqldata('SELECT get_serialnumber("drug_due_list")');
              fcdsDUE.FieldByName('generic_name').AsString := ModifiedName;
              fcdsDUE.FieldByName('vn').AsString := vn;
              fcdsDUE.FieldByName('doctor').AsString := doctor;
              fcdsDUE.FieldByName('entry_date').AsDateTime := Now;
              fcdsDUE.FieldByName('indication').AsString := CheckBox.Caption;
              fcdsDUE.FieldByName('hn').AsString := getHN;
              fcdsDUE.FieldByName('icode').AsString := icodeList[CheckBox.Tag - 1];
              fcdsDUE.Post;
            end;
          end;
        end;

        // Check if there are any changes
        if fcdsDUE.ChangeCount > 0 then
        begin
          // Update the database
          hosxp_updatedelta(fcdsDUE.Delta, 'SELECT * FROM drug_due_list');
        end
        else
        begin
         // ShowMessage('No changes to save.');
        end;
       
      except
        on E: Exception do
          ShowMessage('Error processing data: ' + E.Message);
      end;
    end
    else
    begin
      ShowMessage('No checkboxes are selected.');
    end;
  finally
    fcdsDUE.Free;
    RecordsToDelete.Free;
  end;
end;


procedure TForm1.Button1Click(Sender: TObject);
var
  i, j: Integer;
  CheckBox: TCheckBox;
  AtLeastOneChecked: Boolean;
begin
  // Iterate over each generic name in the list
  for i := 0 to genericNameList.Count - 1 do
  begin
    AtLeastOneChecked := False;

    // Check if at least one checkbox associated with the current generic name is checked
    for j := 0 to CheckBoxList.Count - 1 do
    begin
      CheckBox := TCheckBox(CheckBoxList.Objects[j]);
     
      // Assume CheckBox.Tag stores the index corresponding to the generic name in genericNameList
      if (CheckBox.Tag = i + 1) and CheckBox.Checked then
      begin
        AtLeastOneChecked := True;
        Break; // Exit the loop as soon as we find one checked checkbox for the current generic name
      end;
    end;

    // If no checkbox is checked for the current generic name, show a message and exit
    if not AtLeastOneChecked then
    begin
      ShowMessage('ÂѧäÁèä´éàÅ×Í¡à˵ؼšÒÃãªéÂÒ ' + genericNameList[i]);
      Exit;
    end;
  end;

  // If all checks pass, proceed to save
  try
    SaveCheckedItemsToDatabase;
    Close; // Close the form if everything is valid
  except
    on E: Exception do
      ShowMessage('Error saving data: ' + E.Message);
  end;
end;
 
procedure TForm1.FormDestroy(Sender: TObject);
begin
  CheckBoxList.Free; // Free CheckBoxList when the form is destroyed
  genericNameList.Free;
  icodeList.Free;
end;

end.



DFM

โค๊ด: [Select]
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Drug Use Evaluation (DUE)'
  ClientHeight = 600
  ClientWidth = 800
  Color = clWindow
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnShow = showdata                 
  PixelsPerInch = 96
  TextHeight = 13
  object Shape1: TShape
    Left = 10
    Top = 10
    Width = 780
    Height = 85
    Pen.Color = clWindowFrame
  end
    object Shape2: TShape
    Left = 10
    Top = 105
    Width = 780
    Height = 485
    Pen.Color = clWindowFrame
  end
  object Label2: TLabel
    Left = 168
    Top = 48
    Width = 33
    Height = 16
    Caption = 'ª×èÍ - Ê¡ØÅ'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
  object Label3: TLabel
    Left = 400
    Top = 48
    Width = 22
    Height = 16
    Caption = 'ÍÒÂØ'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
   object Year: TLabel
    Left = 450
    Top = 48
    Width = 22
    Height = 16
    Caption = '»Õ'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
    object age_yLabel: TLabel
    Left = 430
    Top = 48
    Width = 22
    Height = 16
    Caption = '»Õ'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
  object Label4: TLabel
    Left = 32
    Top = 68
    Width = 54
    Height = 16
    Caption = 'Diagnosis'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
  object pdxLabel: TLabel
    Left = 100
    Top = 68
    Width = 20
    Height = 16
    Caption = 'pdx'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
  object Label1: TLabel
    Left = 32
    Top = 48
    Width = 16
    Height = 16
    Caption = 'HN'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
  object Label8: TLabel
    Left = 30
    Top = 16
    Width = 108
    Height = 16
    Caption = 'Patient information'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end

  object Label10: TLabel
    Left = 55
    Top = 48
    Width = 14
    Height = 16
    Caption = 'hn'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
  object Label12: TLabel
    Left = 230
    Top = 48
    Width = 49
    Height = 16
    Caption = 'fullname'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
  object Label13: TLabel
    Left = 500
    Top = 48
    Width = 35
    Height = 16
    Caption = 'ÊÔ·¸Ô¡ÒÃÃÑ¡ÉÒ'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end
  object Label14: TLabel
    Left = 580
    Top = 48
    Width = 35
    Height = 16
    Caption = 'Pttype'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end

  object DoctorLabel: TLabel
    Left = 480
    Top = 532
    Width = 35
    Height = 16
    Caption = ''
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -13
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
  end

  object Button1: TButton
    Left = 660
    Top = 530
    Width = 75
    Height = 25
    Caption = 'ºÑ¹·Ö¡'
    TabOrder = 0
    OnClick = Button1Click
  end

  object Button2: TButton
    Left = 570
    Top = 530
    Width = 75
    Height = 25
    Caption = 'àÅ×Í¡¢éÍà´ÔÁ'
    TabOrder = 0
    OnClick = Button2Click
    Visible = false
  end


end


6
สวัสดีครับ ไม่ทราบว่าเราสามารถโชว์ค่า CrCl ในใบสั่งยาผู้ป่วยในได้ไหมครับ ตอนนี้มีในฝบสั่งยาผู้ป่วยนอกและ popup เวลาบันทึกใบสั่งยาผู้ป่วยใน มันน่ารำคาญมากๆ

หน้า: [1]