domino常用知识总结

关于多值数据转换的问题,在ls代理里面

Dim newdb As NotesDatabase 
Dim newview As NotesView

Set newdb = New NotesDatabase("",F.Getcurpath(db) & "/e_multData.nsf") '多值数据的数据库
Set newview = newdb.Getview("v_module_bydataName") '多值数据库的视图

Dim searchkey(0) As String
 searchkey(0) = "数据库名域名"
Dim newtdoc As Variant
 Set newtdoc = newview.Getdocumentbykey(searchkey, True)
  
Dim arr As Variant
Dim arr2 As Variant
Dim kk As Integer 
arr = newtdoc.DataList '多值数据配置的域
For kk = 0 To UBound(arr)
arr2 = Split(arr(kk),"|")
If tempdoc.域名(0) = arr2(1) Then
 th(3,1) =arr2(0)
 Exit For
  End If
Next

Option Public
Use "class_f_default"
Dim F As f_default
Dim tsr As String
Dim calldb As NotesDatabase
Dim calldoc As NotesDocument
Dim ckey(1) As String

'定义全局变量

Dim DrugName As String '化学名称
Dim Allowance As Double '上周剩余量
Dim Lead_Content As Double '本周领用量
Dim Application_Amount As Double '本周使用量
Dim Surplus As Double '本周剩余量

Dim vccount As Integer '结果集条数

Public Class thisagent
 
 Function GetDataDetail(doc As NotesDocument,tempdoc As NotesDocument,i As Long,th As Variant) As String
  
  On Error Goto errhandle
  
  '第一步判断为空,也就第一条开始
  If DrugName = "" Then
   Allowance = Allowance+myCdbl(tempdoc.Allowance(0)) '上周剩余量累计
   Lead_Content = Lead_Content+myCdbl(tempdoc.Lead_Content(0)) '本周领用量累计
   Application_Amount = Application_Amount+myCdbl(tempdoc.Application_Amount(0)) '本周使用量累计
   Surplus = Surplus + myCdbl(tempdoc.Surplus(0))  '本周剩余量开始累加
   
   DrugName = tempdoc.DrugName(0) '化学品为空就把第一条付给它
   '第二步两个化学品相同
  ElseIf tempdoc.DrugName(0) = DrugName Then
   Allowance = Allowance+myCdbl(tempdoc.Allowance(0)) '上周剩余量累计
   Lead_Content = Lead_Content+myCdbl(tempdoc.Lead_Content(0)) '本周领用量累计
   Application_Amount = Application_Amount+myCdbl(tempdoc.Application_Amount(0)) '本周使用量累计
   Surplus = Surplus + myCdbl(tempdoc.Surplus(0))  '本周剩余量开始累加
   
   '第三部不相同的情况下,打印合计行(tempdoc.DrugName(0) <> DrugName)
  Else 
   th(0,1) = ""
   th(1,1) = ""
   th(2,1) = "合计"
   th(3,1) = ""
   th(4,1) = DrugName
   th(5,1) = ""
   th(6,1) = CStr(Allowance)
   th(7,1) = CStr(Lead_Content)
   th(8,1) = CStr(Application_Amount)
   th(9,1) = CStr(Surplus)
   
   Call F.AppendTableDetail(doc,th,"TableMain",i)
   Allowance = myCdbl(tempdoc.Allowance(0))
   Lead_Content = myCdbl(tempdoc.Lead_Content(0))
   Application_Amount = myCdbl(tempdoc.Application_Amount(0))
   Surplus = myCdbl(tempdoc.Surplus(0))
   
   DrugName = tempdoc.DrugName(0)
  End If
  
  '打印所有的数据行
  If doc.IsModuleManage(0) = "1"  Or (tempdoc.Status_Type(0) = "0" And UCase(tempdoc.Creater(0)) = UCase(doc.Curuser(0)))  Then
   th(0,1) = F.GetCheckBoxHtml(tempdoc,"SelectDoc")
  Else
   th(0,1) = ""
  End If
  th(1,1) = CStr(i)
  
  If UCase(tempdoc.Creater(0)) = UCase(doc.Curuser(0)) Then
   If tempdoc.GoToLiChenBei(0) = "1" Then
    th(1,1) = th(1,1) & "<img src='/oasrc/images/flag_red.gif' border=0 align='absmiddle' alt='里程碑已到'>" '里程碑环节审批
   End If
  End If
  
  If tempdoc.REQUESTNUMBER(0) = "" Then
   tsr = "-"
  Else
   tsr = tempdoc.REQUESTNUMBER(0)
  End If
  th(2,1) = F.GetOpenDocumentHtml(tempdoc,tsr)
  
  th(3,1) = tempdoc.WeekFor(0) 
  th(4,1) = tempdoc.DrugName(0)
  th(5,1) = tempdoc.ApplyDepartment_Show(0)
  th(6,1) = tempdoc.Allowance(0)
  th(7,1) = tempdoc.Lead_Content(0)
  th(8,1) = tempdoc.Application_Amount(0)
  th(9,1) = tempdoc.Surplus(0)
  
  Call F.AppendTableDetail(doc,th,"TableMain",i)
  
  '最后一行打印合计
  If vccount = i Then
   th(0,1) = ""
   th(1,1) = ""
   th(2,1) = "合计"
   th(3,1) = ""
   th(4,1) = DrugName
   th(5,1) = ""
   th(6,1) = CStr(Allowance)
   th(7,1) = CStr(Lead_Content)
   th(8,1) = CStr(Application_Amount)
   th(9,1) = CStr(Surplus)
   
   Call F.AppendTableDetail(doc,th,"TableMain",i)
  End If
  
  Exit Function
