close data
ndialy=1
store be2ce('1/1/2567') to _start,_end
*store date() to _start,_end
_start=be2ce('18/3/2567')
_end=be2ce('19/3/2567')
=settype()
store '' to cshow,cclose
store '' to oErr,myURL,myToken,myDefault
store .T. to lCheckHN,lStart
cShow='OPD'
lTestZone=icase(myhospcode$'14135',.F.,.T.)
_target=icase(ltestzone,[Test],myrcm)+[.Visit_Closable]
_table=[NHSO_Confirm_Privilege]
text to myQuery noshow
drop table if exists test.tmpdata;
create table test.tmpdata (index(vn))
select o.vn,o.hn,o.an,pt.cid,pt.fname,pt.lname,pt.sex,pt.birthday
,caldatetime(o.vstdate,o.vsttime) vstdate
,seekhipdata(ptt.hipdata_code,1) maininscl,ptt.pttype_eclaim_id
,o.pttype,concat_ws(':',o.pttype,ptt.name) pttypename
,v.income,v.uc_money,v.rcpt_money
,diagnosis('opd',o.vn,0) diag
,operation('opd',o.vn) oper
from ovst o
left join patient pt on pt.hn=o.hn
left join pttype ptt on ptt.pttype=o.pttype
left join vn_stat v on v.vn=o.vn
where o.vstdate between @ds1 and @ds2
group by o.vn;
endtext

sele 0
create cursor tmpReport (No n(7) null,Selected L,Status c(15) null,NHSO_Seq n(20) null,Zone c(10) null,VN c(25) null,CID c(13) null,HN c(9) null,AN c(9) null,FName c(30) null,LName c(30) null,Sex c(1) null,Birthday D null,VstDate T null;
,MainInscl c(5) null,PttypeName c(200) null,Diag c(100) null,Income n(15,2) null,UC_Money n(15,2) null,RCPT_Money n(15,2) null,Note c(100) null)
scatt memv memo
store '' to _title,_width,_format,_position
for ii=1 to fcount()
	_field=field(ii)
	_title=_title+icase(ii=1,'','|')+icase(_field='NHSO_SEQ','Seq',_field='INCOME','',_field='UC_MONEY','ԡ',_field='RCPT_MONEY','ԡ','x')
	_format=_format+icase(ii=1,'','|')+icase(_field$'INCOME,UC_MONEY,RCPT_MONEY',formatmoney,'x')
	_width=_width+icase(ii=1,'','|')+icase(_field=='NO','40',_field='STATUS','60',_field$'INCOME,UC_MONEY,RCPT_MONEY','80',_field='DIAG,OPER','250',_field='NHSO_SEQ','80',_field='ZONE','50','x')
	_position=_position+icase(ii=1,'','|')+icase(_field='OK','2','x')
next
lockcolumns=fieldpos('lname')
lno=.T.
_risk='All'
_color=[icase(empty(status),color('lightyellow'),status='C',rgb(192,128,0),income=0,color('lightred'),color('white'))]
_caption='ªͼ¹͡ Ѻԡ '+_message
reportname='showsummary'
clear class myReport
oReport=create('myReport')
oReport.show
defi class myReport as myshows
	add object lsterror as mylistbox with left=5,height=80,tabstop=.F.
	
	add object lblstart as mylabels with caption=''
	add object txtstart as mytextboxdate with controlsource='_start',tabstop=.T.,enabled=.T.
	add object lblend as mylabels with caption='֧'
	add object txtend as mytextboxdate with controlsource='_end',tabstop=.T.,enabled=.T.
	add object cmdShow as mybutton with caption='ʴ',top=3,left=5,height=32,width=50
	add object lblShow as mylabels with caption='ʴ'
	add object txtShow as mycombobox with controlsource='cshow',width=80,rowsourcetype=1,rowsource=',OPD,IPD',tabstop=.F.
	add object lblClose as mylabels with caption='ԴԷ'
	add object txtClose as mycombobox with controlsource='cclose',width=90,rowsourcetype=1,rowsource=',OK,Cancel,ѧԴ',tabstop=.F.
	
	add object chkZone as mycheckbox with controlsource='ltestzone',caption='TestZone',enabled=.T.
	add object cmdOK as mybutton with caption='ԴԷ',height=32
	add object cmdCancel as mybutton with caption='¡ԡ',height=32,enabled=.F.
	add object cmdCheckup as mybutton with caption='Ǩͺ',height=32
	add object cmdUpdate as mybutton with caption='Update',height=32
	add object cmdExit as mybutton with caption='Exit',height=32
	Proc SetObject
		with this
			oerr=.lsterror
			.calpos('start',9,5)
			.calpos('end',9,calpos(.txtstart,5))
			.cmdshow.left=calpos(.txtend,5)
			.calpos('show',9,calpos(.cmdshow,5))
			.calpos('close',9,calpos(.txtshow,5))
			.buttonside('Exit|Update|Checkup|Cancel|OK',,3)
			.position('chkzone',.cmdshow.top+8,.cmdok.left-.chkzone.width)
			.grddata.top=max(calpos(.txtend,5,.T.),calpos(.cmdExit,5,.T.))
		endwith
	Proc SetMergeHeader
		.MergeHeader(fieldpos('status'),fieldpos('zone'),'ûԴԷ',,color('green'))
		.MergeHeader(fieldpos('income'),fieldpos('rcpt_money'),'')
		.headercolor('status',color('green'))
		.headercolor('nhso_seq',color('green'))
		.headercolor('zone',color('green'))
	Proc Activate
		if lstart
			lstart=.F.
			=adddata(.T.)
		endif
	Proc Destroy
		rele oErr
		thisform.release
	Proc ShowData
		lpara _is
		with this
			.grddata.recordsource=''
			=adddata(_is)
			.grddata.recordsource=alias()
			.setfocus
		endwith
	Proc ToRightClick
		thisform.setfocus
	Proc ToClick
		do case
			case myname$'VN,AN,HN,CID,MAININSCL,PTTYPENAME,STATUS'
				index on &myname tag no
		endcase
		thisform.setfocus
	Proc ResetData
		sele tmpreport
		zap
		this.refresh
	Proc chkZone.SetOther
		thisform.showdata
	Proc lblStart.Click
		_start=startyear(_start)
		this.parent.txtstart.setfocus
	Proc txtStart.Gotfocus
		this.tag=this.value
		thisform.resetdata
	Proc lblEnd.Click
		_end=endyear(_end)
		this.parent.txtend.setfocus
	Proc txtEnd.Gotfocus
		this.tag=this.value
		thisform.resetdata
	Proc cmdShow.Click
		with thisform
			=settype()
			_caption='ªͼ¹͡ Ѻԡ '+_message
			.caption=_caption
			.refresh
			.showdata(.T.)
		endwith
	Proc cmdShow.RightClick
		if mydates()
			this.click
		endif
		thisform.setfocus
	Proc txtClose.Click
		thisform.showdata
	Proc grdData.Keypress
		lpara _key,_other
		do case 
			case _key=27
				thisform.destroy
			case _key=-2
			case _key=-3
			case _key=-4 
			case _key=-6
				this.QuickExcel
			case _key=-7
				this.exporttextfile
			case _key=-8
				this.ExportExcel
		endcase
	Proc grdData.DblClick
		acti scree
		?m.vn
		this.setfocus
	Proc cmdExit.Click
		thisform.destroy
	Proc cmdUpdate.Click
		=updaterequest()
		thisform.setfocus
	Proc cmdCheckUp.Click
		if type('oErr')='O'
			oerr.clear
			oerr.columncount=5
			oerr.columnwidths='300,500,100,100,100'
		endif
		sele tmpreport
		scatt memv memo
		=setfielddatas()
		=writeerror(m.vn,oerr)
		=checkvisit()
		=writeerror('OK',oerr)
		thisform.setfocus	
	Proc cmdCheckUp.RightClick
		if type('oErr')='O'
			oerr.clear
			oerr.columncount=5
			oerr.columnwidths='300,500,100,100,100'
		endif
		sele tmpreport
		nrec=recno()
		scan
			scatt memv memo
			=setfielddatas()
			=writeerror(m.vn,oerr)
			=checkvisit()
		ends
		if recco()>0
			go (nrec)
		endif
		=writeerror('OK',oerr)
		thisform.setfocus
	Proc cmdOK.Click
		if type('oErr')='O'
			oerr.clear
			oerr.columncount=5
			oerr.columnwidths='300,500,100,100,100'
		endif
		sele tmpreport
		scatt memv memo
		=setfielddatas()
		=writeerror(m.vn,oerr)
		=closevisit()
		=writeerror('OK',oerr)
		thisform.setfocus
enddefi

Proc MakeTableService
lpara _is
local _drop,lresult,lcopy
acti scree
_is=tologic(_is)
lcopy=.F.
if checktable('nhso_confirm_privilege')
	lresult=checkindex('nhso_confirm_privilege','vn',null)
	if !lresult or !isunique
		_is=.T.
		lcopy=.T.
		=sqlexec(_handle,[create table if not exists test.nhso_confirm_privilege like nhso_confirm_privilege])
		=sqlexec(_handle,comparefield('nhso_confirm_privilege','test.nhso_confirm_privilege'))
		=sqlexec(_handle,[drop table if exists nhso_confirm_privilege])
	endif