errhandle:
  Msgbox "使用量代理ag_get_v_total" & Error() & Erl()
  Call F.printerrmsg(doc,"GetDataDetail")
  Exit Function
 End Function
End Class
Sub Initialize
 On Error Goto errhandle
 
 Dim session As NotesSession
 Set session = New NotesSession
 Dim doc As NotesDocument
 Set doc = session.DocumentContext
 Dim db As NotesDatabase
 Set db = session.CurrentDatabase
 
 Set F = New f_default
 Dim A As thisagent
 Set A = New thisagent
 
 DrugName = ""
 Surplus = 0
 
 '-----------------------------
 '2.输出表格标题部分
 '-----------------------------
 Dim th() As String
 Redim th(9,1)
 
 th(0,0) = "width = ""1%"" align=""left"" nowrap "
 th(0,1) = "&nbsp;"
 
 th(1,0) = "width = ""1%"" align=""left"" nowrap "
 th(1,1) = "序号"
 
 th(2,0) = "Width=""15%"" align=""left"" "
 th(2,1) = "订单号"
 
 th(3,0) = "Width=""8%"" align=""left"" "
 th(3,1) = "周次"
 
 th(4,0) = "width = ""10%"" align=""left"" nowrap "
 th(4,1) = "易制毒品名称"
 
 th(5,0) = "width = ""10%"" align=""left"" nowrap "
 th(5,1) = "申请部门"
 
 th(6,0) = "width = ""10%"" align=""left"" nowrap  "
 th(6,1) = "上周余量"
 
 th(7,0) = "width = ""10%"" align=""left"" nowrap "
 th(7,1) = "本周领用量"
 
 th(8,0) = "width = ""10%"" align=""left"" nowrap  "
 th(8,1) = "本周使用量"
 
 th(9,0) = "width = ""10%"" align=""left"" nowrap  "
 th(9,1) = "本周剩余量"
 
 
 Call F.AppendTableHead(db,doc,th,"TableMain")
 
 Dim view As NotesView
 Dim vc As NotesViewEntryCollection

扫描二维码关注公众号,回复: 5914386 查看本文章

'搜索
' Dim formula As String
'  formula = {SELECT form="mainform" & sys_SuperUserdeal != "1" & sys_SoftDelete != "1"} 
' If doc.Drug(0) <> "" Then
'  formula = formula & { & @Contains(DrugName;"} & doc.Drug(0) & {")}
' End If 
' MsgBox "formula:" & formula
' Set vc = db.Search(formula, Nothing, 0)