endif
text to _sql noshow textmerge
drop table if exists test.visit_closable;
drop table if exists <<myrcm>>.visit_closable;
<<icase(_is,[drop table if exists nhso_confirm_privilege],[])>>;
create table if not exists nhso_confirm_privilege (nhso_confirm_privilege_id int auto_increment,vn varchar(25),nhso_seq int,nhso_authen_code varchar(20),nhso_request_json text,nhso_reponse_json text
,nhso_requst_datetime datetime,nhso_response_datetime datetime,confirm_staff varchar(50),nhso_status char(1),debt_id int,nhso_total_amount double(18,2),nhso_cancel_response text
,nhso_cancel_datetime datetime,cancel_staff varchar(50),nhso_confirm_type_id int,fdh_send_status char(1),fdh_transaction_id varchar(100),pttype char(2),nhso_privilege_amount double(18,2)
,nhso_cash_amount double(18,2),testzone varchar(1)
,primary key (nhso_confirm_privilege_id)
,unique key vn(vn)
) engine=MyISAM default charset=tis620;
call addcolumn('nhso_confirm_privilege','TestZone','varchar(1)',null);
endtext
=runsql(_sql,.T.)
if checktable('test.nhso_confirm_privilege') and lcopy
	=sqlexec(_handle,comparefield('test.nhso_confirm_privilege','nhso_confirm_privilege'))
endif

Proc SetRemark
local _remark
_remark=''
cshow=ntoc(cshow,0)
if cshow#''
	_remark=_remark+icase(empty(_remark),[where ],[ and ])+icase(cshow='OPD',[ifnull(an,'')=''],[ifnull(an,'')<>''])
endif
cclose=ntoc(cclose,0)
if cclose#''
	_remark=_remark+icase(empty(_remark),[where ],[ and ])+icase(cclose='OK',[nn.nhso_status='Y'],cclose='Cancel',[nn.nhso_status='C'],[ifnull(nn.nhso_status,'')=''])
endif
retu _remark

Proc AddData
lpara _is
if type('oErr')='O'
	oerr.clear
	oerr.columncount=5
	oerr.columnwidths='300,500,100,100,100'
endif
=maketableservice()
=showloading()
sele tmpReport
zap
_is=tologic(_is)
if _is
	=runsql(myquery,.T.)
endif
_remark=setremark()
text to _sql noshow textmerge
select t.*
,case
when nn.nhso_status='Y' then 'OK'
when nn.nhso_status='C' then 'Cancel'
else '' end status
,nn.nhso_seq
,if(nn.testzone='Y','Test','') Zone
from test.tmpdata t
left join <<_table>> nn on nn.vn=t.vn
<<_remark>>
endtext
if !runsql(_sql,.T.)
	retu .F.
endif
rec=recco()
n=0
=writeerror('Add Data',oerr)
=writeas(trans(n)+'/'+trans(rec),oerr,2)
scan
	n=n+1
	=writeas(trans(n)+'/'+trans(rec),oerr,2)
	store .null. to m.vn,m.an,m.hn,m.cid,m.birthday,m.vstdate,m.status,m.nhso_seq
	scatt memv memo
	m.vn=ntoc(m.vn)
	m.an=ntoc(m.an)
	m.hn=ntoc(m.hn)
	m.cid=ntoc(m.cid)
	m.cid=icase(checkpid(@m.cid),m.cid,'')
	m.birthday=tonull(toengdate(m.birthday))
	m.vstdate=tonull(toengdatetime(m.vstdate))
	m.status=ntoc(m.status)
	m.nhso_seq=tonull(m.nhso_seq)
	insert into tmpreport from memv
ends
rele oload
sele tmpreport
go top