'使用视图惊吓搜索排序
 If doc.Drug(0) <> "" Then
  Set vc = F.Getsearchkeyview(db, "v_key_total", view, doc.Drug(0), "True")
 Else
  Set vc = F.Getsortedview(db, "v_key_total", view)
 End If
 
 '找到最后一行的条数
 vccount = vc.Count
 
 
 If vc Is Nothing Then Error 20000, "文档集合无法找到,请与管理员联系!"
 'Call F.GetDataSetDetail_div_new(vc,doc,th,A)
 Call F.Getdatasetdetail_foronepage(vc, doc, th, A)
 Set doc = Nothing
 
 Exit Sub
errhandle:
 Call F.printerrmsg(doc,"Initialize")
 Exit Sub
End Sub
Sub Terminate
 
End Sub


%REM
 Function myCdbl
 Description: Comments for Function
%END REM

'文本转换为double类型
Function myCdbl(tstr As String) As Double
 If tstr = "" Then tstr = "0"
 myCdbl = CDbl(tstr)
End Function

下拉框,复选框多值显示

Dim kk As Integer
Dim tstr As String
For kk = 0 To UBound(tempdoc.Use)
 tstr = tstr & tempdoc.Use(kk) & ","
Next
 tstr = Left(tstr,Len(tstr)-1)
 th(7,1) = tstr

Dim Formula As String
Dim view As NotesView 
Dim SearchKey(0) As String

'没有搜索条件的
Set vc = F.GetSortedView(db, "v_all", view) 
'有搜索条件的
SearchKey(0) = 域名

If vc.count>0 Then
 Call vc.Ftsearch(Formula, 0)
End If

Lotus Notes常用代码
1.检测当前用户是不是文档的创建者,如果不是,不允许编辑文档。
Sub Querymodechange(Source As Notesuidocument, Continue As Variant)
Dim session As New NotesSession
Dim doc As notesdocument
Dim userName As New NotesName(session.UserName)
Set doc=source.document
If Not ( source.EditMode ) Then
If ( doc.authors(0) = username.CANONICAL ) Then
continue=True
Else
Msgbox "您不是此文档的创建人,不可以修改!",0,"文档数据库"
continue=False
End If
End If
End Sub


2.退出时检测关键的域不能为空
Sub Click(Source As Button)
Dim w As New notesuiworkspace
Dim uidoc As notesuidocument
Dim doc As notesdocument
Set uidoc=w.currentdocument
name1=uidoc.fieldgettext("name")
If name1="" Then
Messagebox "姓名不能为空!",0,"通讯录"
Exit Sub
End If
Call uidoc.save
Call uidoc.close
End Sub


3.用私有视图来显示需要当前用户处理的文档,用以下视图公式:
注意建立视图时不要选中"保存到本地"选项,否则调试不便.
SELECT Form = "收文1" & NextApprover=@Name([CN];@V3UserName)


4.Notes中Active控件
当文档中添加OLE或其他通用的ActiveX控件后,在文档的script编辑框右侧中,会自动添
加各种属性和方法在notes的类列表中.在script中声明该对象的 方法如下:
Sub Postopen(Source As Notesuidocument)
Dim w as notesuiworkspace
Dim uidoc as notesuidocument
Dim aa As Variant
Set w =New notesuiworkspace
Set uidoc =w.currentdocument
Set aa=uidoc. getObject("Chart")'该句为ole对象声明,注意Chart是你给对象起的名
字 '接下来你就可以通过aa.**来调用其方法和属性了.
End Sub


5.以下是script错误陷阱代码
Sub subname On Error Goto Errcode '下面添加你的程序代码
Exit Sub Errcode: Msgbox "错误 (" & Cstr(Err) & " ) -> " & Error$(Err),16,"错
误提示"
Exit Sub
End Sub