Proc SetData
_target=icase(ltestzone,[Test],myrcm)+[.Visit_Closable]
myDefault=ntoc(readsysvar('NHSO-CONFIRM-PRIVIVLEGE-API-TOKEN'),0)			&&Token
myConfirm=checkyes(readsysvar('NHSO-CONFIRM-PRIVIVLEGE-API-URL'),.T.)		&&ҡѺ Y
myDefault=icase(empty(myDefault),[90cfc580-4d39-4fa0-8c0a-7fc5a36d4c64],myDefault)
myToken=icase(ltestzone,[adca1552-0680-40e9-83bc-e26a09df462a],myDefault)
myURL=icase(ltestzone,[https://test.nhso.go.th/nhsoendpoint/],[https://nhsoapi.nhso.go.th/nhsoendpoint/])

Proc UpdateRequest
if type('oErr')='O'
	oerr.clear
	oerr.columncount=5
	oerr.columnwidths='300,500,100,100,100'
endif
=maketableservice()
if !checktable(_table)
	retu .F.
endif
if !runsql([select * from <<_table>>],.T.,'tmpdata')
	retu .F.
endif
rec=recco()
n=0
=writeerror('Update:'+trans(n)+'/'+trans(rec),oerr)
do while !eof() and inkey()=0
	n=n+1
	=writeas('Update:'+trans(n)+'/'+trans(rec),oerr)
	doevents
	store '' to m.nhso_request_json
	scatt memv memo
	_request=ntoc(m.nhso_request_json,0)
	_date=strextract(_request,["invoiceDateTime":],[,])
	_date=unix2datetime(_date)
	m.nhso_requst_datetime=_date
	=savemysqldata(_table)
	sele tmpdata
	skip
enddo
=writeerror('OK',oerr)

Proc CloseVisit
acti scre
if empty(m.vn)
	retu .F.
endif
=setdata()
myURL=checkhttp(myURL+[/api/nhso-claim-detail],.T.)
*m.nhso_requst_datetime=datetime()
myvisitdate=datetime2unix(m.vstdate)
myincomedate=myvisitdate		&&datetime2unix(m.nhso_request_datetime)
_id=readsysvar([BMS-NHSO-CONFIRM-PRIVILEGE-OFFICER-ID])		&&ҵèҡҧ system_setting_list
*m.recorder=ntoc(getsqldata([select ifnull(u.cid,ifnull(o.officer_cid,'3620400295139')) cc from officer o left join opduser u on u.loginname=o.officer_login_name where officer_id=?_id]))
m.recorder=ntoc(getsqldata([select ifnull(u.cid,o.officer_cid) cc from officer o left join opduser u on u.loginname=o.officer_login_name where officer_id=?_id]))
m.recorder=icase(checkpid(@m.recorder),m.recorder,'')
text to _data noshow textmerge	&&6. š觢š׹ѹԴԷ (NHSO Claim Detail)
{
	"hcode":"<<myhospcode>>",
	"visitNumber":"<<m.vn>>",
	"pid":"<<m.cid>>",
	"transactionId":"<<myhospcode>><<m.vn>>",
	"serviceDateTime":<<myvisitdate>>,
	"invoiceDateTime":<<myincomedate>>,
	"mainInsclCode":"<<m.maininscl>>",
	"totalAmount":<<m.income>>,
	"paidAmount":<<m.rcpt_money>>,
	"privilegeAmount":<<m.uc_money>>,
	"claimServiceCode":"PG0060001",
	"sourceId":"RCM01",
	"recorderPid":"<<m.recorder>>"
}
endtext
m.nhso_request_json=_data
_ret=readurl(myURL,_data,'POST')
oJson=nfJsonRead(_ret)
msgError=ntoc(returndata('oJSon.Error'),0)
m.dataError=ntoc(returndata('oJSon.dataError'),0)
m.dataError=icase(empty(m.dataError),msgError,m.dataError)
if empty(m.dataError)
	m.nhso_reponse_json=_ret
else
	=writeas(m.dataerror,oerr,2)
endif
=savedata()

Proc CheckVisit
acti scree
if empty(m.vn)
	retu .F.
endif
=setdata()
myURL=checkhttp(myURL+[/api/nhso-claim-detail],.T.)
myvisitdate=datetime2unix(m.vstdate)
myincomedate=ntoc(getsqldata([select nhso_request_json from <<_table>> where vn=?m.vn]),0)
myincomedate=strextract(myincomedate,["invoiceDateTime":],[,])
*myincomedate=ntoc(getsqldata([select datetime2unix(nhso_requst_datetime) cc from <<_table>> where vn=?m.vn]),0)	&&ͧ䢵 request
myincomedate=icase(empty(myincomedate),myvisitdate,myincomedate)
text to _data noshow textmerge
{
	"transactionId": "<<myhospcode>><<m.vn>>",
	"hcode": "<<myhospcode>>",
	"pid": "<<m.cid>>",
	"DateTime":"<<ce2dmy('eeee-mm-ddThh:ii:ss',m.vstdate)>>",
	"invoiceDateTime":<<myincomedate>>
}
endtext
_ret=readurl(myURL,_data,'GET',.F.,.F.,'WinHttp.WinHttpRequest.5.1','Bearer')	&&GET ͧ WinHttp.WinHttpRequest.5.1
oJson=nfJsonRead(_ret)
=savedata()

Proc SaveData
local _old
_old=sele()
m.nhso_seq=tonum(returndata('oJSon.Seq'))
m.nhso_authen_code=ntoc(returndata('oJSon.authenCode'))
m.nhso_response_datetime=datetime()
if !empty(m.nhso_seq)
	=writeas('OK',oerr,2)
	m.status=icase(empty(m.nhso_seq),'','OK')
	m.nhso_status='Y'
	m.testzone=icase(ltestzone,'Y',.null.)
	sele tmpreport
	gath fields status,nhso_seq memv memo
	=sqlexec(_handle,textmerge([select * from <<_table>> where vn=?m.vn]),[tmpfield])
	=savedata2mysql(_table,_handle,0,'tmpfield')
endif
if !empty(_old)
	sele (_old)
endif