6.是否保存
在表单中设定一个域,名称为saveoptions
下列公式添加到返回按钮中,决定文件退出是否保存
FIELD saveoptions:="1"; 保存 FIELD saveoptions:="0"; 不保存


7.用公式弹出对话框,按确定继续,取消返回.
@If(@DialogBox("表单名";[AutoHorzFit]:[AutoVertFit];"表单标题");"";@Return("
"))


8.用script弹出对话框,按确定继续,取消返回
Dim w as notesuiworkspace
If Not w.dialogbox("表单名",True,True,False,True,False,False,"填写")
Then doc.close'用户按取消退出
Exit Sub
End If


9.视图中删除文档语句
@Command([EditClear]);
@Command([ViewRefreshFields])


10.检测是否是周末
Dim dt as notesdatetime
call dt.setnow
If Weekday(dt.lslocaltime)=7
Then'是周六耶,
dt.adjustday(2) '加两天到星期一
Elseif Weekday(dt.lslocaltime)=1
Then'周日加一天
dt.adjustday(1)
End If


11.得到当前的服务器和路径
公式: ResideServer := @Subset(@DbName; 1) ;
CurrentPath := @Subset(@DbName; -1) ;
DirOnly := @If(@Contains(CurrentPath; "\\");
@LeftBack(CurrentPath; "\\") + "\\"; "");
DbFile := DirOnly + "***.NSF";


12.得到当前用户名
公式:@Name([CN];@V3UserName)
scriptim s as notessession
Dim myname as newnotesname(s.username)
messagebox myname.common


13.得到当前日期公式:
@today @date(@created)
scriptim dt as notesdatetime
Set dt=New notesdatetime("")
Call dt.setnow


14.常用全局对象声明 '-----对象变量-----
Dim w As NotesUIWorkspace
Dim s As NotesSession
Dim db As NotesDatabase
Dim view As NotesView
Dim uidoc As NotesUIDocument
Dim doc As NotesDocument
Dim item As NotesItem
Dim dt As NotesDateTime
Dim username as notesname


15.一些计算域,开始时没有值,如果不给它一个值会报错,以下公式给计算域赋值
@if(Bfield="";0;Bfield)


16.特殊字符
@char(13)可以在@prompt提示框中显示回车 script中用函数chr(13)


17.再notes状态兰中显示进度条
(Declarations) Const NPB_STATUSBAR% = 32
Declare Sub NEMProgressEnd Lib "nnotesws.dll" ( Byval hwnd As Long ) Declare
Function NEMProgressBegin Lib "nnotesws.dll" ( Byval wFlags As Integer ) As
Long
Declare Sub NEMProgressSetBarPos Lib "nnotesws.dll" ( Byval hwnd As Long, By
val dwPos As Long)
Declare Sub NEMProgressSetBarRange Lib "nnotesws.dll" ( Byval hwnd As Long, 
Byval dwMax As Long )
Declare Sub NEMProgressSetText Lib "nnotesws.dll" ( Byval hwnd As Long, Byva
l pcszLine1 As String, Byval pcszLine2 As String )
Sub Click(Source As Button)
Dim hwnd As Long Dim i As Long
Dim j As Long 'Create the progress bar hwnd = NEMProgressBegin( NPB_STATUSBA
R ) 'Set the bar range - the default is 100 NEMProgressSetBarRange hwnd, 100

For i = 0 To 100 'Simple delay for the example!!
For j = 0 To 5000 Next 'Update the bar position NEMProgressSetBarPos hwnd, i
Next 'Destroy the dialog when we're done NEMProgressEnd hwnd End Sub

 '封样搜素公式
 fyformula = {a:=@Text(@Month(FYDATE));@If(@Length(a)=1;a:="0"+a;"");b:=@Text(@Day(FYDATE));@If(@Length(b)=1;b:="0"+b;"");}
 fyformula  = fyformula+{SELECT @Contains(form;"f_NewProduct" )& RESULT="通过" & IsHistory!="1"}
 '换样搜素公式
 hyformula = {a:=@Text(@Month(HuanYangDate));@If(@Length(a)=1;a:="0"+a;"");b:=@Text(@Day(HuanYangDate));@If(@Length(b)=1;b:="0"+b;"");}
 hyformula  = hyformula+{ SELECT form="f_HuanYangJL"  }
 
 '加上日期搜素
 If SearchKey(1) <> "" And SearchKey(2)<>"" Then
  fyformula = fyformula + { & FYDATE!=""}
  fyformula = fyformula + { & @TextToNumber(@Text(@Year(FYDATE))+a+b)>=@TextToNumber(@ReplaceSubstring("} + SearchKey(1) + {";"-";""))}
  fyformula = fyformula + { & @TextToNumber(@Text(@Year(FYDATE))+a+b)<=@TextToNumber(@ReplaceSubstring("} + SearchKey(2) + {";"-";""))}
  
  hyformula = hyformula + { & @TextToNumber(@Text(@Year(HuanYangDate))+a+b)>=
@TextToNumber(@ReplaceSubstring("} + SearchKey(1) + {";"-";""))}
  hyformula = hyformula + { & @TextToNumber(@Text(@Year(HuanYangDate))+a+b)<=@TextToNumber(@ReplaceSubstring("} + SearchKey(2) + {";"-";""))}
 End If

申请人根据登录来填写

Creater

tempstr:=@DbLookup(class : "NoCache" ; "" : Sys_SYSDB ;"v_or_deptbyperson_new"; @UserName;3);

@If(@IsError(tempstr);"";tempstr)

下拉框,单选框,复选框复制的方式:

第一种写公式:

server := @Name([CN]; @Subset(@DbName; 1));

database := @LeftBack(@Subset(@DbName;-1);DbsearchKey) +DbsearchKey+ "e_multData.nsf";

show:= @DbLookup("":"NoCache";server:database;"v_module_bydataName";Sys_CURDB2+"  字段名";2);

@If(@IsError(show);"";"---请选择---|":show)

第二种字节写死:

名称 | 1

名称2 | 2

多行文本显示:@Implode(域名;"<br />")

代理里面多值数据的显示:

Dim kk As Integer

Dim tstr As String

For kk = 0 To UBound(tempdoc.Use)

tstr = tstr & tempdoc.Use(kk) & ","

Next

tstr = Left(tstr,Len(tstr)-1)

th(7,1) = tstr

必填项的方法:

第一种在流程里面 提交必填域,字段记录维护要输入相应的中文描述

第二种在表单里判断:

Jsfunction savecheck(sel){

var msg = "";

msg += isnull_text("BDate","开始日期");

msg += isnull_text("EDate","结束日期");

msg += isnull_text("ZhaiYao","摘要");

if(msg!="")

{

alert(msg);

}

else

{

savesubmit(msg);

}

}

解决js的float加减精确bug

//用于解决js的float加减精确bug问题
Number.prototype.getB = function(){
var arr = this.toString().split('.');
return arr[1]? arr[1].length : 0;
}
Number.prototype.getP = function(to){
return Math.pow(10, Math.max(this.getB(), to.getB()));
}
Number.prototype.add = function(to){
var p = this.getP(to);
return (this * p + to * p) / p;
}
Number.prototype.sub = function(to){
var p = this.getP(to);
return (this * p - to * p) / p;
}


在搜索里面
If doc.Week(0) <> "" Then
  formula = formula & { & @Contains(WeekFor;"} & doc.Week(0) & {")}
  End if
---模糊搜索
周次这个字段,应该是判断是否相等的,不是判断包含的
formula = formula & { & WeekFor="} & doc.week(0) & {"}

某些文本内容的字段,才用模糊搜索
具体的数字,像周次这样的,就用相等去做比较

下拉框,单选按钮的配置,在多值数据里面
key:=Sys_CURDB2+"L0No";
database:=@LeftBack(@Subset(@DbName;-1);DbsearchKey) +DbsearchKey+ "e_multData.nsf";
show:= @DbLookup("":"NoCache";"":database;"v_module_bydataName";key;2);
@If(@IsError(show);"---请选择---|";"---请选择---|":show)


[转]解决JS浮点数(小数)计算加减乘除的BUG
问题这样的:

  37.5*5.5=206.08  (JS算出来是这样的一个结果,我四舍五入取两位小数)

  我先怀疑是四舍五入的问题,就直接用JS算了一个结果为:206.08499999999998

  怎么会这样,两个只有一位小数的数字相乘,怎么可能多出这么小数点出来。

  我Google了一下,发现原来这是JavaScript浮点运算的一个bug。

  比如:7*0.8 JavaScript算出来就是:5.6000000000000005

  网上找到了一些解决办法,就是重新写了一些浮点运算的函数。

  下面就把这些方法摘录下来,以供遇到同样问题的朋友参考:

  

   程序代码

//除法函数,用来得到精确的除法结果

// 说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。

//调用:accDiv(arg1,arg2)

//返回值:arg1除以arg2的精确结果

 function accDiv(arg1, arg2) {

        var t1 = 0, t2 = 0, r1, r2;

        try { t1 = arg1.toString().split(".")[1].length } catch (e) { }

        try { t2 = arg2.toString().split(".")[1].length } catch (e) { }

        with (Math) {

            r1 = Number(arg1.toString().replace(".", ""))

            r2 = Number(arg2.toString().replace(".", ""))

            return (r1 / r2) * pow(10, t2 - t1);

        }

    }

//给Number类型增加一个div方法,调用起来更加方便。

Number.prototype.div = function(arg) {

        return accDiv(this, arg);

    }

//乘法函数,用来得到精确的乘法结果

//说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。

//调用:accMul(arg1,arg2)

//返回值:arg1乘以 arg2的精确结果

function accMul(arg1, arg2) {

        var m = 0, s1 = arg1.toString(), s2 = arg2.toString();

        try { m += s1.split(".")[1].length } catch (e) { }

        try { m += s2.split(".")[1].length } catch (e) { }

        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)

    }

// 给Number类型增加一个mul方法,调用起来更加方便。

Number.prototype.mul = function(arg) {

        return accMul(arg, this);

    }

//加法函数,用来得到精确的加法结果

//说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。

//调用:accAdd(arg1,arg2)

// 返回值:arg1加上arg2的精确结果

function accAdd(arg1, arg2) {

        var r1, r2, m, c;

        try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }

        try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }

        c = Math.abs(r1 - r2);
        m = Math.pow(10, Math.max(r1, r2))
        if (c > 0) {
            var cm = Math.pow(10, c);
            if (r1 > r2) {
                arg1 = Number(arg1.toString().replace(".", ""));
                arg2 = Number(arg2.toString().replace(".", "")) * cm;
            }
            else {
                arg1 = Number(arg1.toString().replace(".", "")) * cm;
                arg2 = Number(arg2.toString().replace(".", ""));
            }
        }
        else {
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", ""));
        }
        return (arg1 + arg2) / m

    }

//给Number类型增加一个add方法,调用起来更加方便。

 Number.prototype.add = function(arg) {

        return accAdd(arg, this);

    }

//减法函数,用来得到精确的减法结果

//说明:javascript的减法结果会有误差,在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。

//调用:accSub(arg1,arg2)

// 返回值:arg1加上arg2的精确结果

function accSub(arg1,arg2){
   var r1,r2,m,n;
   try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
   try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
   m=Math.pow(10,Math.max(r1,r2));
   //last modify by deeka
   //动态控制精度长度
   n=(r1>=r2)?r1:r2;
   return ((arg1*m-arg2*m)/m).toFixed(n);
}

 
  在你要用的地方包含这些函数,然后调用它来计算就可以了。

  比如你要计算:7*0.8 ,则改成 (7).mul(8)

  其它运算类似,就可以得到比较精确的结果。


server := @Name([CN]; @Subset(@DbName; 1));
database := @LeftBack(@Subset(@DbName;-1);DbSearchKey) + DbSearchKey + "app_XCPPTInfo.nsf";
tempstr:=@DbLookup(class : "NoCache" ; server : database ;"v_Key_ShengBaoDanWei_QiYong"; ShengBaoDanWei;2);
@If(@IsError(tempstr);"";tempstr)

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.Vector;

import lotus.domino.AgentBase;
import lotus.domino.AgentContext;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.DocumentCollection;
import lotus.domino.NotesError;
import lotus.domino.NotesException;
import lotus.domino.Session;
import lotus.domino.View;

public class JavaAgent extends AgentBase {
 public PublicFunction F = new PublicFunction();

 public static Vector rowItems = null;
 public static Database asDb = null;
 public static Document tempDoc = null;
 
 public static Connection conn = null;
 public static PreparedStatement ps = null;
 public static ResultSet rs = null;

 public void NotesMain() {
  Session session = null;
  AgentContext agentContext = null;
  Database db = null;
  Document doc = null;
  PrintWriter pw = null;
  try {
   session = getSession();
   agentContext = session.getAgentContext();
   db = agentContext.getCurrentDatabase();
   doc = agentContext.getDocumentContext();
   pw = getAgentOutput();
   asDb = session.getDatabase("oerp", "oadata/app_AfterSales.nsf");
   if (!asDb.isOpen())
    asDb.open();
   rowItems = doc.getItemValue("RowItems");
   if(saveReimToDatabase(rowItems, db, session, doc))
   {
    pw.println("<script>alert(\"数据已成功写入数据库\")</script>");
   }else{
    pw.println("<script>alert(\"数据写入数据库失败\")</script>");
   }
  } catch (Exception e) {
   try {
    doc.replaceItemValue("errmsg_sys",e.getLocalizedMessage());
   } catch (NotesException e1) {
    e1.printStackTrace();
   }
  }finally{
   try {
    if(db != null)db.recycle();
    if(doc != null)doc.recycle();
    if(rowItems != null)rowItems = null;
    if(asDb !=null)asDb.recycle();
    if(tempDoc != null)tempDoc.recycle();
    if(session != null)session.recycle();
    if(agentContext != null)agentContext.recycle();
    if(conn != null)conn.close();
    if(rs != null)rs.close();
    if(ps != null)ps.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * @param universalId
  * @return Document
  * @throws NotesException
  */
 protected Document getReimDocumentById(String universalId) throws NotesException {
  try {
   return asDb.getDocumentByUNID(universalId);
  } catch (NotesException e) {
   if(e.id == NotesError.NOTES_ERR_BAD_UNID)
    return null;
   else
    throw e;
  }
 }
 
 protected boolean saveReimToDatabase(Vector vector, Database db, Session session, Document doc) throws Exception {
  Document subDoc = null;
  DocumentCollection dc = null;
  try {
   String sql = "INSERT INTO T_REIMBUSEMENT_DETAILS (V_ID," + // 拜访活动ID
               "SA_ID," + // 派遣单ID
               "S_ID," + // 业务员ID
               "PEOPLE_SORT," + // 人员分类
               "RE_TYPE," + // 费用类型
               "RE_MONEY," + // 费用金额
               "RE_ORDER_ID," + // 报销单号
               "CREATE_DATE," + // 报销时间
               "RE_DATE," +
               "CUSTOMER_ID) VALUES (" + // 创建时间
               "?,?,?,?,?,?,?,?,?,?)";
   conn = F.OpenDB("oerp", db, session);
   ps = conn.prepareStatement(sql);
   String fareTypeSql = "SELECT NAME FROM T_COSTTYPE WHERE ID = ?";
   String orderNumber = doc.getItemValueString("OrderNumber");
   Date date = getSQLSystemDate();
   int i = 0;
   String reimStr = "0";
   for (Iterator it = vector.iterator(); it.hasNext();) {
    String universalId = (String) it.next();
    tempDoc = getReimDocumentById(universalId);
    if (tempDoc != null) {
     dc = getSubDocumentCollection(tempDoc.getItemValueString("KEYUNID"));
     subDoc = dc.getFirstDocument();
     if (subDoc != null) {
      if(!subDoc.getItemValueString("CurrRemain").equals(""))
       reimStr = subDoc.getItemValueString("CurrRemain");
      float reim = Float.parseFloat(reimStr);
      ps.setString(1, "");
      ps.setString(2, tempDoc.getItemValueString("ApplyNumber"));
      ps.setString(3, getSalesmanWorkIdByName(tempDoc.getItemValueString("ReimbursementMan"),session));
      ps.setInt(4, 0);
      ps.setString(5, getFareTypeName(session, db, fareTypeSql, subDoc.getItemValueString("FareType")));
      ps.setFloat(6, reim);
      ps.setString(7, orderNumber);
      ps.setDate(8, date);
      ps.setDate(9, date);
      ps.setString(10, getCustomerIdbyCustomerName(tempDoc.getItemValueString("CustomerName")));
      ps.addBatch();
      i++;
      subDoc = dc.getNextDocument(subDoc);
     }
    }
   }
   if (i > 0) {
    ps.executeBatch();
    return true;
   } else
    return false;
  } finally {
   if (subDoc != null)
    subDoc.recycle();
  }
 }
 
 /**
  * @return
  */
 protected Date getSQLSystemDate() {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  return Date.valueOf(sdf.format(new java.util.Date()));
 }
 
 /**
  * @param date
  * @return
  */
 protected Date formatSQLDate(String date) {
  try {
   return Date.valueOf(date);
  } catch (Exception ex) {
   ex.printStackTrace();
   return null;
  }
 }
 
 /**
  * @param keyUNID
  * @return
  * @throws NotesException
  */
 protected DocumentCollection getSubDocumentCollection(String keyUNID) throws NotesException {
  View subDocView = null;
  try {
   subDocView = asDb.getView("v_list_SubDoc_Fare");
   return subDocView.getAllDocumentsByKey(keyUNID);
  } finally{
   if(subDocView != null)subDocView.recycle();
  }
 }
 
 /**
  * Get the type name of the fare by the type id of the fare
  * @param session
  * @param db
  * @param sql Query sql
  * @param key Search key
  * @return String, the name of fare type
  * @throws SQLException
  */
 protected String getFareTypeName(Session session, Database db, String sql, String key) throws SQLException {
  
  PreparedStatement ps1 = null;
  try {
   ps1 = conn.prepareStatement(sql);
   ps1.setString(1, key);
   rs = ps1.executeQuery();
   String name = "";
   while (rs.next()) {
    name = rs.getString(1);
   }
   return name;
  } finally{
   if(ps1 != null)ps1.close();
  }
 }
 
 /**
  * @param customerName
  * @return customer id
  * @throws SQLException
  */
 protected String getCustomerIdbyCustomerName(String customerName) throws SQLException {
  PreparedStatement ps1 = null;
  try {
   String sql = "SELECT ID FROM T_KHDA WHERE FNAME = ?";
   ps1 = conn.prepareStatement(sql);
   ps1.setString(1, customerName);
   rs = ps1.executeQuery();
   String name = "";
   while (rs.next()) {
    name = rs.getString(1);
   }
   return name;
  } finally{
   if(ps1 != null)ps1.close();
  }
 }
 
 protected String getSalesmanWorkIdByName(String salesmanName,Session session) throws NotesException {
  Database sysDb = null;
  View sView = null;
  Document sDoc = null;
  
  try {
   sysDb = session.getDatabase("oerp", "oadata/AIS_Org.nsf");
   if (!asDb.isOpen())
    asDb.open();
   sView = sysDb.getView("v_or_deptbyperson_byname");
   sDoc = sView.getDocumentByKey(salesmanName);
   if(sDoc != null)
    return sDoc.getItemValueString("peWorkID");
   else
    return "";
  } finally{
   if(sysDb != null)sysDb.recycle();
   if(sView != null)sView.recycle();
   if(sDoc != null)sDoc.recycle();
  }
 }
}


 

猜你喜欢

转载自blog.csdn.net/vera514514/article/details/16338161
今日推荐