text stringlengths 14 6.51M |
|---|
unit Helpers;
{$IF CompilerVersion >= 21.0}
{$WEAKLINKRTTI ON}
{$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])}
{$IFEND}
interface
uses
Windows, //Winapi.Windows,
SysUtils, //System.SysUtils,
{$IFNDEF EXCLUDE_CLASSES}
Classes, //System.Classes,
{$ENDIF}
{$IFNDEF EXCLUDE_COMOBJ}
ComObj, //System.Win.ComObj,
{$ENDIF}
ActiveX; //Winapi.ActiveX;
type
{$IFDEF EXCLUDE_COMOBJ}
EOleError = class(Exception);
EOleSysError = class(EOleError)
private
FErrorCode: HRESULT;
public
constructor Create(const Message: UnicodeString; ErrorCode: HRESULT;
HelpContext: Integer);
property ErrorCode: HRESULT read FErrorCode write FErrorCode;
end;
EOleException = class(EOleSysError)
private
FSource: string;
FHelpFile: string;
public
constructor Create(const Message: string; ErrorCode: HRESULT;
const Source, HelpFile: string; HelpContext: Integer);
property HelpFile: string read FHelpFile write FHelpFile;
property Source: string read FSource write FSource;
end;
EOleRegistrationError = class(EOleSysError);
{$ENDIF}
EBaseException = class(EOleSysError)
private
function GetDefaultCode: HRESULT;
public
constructor Create(const Msg: string);
constructor CreateFmt(const Msg: string; const Args: array of const);
constructor CreateRes(Ident: Integer); overload;
constructor CreateRes(ResStringRec: PResStringRec); overload;
constructor CreateResFmt(Ident: Integer; const Args: array of const); overload;
constructor CreateResFmt(ResStringRec: PResStringRec; const Args: array of const); overload;
constructor CreateHelp(const Msg: string; AHelpContext: Integer);
constructor CreateFmtHelp(const Msg: string; const Args: array of const; AHelpContext: Integer);
constructor CreateResHelp(Ident: Integer; AHelpContext: Integer); overload;
constructor CreateResHelp(ResStringRec: PResStringRec; AHelpContext: Integer); overload;
constructor CreateResFmtHelp(ResStringRec: PResStringRec; const Args: array of const; AHelpContext: Integer); overload;
constructor CreateResFmtHelp(Ident: Integer; const Args: array of const; AHelpContext: Integer); overload;
end;
ECheckedInterfacedObjectError = class(EBaseException);
ECheckedInterfacedObjectDeleteError = class(ECheckedInterfacedObjectError);
ECheckedInterfacedObjectDoubleFreeError = class(ECheckedInterfacedObjectError);
ECheckedInterfacedObjectUseDeletedError = class(ECheckedInterfacedObjectError);
EInvalidCoreVersion = class(EBaseException);
type
TDebugName = String[99];
TCheckedInterfacedObject = class(TInterfacedObject, IInterface)
private
FName: TDebugName;
function GetRefCount: Integer;
protected
procedure SetName(const AName: String);
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
constructor Create;
procedure BeforeDestruction; override;
property RefCount: Integer read GetRefCount;
function SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; override;
end;
const
GUID_DefaultErrorSource: TGUID = '{1FC872DA-2917-48AC-8E51-552A7AD60E46}';
function HResultFromException(const E: Exception): HRESULT;
function HandleSafeCallException(Caller: TObject; ExceptObject: TObject; ExceptAddr: Pointer): HResult;
implementation
uses
PluginAPI,
{$IFDEF EXCLUDE_COMOBJ}
System.ComConst,
{$ENDIF}
CRC16;
{$IFDEF EXCLUDE_COMOBJ}
{ EOleSysError }
constructor EOleSysError.Create(const Message: UnicodeString; ErrorCode: HRESULT; HelpContext: Integer);
var
S: string;
begin
S := Message;
if S = '' then
begin
S := SysErrorMessage(Cardinal(ErrorCode));
if S = '' then
FmtStr(S, SOleError, [ErrorCode]);
end;
inherited CreateHelp(S, HelpContext);
FErrorCode := ErrorCode;
end;
{ EOleException }
constructor EOleException.Create(const Message: string; ErrorCode: HRESULT; const Source, HelpFile: string; HelpContext: Integer);
function TrimPunctuation(const S: string): string;
var
P: PChar;
begin
Result := S;
P := AnsiLastChar(Result);
while (Length(Result) > 0) and CharInSet(P^, [#0..#32, '.']) do
begin
SetLength(Result, P - PChar(Result));
P := AnsiLastChar(Result);
end;
end;
begin
inherited Create(TrimPunctuation(Message), ErrorCode, HelpContext);
FSource := Source;
FHelpFile := HelpFile;
end;
{$ENDIF}
resourcestring
rsInvalidDelete = 'Попытка удалить объект %s при активной интерфейсной ссылке; счётчик ссылок: %d';
rsDoubleFree = 'Попытка повторно удалить уже удалённый объект %s';
rsUseDeleted = 'Попытка использовать уже удалённый объект %s';
{ TCheckedInterfacedObject }
constructor TCheckedInterfacedObject.Create;
begin
FName := TDebugName(Format('[$%s] %s', [IntToHex(PtrUInt(Self), SizeOf(Pointer) * 2), ClassName]));
inherited;
end;
procedure TCheckedInterfacedObject.SetName(const AName: String);
begin
FillChar(FName, SizeOf(FName), 0);
FName := TDebugName(AName);
end;
procedure TCheckedInterfacedObject.BeforeDestruction;
begin
if FRefCount < 0 then
raise ECheckedInterfacedObjectDoubleFreeError.CreateFmt(rsDoubleFree, [String(FName)])
else
if FRefCount <> 0 then
raise ECheckedInterfacedObjectDeleteError.CreateFmt(rsInvalidDelete, [String(FName), FRefCount]);
inherited;
FRefCount := -1;
end;
function TCheckedInterfacedObject.GetRefCount: Integer;
begin
if FRefCount < 0 then
Result := 0
else
Result := FRefCount;
end;
function TCheckedInterfacedObject._AddRef: Integer;
begin
if FRefCount < 0 then
raise ECheckedInterfacedObjectUseDeletedError.CreateFmt(rsUseDeleted, [String(FName)]);
Result := InterlockedIncrement(FRefCount);
end;
function TCheckedInterfacedObject._Release: Integer;
begin
Result := InterlockedDecrement(FRefCount);
if Result = 0 then
Destroy;
end;
function TCheckedInterfacedObject.SafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer): HResult;
begin
Result := HandleSafeCallException(Self, ExceptObject, ExceptAddr);
end;
{ EBaseException }
function EBaseException.GetDefaultCode: HRESULT;
begin
Result := MakeResult(SEVERITY_ERROR, FACILITY_ITF, CalcCRC16(ClassName));
end;
constructor EBaseException.Create(const Msg: string);
begin
inherited Create(Msg, GetDefaultCode, 0);
end;
constructor EBaseException.CreateFmt(const Msg: string; const Args: array of const);
begin
inherited Create(Format(Msg, Args), GetDefaultCode, 0);
end;
constructor EBaseException.CreateFmtHelp(const Msg: string; const Args: array of const; AHelpContext: Integer);
begin
inherited Create(Format(Msg, Args), GetDefaultCode, AHelpContext);
end;
constructor EBaseException.CreateHelp(const Msg: string; AHelpContext: Integer);
begin
inherited Create(Msg, GetDefaultCode, AHelpContext);
end;
constructor EBaseException.CreateRes(Ident: Integer);
begin
inherited Create(LoadStr(Ident), GetDefaultCode, 0);
end;
constructor EBaseException.CreateRes(ResStringRec: PResStringRec);
begin
inherited Create(LoadResString(ResStringRec), GetDefaultCode, 0);
end;
constructor EBaseException.CreateResFmt(Ident: Integer; const Args: array of const);
begin
inherited Create(Format(LoadStr(Ident), Args), GetDefaultCode, 0);
end;
constructor EBaseException.CreateResFmt(ResStringRec: PResStringRec; const Args: array of const);
begin
inherited Create(Format(LoadResString(ResStringRec), Args), GetDefaultCode, 0);
end;
constructor EBaseException.CreateResFmtHelp(ResStringRec: PResStringRec; const Args: array of const; AHelpContext: Integer);
begin
inherited Create(Format(LoadResString(ResStringRec), Args), GetDefaultCode, AHelpContext);
end;
constructor EBaseException.CreateResFmtHelp(Ident: Integer; const Args: array of const; AHelpContext: Integer);
begin
inherited Create(Format(LoadStr(Ident), Args), GetDefaultCode, AHelpContext);
end;
constructor EBaseException.CreateResHelp(Ident, AHelpContext: Integer);
begin
inherited Create(LoadStr(Ident), GetDefaultCode, AHelpContext);
end;
constructor EBaseException.CreateResHelp(ResStringRec: PResStringRec; AHelpContext: Integer);
begin
inherited Create(LoadResString(ResStringRec), GetDefaultCode, AHelpContext);
end;
// _____________________________________________________________________________
type
OleSysErorClass = class of EOleSysError;
OleExceptionClass = class of EOleException;
function HResultFromException(const E: Exception): HRESULT;
begin
if E.ClassType = Exception then
Result := E_UNEXPECTED
else
if E is EOleSysError then
Result := EOleSysError(E).ErrorCode
else
if E is EOSError then
Result := HResultFromWin32(EOSError(E).ErrorCode)
else
Result := MakeResult(SEVERITY_ERROR, FACILITY_ITF, CalcCRC16(E.ClassName));
end;
function HandleSafeCallException(Caller: TObject; ExceptObject: TObject; ExceptAddr: Pointer): HResult;
var
E: TObject;
CreateError: ICreateErrorInfo;
ErrorInfo: IErrorInfo;
Source: WideString;
begin
Result := E_UNEXPECTED;
E := ExceptObject;
if Succeeded(CreateErrorInfo(CreateError)) then
begin
Source := 'pluginsystem.' + Caller.ClassName;
CreateError.SetSource(PWideChar(Source));
if E is Exception then
begin
CreateError.SetDescription(PWideChar(WideString(Exception(E).Message)));
CreateError.SetHelpContext(Exception(E).HelpContext);
if (E is EOleSysError) and (EOleSysError(E).ErrorCode < 0) then
Result := EOleSysError(E).ErrorCode
else
if E is EOSError then
Result := HResultFromWin32(EOleSysError(E).ErrorCode)
else
Result := HResultFromException(Exception(E));
end;
if HResultFacility(Result) = FACILITY_ITF then
CreateError.SetGUID(GUID_DefaultErrorSource)
else
CreateError.SetGUID(GUID_NULL);
if CreateError.QueryInterface(IErrorInfo, ErrorInfo) = S_OK then
SetErrorInfo(0, ErrorInfo);
end;
end;
procedure CustomSafeCallError(ErrorCode: HResult; ErrorAddr: Pointer);
function CreateExceptionFromCode(ACode: HRESULT): Exception;
var
ExceptionClass: ExceptClass;
ErrorInfo: IErrorInfo;
Source, Description, HelpFile: WideString;
HelpContext: Longint;
begin
if HResultFacility(ACode) = FACILITY_WIN32 then
ExceptionClass := EOSError
else
case HRESULT(ErrorCode) of
{E_ArgumentException: ExceptionClass := EArgumentException;
E_ArgumentOutOfRangeException: ExceptionClass := EArgumentOutOfRangeException;
E_PathTooLongException: ExceptionClass := EPathTooLongException;
E_NotSupportedException: ExceptionClass := ENotSupportedException;
E_DirectoryNotFoundException: ExceptionClass := EDirectoryNotFoundException;
E_FileNotFoundException: ExceptionClass := EFileNotFoundException;
E_NoConstructException: ExceptionClass := ENoConstructException;}
E_Abort: ExceptionClass := EAbort;
E_HeapException: ExceptionClass := EHeapException;
E_OutOfMemory: ExceptionClass := EOutOfMemory;
E_InOutError: ExceptionClass := EInOutError;
E_InvalidPointer: ExceptionClass := EInvalidPointer;
E_InvalidCast: ExceptionClass := EInvalidCast;
E_ConvertError: ExceptionClass := EConvertError;
E_VariantError: ExceptionClass := EVariantError;
E_PropReadOnly: ExceptionClass := EPropReadOnly;
E_PropWriteOnly: ExceptionClass := EPropWriteOnly;
E_AssertionFailed: ExceptionClass := EAssertionFailed;
E_AbstractError: ExceptionClass := EAbstractError;
E_IntfCastError: ExceptionClass := EIntfCastError;
E_InvalidContainer: ExceptionClass := EInvalidContainer;
E_InvalidInsert: ExceptionClass := EInvalidInsert;
E_PackageError: ExceptionClass := EPackageError;
{E_Monitor: ExceptionClass := EMonitor;
E_MonitorLockException: ExceptionClass := EMonitorLockException;
E_NoMonitorSupportException: ExceptionClass := ENoMonitorSupportException;
E_ProgrammerNotFound: ExceptionClass := EProgrammerNotFound;}
{$IFNDEF EXCLUDE_CLASSES}
E_StreamError: ExceptionClass := EStreamError;
E_FileStreamError: ExceptionClass := EFileStreamError;
E_FCreateError: ExceptionClass := EFCreateError;
E_FOpenError: ExceptionClass := EFOpenError;
E_FilerError: ExceptionClass := EFilerError;
E_ReadError: ExceptionClass := EReadError;
E_WriteError: ExceptionClass := EWriteError;
E_ClassNotFound: ExceptionClass := EClassNotFound;
E_MethodNotFound: ExceptionClass := EMethodNotFound;
E_InvalidImage: ExceptionClass := EInvalidImage;
E_ResNotFound: ExceptionClass := EResNotFound;
E_ListError: ExceptionClass := EListError;
E_BitsError: ExceptionClass := EBitsError;
E_StringListError: ExceptionClass := EStringListError;
E_ComponentError: ExceptionClass := EComponentError;
E_ParserError: ExceptionClass := EParserError;
E_OutOfResources: ExceptionClass := EOutOfResources;
E_InvalidOperation: ExceptionClass := EInvalidOperation;
{$ENDIF}
E_CheckedInterfacedObjectError: ExceptionClass := ECheckedInterfacedObjectError;
E_CheckedInterfacedObjectDeleteError: ExceptionClass := ECheckedInterfacedObjectDeleteError;
E_CheckedInterfacedObjectDoubleFreeError: ExceptionClass := ECheckedInterfacedObjectDoubleFreeError;
E_CheckedInterfacedObjectUseDeletedError: ExceptionClass := ECheckedInterfacedObjectUseDeletedError;
E_InvalidCoreVersion: ExceptionClass := EInvalidCoreVersion;
else
ExceptionClass := EOleException;
end;
if GetErrorInfo(0, ErrorInfo) = S_OK then
begin
ErrorInfo.GetSource(Source);
ErrorInfo.GetDescription(Description);
ErrorInfo.GetHelpFile(HelpFile);
ErrorInfo.GetHelpContext(HelpContext);
end
else
begin
Source := '';
Description := '';
HelpFile := '';
HelpContext := 0;
end;
if ExceptionClass.InheritsFrom(EOleException) then
Result := OleExceptionClass(ExceptionClass).Create(Description, ACode, Source, HelpFile, HelpContext)
else
if ExceptionClass.InheritsFrom(EOleSysError) then
Result := OleSysErorClass(ExceptionClass).Create(Description, ACode, HelpContext)
else
begin
Result := ExceptionClass.Create(Description);
if Result is EOSError then
EOSError(Result).ErrorCode := HResultCode(ACode);
end;
end;
var
E: Exception;
begin
E := CreateExceptionFromCode(HRESULT(ErrorCode));
raise E at ErrorAddr;
end;
initialization
SafeCallErrorProc := CustomSafeCallError;
finalization
SafeCallErrorProc := nil;
end.
|
unit TestMonthlyAverageValueObj;
interface
uses
DUnitX.TestFramework,
System.Net.HttpClient, System.Net.HttpClientComponent,
SecurityUtilityUnit, System.Classes, System.SysUtils;
type
[TestFixture]
TTestMonthlyAverageValueObj = class(TObject)
strict private
aNetHTTPRequest: TNetHTTPRequest;
aNetHTTPClient: TNetHTTPClient;
aSecurityUtil : TSecuritiesUtility;
aCSVData : string;
procedure InitData(newpath : string);
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure TestMonthlyAverageValue_EndBeforeStart;
[Test]
procedure TestMonthlyAverageValue_BadTicker;
[Test]
procedure TestMonthlyAverageValue_OneMonth;
[Test]
procedure TestMonthlyAverageValue_PartialMonth;
[Test]
procedure TestMonthlyAverageValue_MultiPartialMonths;
end;
implementation
procedure TTestMonthlyAverageValueObj.InitData(newpath: string);
begin
aCSVData := aNetHTTPRequest.Get(newPath).ContentAsString();
aSecurityUtil.LoadDataSetfromCSV(aCSVData);
Assert.IsTrue(aSecurityUtil.SecuritiesData.Active,'DataSet is not active');
Assert.IsTrue(aSecurityUtil.SecuritiesData.RecordCount > 0,'DataSet has no Records');
end;
procedure TTestMonthlyAverageValueObj.Setup;
begin
aSecurityUtil := TSecuritiesUtility.Create(['ticker','date','open','close','high','low','volume']);
aNetHTTPRequest := TNetHTTPRequest.Create(nil);
aNetHTTPClient := TNetHTTPClient.Create(nil);
aNetHTTPRequest.Client := aNetHTTPClient;
InitData('https://www.quandl.com/api/v3/datatables'+
'/WIKI/PRICES.csv?date.gte=20170101&date.lte=20170630&ticker=COF,GOOGL,MSFT'+
'&qopts.columns=ticker,date,open,close,high,low,volume&'+
'api_key=s-GMZ_xkw6CrkGYUWs1p');
end;
procedure TTestMonthlyAverageValueObj.TearDown;
begin
aSecurityUtil.Destroy;
aNetHTTPClient.Destroy;
aNetHTTPRequest.Destroy;
end;
procedure TTestMonthlyAverageValueObj.TestMonthlyAverageValue_BadTicker;
var
testList : TList;
begin
testList := aSecurityUtil.MonthlyAverageValue('BADVALUE',StrToDate('1/1/17'),StrToDate('1/31/17'));
Assert.IsNull(testList,'Using a bad security ticker code should have returned nil.');
end;
procedure TTestMonthlyAverageValueObj.TestMonthlyAverageValue_EndBeforeStart;
var
testList : TList;
begin
testList := aSecurityUtil.MonthlyAverageValue('MSFT',StrToDate('1/30/17'),StrToDate('1/1/17'));
Assert.IsNull(testList,'End Date before Start Date should have returned nil.');
end;
procedure TTestMonthlyAverageValueObj.TestMonthlyAverageValue_OneMonth;
var
testList : TList;
begin
testList := aSecurityUtil.MonthlyAverageValue('GOOGL',StrToDate('3/1/17'),StrToDate('3/31/17'));
Assert.AreEqual(TStringList(testList[0])[2],'average_open:853.86',
TStringList(testList[0])[2] + '<> average_open:853.86 -> Calculation Error');
Assert.AreEqual(TStringList(testList[0])[3],'average_close:853.79',
TStringList(testList[0])[3] + '<> average_open:853.79 -> Calculation Error');
end;
procedure TTestMonthlyAverageValueObj.TestMonthlyAverageValue_PartialMonth;
var
testList : TList;
startDt, endDt : string;
begin
testList := aSecurityUtil.MonthlyAverageValue('GOOGL',StrToDate('3/5/17'),StrToDate('3/15/17'));
Assert.AreEqual(TStringList(testList[0])[2],'average_open:857.02',
'GOOGL avg open -> Calculation Error');
Assert.AreEqual(TStringList(testList[0])[3],'average_close:858.77',
'GOOGL avg close -> Calculation Error');
end;
procedure TTestMonthlyAverageValueObj.TestMonthlyAverageValue_MultiPartialMonths;
var
testList : TList;
begin
testList := aSecurityUtil.MonthlyAverageValue('COF',StrToDate('2/5/17'),StrToDate('5/8/17'));
//Month of February for COF
Assert.AreEqual(TStringList(testList[0])[0],'COF',
TStringList(testList[0])[0] + '<> COF -> Ticker Not Expected');
Assert.AreEqual(TStringList(testList[0])[2],'average_open:90.28',
TStringList(testList[0])[2] + '<> average_open:90.28 -> Calculation Error');
Assert.AreEqual(TStringList(testList[0])[3],'average_close:90.75',
TStringList(testList[0])[3] + '<> average_open:90.75 -> Calculation Error');
testList := aSecurityUtil.MonthlyAverageValue('GOOGL',StrToDate('2/5/17'),StrToDate('5/8/17'));
//Month of May for GOOGL
Assert.AreEqual(TStringList(testList[3])[0],'GOOGL',
TStringList(testList[3])[0] + '<> GOOGL -> Ticker Not Expected');
Assert.AreEqual(TStringList(testList[3])[2],'average_open:941.32',
TStringList(testList[3])[2] + '<> average_open:941.32 -> Calculation Error');
Assert.AreEqual(TStringList(testList[3])[3],'average_close:947.01',
TStringList(testList[3])[3] + '<> average_open:947.01 -> Calculation Error');
testList := aSecurityUtil.MonthlyAverageValue('MSFT',StrToDate('2/5/17'),StrToDate('5/8/17'));
//Month of March for MSFT
Assert.AreEqual(TStringList(testList[1])[0],'MSFT',
TStringList(testList[1])[0] + '<> MSFT -> Ticker Not Expected');
Assert.AreEqual(TStringList(testList[1])[2],'average_open:64.76',
TStringList(testList[1])[2] + '<> average_open:64.76 -> Calculation Error');
Assert.AreEqual(TStringList(testList[1])[3],'average_close:64.84',
TStringList(testList[1])[3] + '<> average_open:64.84 -> Calculation Error');
end;
initialization
TDUnitX.RegisterTestFixture(TTestMonthlyAverageValueObj);
end.
|
unit URepositorioUsuario;
interface
uses
URepositorioDB
, UEntidade
, UUsuario
, SqlExpr
;
type
TRepositorioUsuario = class(TRepositorioDB<TUSUARIO>)
protected
//Atribui os dados do banco no objeto
procedure AtribuiDBParaEntidade(const coUSUARIO: TUSUARIO); override;
//Atribui os dados do objeto no banco
procedure AtribuiEntidadeParaDB(const coUSUARIO: TUSUARIO;
const coSQLQuery: TSQLQuery); override;
public
constructor Create;
function RetornaPeloLogin(const csLogin: String): TUSUARIO;
end;
implementation
{ TRepositorioUsuario }
uses
UDM
, UMensagens
;
const
CNT_SELECT_PELO_LOGIN = 'select * from usuario where nome = :nome';
procedure TRepositorioUsuario.AtribuiDBParaEntidade(const coUSUARIO: TUSUARIO);
begin
inherited;
coUSUARIO.NOME := FSQLSelect.FieldByName(FLD_USUARIO_NOME).AsString;
coUSUARIO.SENHA := FSQLSelect.FieldByName(FLD_USUARIO_SENHA).AsString;
coUSUARIO.EMAIL := FSQLSelect.FieldByName(FLD_USUARIO_EMAIL).AsString;
end;
procedure TRepositorioUsuario.AtribuiEntidadeParaDB(const coUSUARIO: TUSUARIO;
const coSQLQuery: TSQLQuery);
begin
inherited;
coSQLQuery.ParamByName(FLD_USUARIO_NOME).AsString := coUSUARIO.NOME;
coSQLQuery.ParamByName(FLD_USUARIO_SENHA).AsString := coUSUARIO.SENHA;
coSQLQuery.ParamByName(FLD_USUARIO_EMAIL).AsString := coUSUARIO.EMAIL;
end;
constructor TRepositorioUsuario.Create;
begin
Inherited Create(TUSUARIO, TBL_USUARIO, FLD_ENTIDADE_ID, STR_USUARIO);
end;
function TRepositorioUsuario.RetornaPeloLogin(const csLogin: String): TUSUARIO;
begin
FSQLSelect.Close;
FSQLSelect.CommandText := CNT_SELECT_PELO_LOGIN;
FSQLSelect.Prepared := True;
FSQLSelect.ParamByName(FLD_USUARIO_NOME).AsString := csLogin;
FSQLSelect.Open;
Result := nil;
if not FSQLSelect.Eof then
begin
Result := TUSUARIO.Create;
AtribuiDBParaEntidade(Result);
end;
end;
end.
|
unit MainUnit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
//Windows, ShellAPI,
VirtualTrees,
LCLIntf,
PE.Common,
PE.Image,
PE.ExportSym
;
type
{ TMainForm }
TMainForm = class(TForm)
CodeGenButton: TButton;
CodeMemo: TMemo;
FuncsVST: TVirtualStringTree;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
OpenDialog1: TOpenDialog;
OrgDllFileNameBtn: TButton;
OrgDllFileNameEdit: TEdit;
PointDllNameEdit: TEdit;
SaveDialog1: TSaveDialog;
procedure CodeGenButtonClick(Sender: TObject);
procedure FormDropFiles(Sender: TObject; const FileNames: array of String);
procedure FuncsVSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: String);
procedure Label3Click(Sender: TObject);
procedure Label3MouseEnter(Sender: TObject);
procedure Label3MouseLeave(Sender: TObject);
procedure OrgDllFileNameBtnClick(Sender: TObject);
private
{ private declarations }
fPEImage: TPEImage;
procedure LoadDLL(const aDLLFileName: String);
public
{ public declarations }
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
function ExtractJustName(const FileName: String): String;
begin
Result := ExtractFileName(FileName);
SetLength(Result, Length(Result) - Length(ExtractFileExt(FileName)));
end;
{ TMainForm }
constructor TMainForm.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
fPEImage:= TPEImage.Create;
end;
destructor TMainForm.Destroy;
begin
fPEImage.Free;
inherited Destroy;
end;
procedure TMainForm.LoadDLL(const aDLLFileName: String);
begin
FuncsVST.Clear;
OrgDllFileNameEdit.Text := '';
PointDllNameEdit.Text := '';
if not fPEImage.LoadFromFile(aDLLFileName, [PF_EXPORT]) then
begin
MessageDlg('Failed to load dll', mtError, [mbOK], 0);
Exit;
end;
//ShowMessage(IntToStr(fPEImage.ExportSyms.Count));
OrgDllFileNameEdit.Text := aDLLFileName;
PointDllNameEdit.Text := ExtractJustName(aDLLFileName) + '_.dll';
FuncsVST.ChildCount[nil] := fPEImage.ExportSyms.Count;
end;
procedure TMainForm.OrgDllFileNameBtnClick(Sender: TObject);
begin
if not OpenDialog1.Execute then Exit;
LoadDLL(OpenDialog1.FileName);
end;
procedure TMainForm.FuncsVSTGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: String);
begin
if Node^.Index >= Cardinal(fPEImage.ExportSyms.Count) then Exit;
case Column of
0: CellText := IntToStr(Node^.Index + 1);
1: CellText := IntToHex(fPEImage.ExportSyms.Items[Node^.Index].RVA, 8);
2: CellText := IntToStr(fPEImage.ExportSyms.Items[Node^.Index].Ordinal);
3: CellText := fPEImage.ExportSyms.Items[Node^.Index].Name;
end;
end;
procedure TMainForm.Label3Click(Sender: TObject);
//var
//URL: String;
begin
//URL:= 'http://oranke.tistory.com';
//ShellExecute(0, 'open', PChar(URL), nil, nil, SW_SHOWNORMAL);
OpenURL('http://oranke.tistory.com');
end;
procedure TMainForm.Label3MouseEnter(Sender: TObject);
begin
TLabel(Sender).Font.Style := TLabel(Sender).Font.Style + [fsUnderline];
TLabel(Sender).Font.Color := clBlue;
end;
procedure TMainForm.Label3MouseLeave(Sender: TObject);
begin
TLabel(Sender).Font.Style := TLabel(Sender).Font.Style - [fsUnderline];
TLabel(Sender).Font.Color := clDefault;
end;
procedure TMainForm.CodeGenButtonClick(Sender: TObject);
var
LibName: String;
i: Integer;
MainCodeList,
FuncCodeList,
ProxyCodeList,
ExportCodeList: TStringList;
LineEndStr: String;
begin
if not FileExists(OrgDllFileNameEdit.Text) then
begin
MessageDlg('Check original dll file first', mtError, [mbOK], 0);
Exit;
end;
if Length(PointDllNameEdit.Text) = 0 then
begin
MessageDlg('Point dll name is Empty', mtError, [mbOK], 0);
Exit;
end;
if fPEImage.ExportSyms.Count = 0 then
begin
MessageDlg('There''re no functions to generate', mtError, [mbOK], 0);
Exit;
end;
LibName:= ExtractJustName(OrgDllFileNameEdit.Text);
SaveDialog1.FileName := LibName + '.dpr';
if not SaveDialog1.Execute then Exit;
LibName:= ExtractJustName(SaveDialog1.FileName);
MainCodeList := TStringList.Create;
FuncCodeList := TStringList.Create;
ProxyCodeList:= TStringList.Create;
ExportCodeList:= TStringList.Create;
try
LineEndStr:= ',';
for i := 0 to fPEImage.ExportSyms.Count-1 do
with fPEImage.ExportSyms.Items[i] do
begin
FuncCodeList.Add(
Format(
' OrgFuncs.Arr[%d] := GetProcAddress(hl, ''%s'');',
[i, Name]
)
);
ProxyCodeList.Add(
Format(
'// %s'#13#10 +
'procedure __E__%d__();'#13#10 +
'asm'#13#10 +
' jmp [OrgFuncs.Base + SIZE_OF_FUNC * %d]'#13#10 +
'end;'#13#10#13#10
,
[Name, i, i]
)
);
if i = fPEImage.ExportSyms.Count-1 then LineEndStr := ';';
ExportCodeList.Add(
Format(
' __E__%d__ index %u name ''%s''%s',
[i, Ordinal, Name, LineEndStr]
)
);
end;
MainCodeList.Text :=
Format(
CodeMemo.Text,
[
LibName,
fPEImage.ExportSyms.Count-1,
PointDllNameEdit.Text,
FuncCodeList.Text,
ProxyCodeList.Text,
ExportCodeList.Text
]
);
//MainCodeList.WriteBOM := false;
MainCodeList.SaveToFile(SaveDialog1.FileName);//, TEncoding.UTF8);
MessageDlg(
Format(
'Code generated!'+#13+#10+''+#13+#10+
'1. Rename "%s" to "%s"'+#13+#10+
'2. Build "%s"'+#13+#10+
'3. and Rock''n ROLL!',
[
ExtractFileName(OrgDllFileNameEdit.Text),
PointDllNameEdit.Text,
ExtractFileName(SaveDialog1.FileName)
]),
mtInformation, [mbOK], 0
);
finally
MainCodeList.Free;
FuncCodeList.Free;
ProxyCodeList.Free;
ExportCodeList.Free;
end;
end;
procedure TMainForm.FormDropFiles(Sender: TObject;
const FileNames: array of String);
begin
if Length(FileNames) = 0 then Exit;
//ShowMessage(UpperCase(ExtractFileExt(FileNames[0])));
if UpperCase(ExtractFileExt(FileNames[0])) <> '.DLL' then Exit;
LoadDLL(FileNames[0]);
end;
end.
|
// DES fakturuje najednou všechny smlouvy zákazníka, internet, VoIP i IPTV s datem vystavení i plnění poslední den v měsíci.
// Zákazníci nebo smlouvy k fakturaci jsou v asgMain, faktury se vytvoří v cyklu přes řádky.
// 23.1.17 Výkazy pro ČTÚ vyžadují dělení podle typu uživatele, technologie a rychlosti - do Abry byly přidány 3 obchodní případy
// - VO (velkoobchod - DRC) , F a P (fyzická a právnická osoba) a 24 zakázek (W - WiFi, B - FFTB, A - FTTH AON, a P - FTTH PON,
// každá s šesti různými rychlostmi). Každému řádku faktury bude přiřazen jeden obchodní případ a jedna zakázka.
unit FIfaktura;
interface
uses
Windows, Messages, Dialogs, Classes, Forms, Controls, SysUtils, DateUtils, StrUtils, Variants, ComObj, Math,
Superobject, AArray,
FImain;
type
TdmFaktura = class(TDataModule)
private
isDRC : boolean;
procedure FakturaAbra(Radek: integer);
public
procedure VytvorFaktury;
end;
var
dmFaktura: TdmFaktura;
implementation
{$R *.dfm}
uses DesUtils, AbraEntities, DesInvoices;
// ------------------------------------------------------------------------------------------------
procedure TdmFaktura.VytvorFaktury;
var
Radek: integer;
begin
with fmMain, fmMain.asgMain do try
fmMain.Zprava(Format('Počet faktur k vygenerování: %d', [Trunc(ColumnSum(0, 1, RowCount-1))]));
Screen.Cursor := crHourGlass;
apbProgress.Position := 0;
apbProgress.Visible := True;
for Radek := 1 to RowCount-1 do begin
Row := Radek;
apbProgress.Position := Round(100 * Radek / RowCount-1);
Application.ProcessMessages;
if Prerusit then begin
Prerusit := False;
btVytvorit.Enabled := True;
Break;
end;
if Ints[0, Radek] = 1 then FakturaAbra(Radek);
end;
finally
apbProgress.Position := 0;
apbProgress.Visible := False;
Screen.Cursor := crDefault;
fmMain.Zprava('Generování faktur ukončeno');
end; // with fmMain
end;
// ------------------------------------------------------------------------------------------------
procedure TdmFaktura.FakturaAbra(Radek: integer);
// pro měsíc a rok zadaný v aseMesic a aseRok vytvoří fakturu za připojení k internetu a za VoIP
// 27.1.17 celé přehledněji
var
Firm_Id,
FirmOffice_Id,
BusOrder_Id,
BusOrderCode,
// Speed,
BusTransaction_Id,
BusTransactionCode,
OrgIdentNumber,
ID: string[10];
FCena,
CenaTarifu,
Redukce,
PausalVoIP,
HovorneVoIP,
DatumSpusteni,
DatumUkonceni: double;
FakturaVoIP,
SmlouvaVoIP,
ProvolatelnyPausal,
PosledniFakturace,
PrvniFakturace: boolean;
Dotaz,
CisloFaktury: integer;
FirmName,
Description,
CustomerVarSymbol,
SQLStr: string;
boRowAA: TAArray;
abraResponseSO : ISuperObject;
abraWebApiResponse : TDesResult;
NewInvoice : TNewDesInvoiceAA;
cas01, cas02, cas03: double;
begin
cas01 := Now;
with fmMain, DesU.qrZakos, asgMain do begin
CustomerVarSymbol := Cells[1, Radek];
// není víc zákazníků pro jeden VS ? 31.1.2017
//HWTODO mělo by se kontrolovat v Denní kontrole
Close;
SQL.Text := 'SELECT COUNT(*) FROM customers'
+ ' WHERE variable_symbol = ' + Ap + CustomerVarSymbol + Ap;
Open;
if Fields[0].AsInteger > 1 then begin
fmMain.Zprava(Format('Variabilní symbol %s má více zákazníků.', [CustomerVarSymbol]));
Close;
Exit;
end;
// je přenesená daňová povinnost ? 19.10.2016 - bude pro celou fakturu, ne pro jednotlivé smlouvy
Close;
SQL.Text := 'SELECT COUNT(*) FROM contracts'
+ ' WHERE drc = 1'
+ ' AND customer_id = (SELECT id FROM customers'
+ ' WHERE variable_symbol = ' + Ap + CustomerVarSymbol + ApZ;
Open;
isDRC := Fields[0].AsInteger > 0;
// vyhledání údajů o smlouvách
Close;
SQL.Text := 'CALL get_monthly_invoicing_by_vs('
+ Ap + FormatDateTime('yyyy-mm-dd', StartOfTheMonth(deDatumPlneni.Date)) + ApC
+ Ap + FormatDateTime('yyyy-mm-dd', deDatumPlneni.Date) + ApC
+ Ap + CustomerVarSymbol + ApZ;
// přejmenováno takto: AbraKod (cu_abra_code), Typ (co_type), Smlouva (co_number), AktivniOd (co_activated_at), AktivniDo (co_canceled_at),
// FakturovatOd (co_invoice_from), Tarif (tariff_name), Posilani (cu_invoice_sending_method_name),
// Perioda (bb_period), Text (bi_description), Cena (bi_price), DPH (bi_vat_name), Tarifni (bi_is_tariff), CTU (co_ctu_category)'
Open;
// při lecjaké chybě v databázi (např. Tariff_Id je NULL) konec
if RecordCount = 0 then begin
fmMain.Zprava(Format('Pro variabilní symbol %s není co fakturovat.', [CustomerVarSymbol]));
Close;
Exit;
end;
if FieldByName('cu_abra_code').AsString = '' then begin
fmMain.Zprava(Format('Smlouva %s: zákazník nemá kód Abry.', [FieldByName('co_number').AsString]));
Close;
Exit;
end;
{ 1.9.2022 zakomentováno, nepotřebné
if (FieldByName('co_ctu_category').AsString = '') and (FieldByName('co_type').AsString = 'InternetContract') then begin
dmCommon.Zprava(Format('Smlouva %s: zákazník nemá kód pro ČTÚ.', [FieldByName('co_number').AsString]));
Close;
Exit;
end;
}
with DesU.qrAbra do begin
// kontrola kódu firmy, při chybě konec, jinak načteme
Close;
SQL.Text := 'SELECT F.ID as Firm_ID, F.Name as FirmName, F.OrgIdentNumber'
+ ' FROM Firms F'
+ ' WHERE Code = ' + Ap + DesU.qrZakos.FieldByName('cu_abra_code').AsString + Ap
+ ' AND F.Firm_ID IS NULL' // bez následovníků
+ ' AND F.Hidden = ''N'''
+ ' ORDER BY F.ID DESC';
Open;
if RecordCount = 0 then begin
fmMain.Zprava(Format('Smlouva %s: Zákazník s kódem %s není v adresáři Abry.',
[DesU.qrZakos.FieldByName('co_number').AsString, DesU.qrZakos.FieldByName('cu_abra_code').AsString]));
Exit;
end
else if RecordCount > 1 then begin
fmMain.Zprava(Format('Smlouva %s: V Abře je více zákazníků s kódem %s.',
[DesU.qrZakos.FieldByName('co_number').AsString, DesU.qrZakos.FieldByName('cu_abra_code').AsString]));
Exit;
end
else begin
Firm_ID := FieldByName('Firm_ID').AsString;
FirmName := FieldByName('FirmName').AsString;
OrgIdentNumber := Trim(FieldByName('OrgIdentNumber').AsString);
end;
// 24.1.2017 obchodní případy pro ČTÚ - platí pro celou faktury
if isDRC then BusTransactionCode := 'VO' // velkoobchod (s DRC)
else if OrgIdentNumber = '' then BusTransactionCode := 'F' // fyzická osoba, nemá IČ
else BusTransactionCode := 'P'; // právnická osoba
BusTransaction_Id := AbraEnt.getBusTransaction('Code=' + BusTransactionCode).ID;
// kontrola poslední faktury
Close;
SQLStr := 'SELECT OrdNumber, DocDate$DATE, VATDate$DATE, Amount FROM IssuedInvoices'
+ ' WHERE VarSymbol = ' + Ap + CustomerVarSymbol + Ap
+ ' AND VATDate$DATE >= ' + FloatToStr(Trunc(StartOfAMonth(aseRok.Value, aseMesic.Value)))
+ ' AND VATDate$DATE <= ' + FloatToStr(Trunc(EndOfAMonth(aseRok.Value, aseMesic.Value)));
SQLStr := SQLStr + ' AND DocQueue_ID = ' + Ap + AbraEnt.getDocQueue('Code=FO1').ID + Ap;
SQLStr := SQLStr + ' ORDER BY OrdNumber DESC';
SQL.Text := SQLStr;
Open;
if RecordCount > 0 then begin
fmMain.Zprava(Format('%s (%s): %d. faktura se stejným datem.',
[FirmName, CustomerVarSymbol, RecordCount + 1]));
Dotaz := Application.MessageBox(PChar(Format('Pro zákazníka "%s" existuje faktura %s-%s s datem %s na částku %s Kč. Má se vytvořit další?',
[FirmName, 'FO1', FieldByName('OrdNumber').AsString, DateToStr(FieldByName('DocDate$DATE').AsFloat), FieldByName('Amount').AsString])),
'Pozor', MB_ICONQUESTION + MB_YESNOCANCEL + MB_DEFBUTTON1);
if Dotaz = IDNO then begin
fmMain.Zprava('Ruční zásah - faktura nevytvořena.');
Exit;
end else if Dotaz = IDCANCEL then begin
fmMain.Zprava('Ruční zásah - program ukončen.');
Prerusit := True;
Exit;
end else fmMain.Zprava('Ruční zásah - faktura se vytvoří.');
end;
end; // with qrAbra
Description := Format('připojení %d/%d, ', [aseMesic.Value, aseRok.Value-2000]);
// vytvoří se objekt TNewDesInvoiceAA a pak zbytek hlavičky faktury
NewInvoice := TNewDesInvoiceAA.create(Floor(deDatumDokladu.Date), CustomerVarSymbol);
NewInvoice.AA['VATDate$DATE'] := Floor(deDatumPlneni.Date);
NewInvoice.AA['DueTerm'] := aedSplatnost.Text;
NewInvoice.AA['DocQueue_ID'] := AbraEnt.getDocQueue('Code=FO1').ID; //VarToStr(globalAA['abraIiDocQueue_Id'])
NewInvoice.AA['Firm_ID'] := Firm_Id;
// boAA['FirmOffice_ID'] := FirmOffice_Id; // ABRA si vytvoří sama
// boAA['CreatedBy_ID'] := MyUser_Id; // vytvoří se podle uživatele, který se hlásí k ABRA WebApi
if isDRC then begin
NewInvoice.AA['IsReverseChargeDeclared'] := True;
NewInvoice.AA['VATFromAbovePrecision'] := 0; // pro jistotu, default je stejně 0
NewInvoice.AA['TotalRounding'] := 0;
end;
// 1. řádek
boRowAA := NewInvoice.createNew0Row(
Format('Fakturujeme Vám za období od 1.%d.%d do %d.%d.%d',
[aseMesic.Value, aseRok.Value, DayOfTheMonth(EndOfAMonth(aseRok.Value, aseMesic.Value)), aseMesic.Value, aseRok.Value])
);
// ============ smlouvy zákazníka - další řádky faktury se vytvoří z qrSmlouvy
while not EOF do begin // DesU.qrZakos
CenaTarifu := 0;
PausalVoIP := 0;
HovorneVoIP := 0;
// je-li datum aktivace menší než datum fakturace, vybere se prvni platba hotově a fakturuje se pak celý měsíc, jinak
// se platí jen část měsíce od data spuštění
DatumSpusteni := FieldByName('co_activated_at').AsDateTime;
DatumUkonceni := FieldByName('co_canceled_at').AsDateTime;
Redukce := 1;
PrvniFakturace := False;
if DatumSpusteni >= FieldByName('co_invoice_from').AsDateTime then
with DesU.qrAbraOC do begin
// už je nějaká faktura ?
SQL.Text := 'SELECT COUNT(*) FROM IssuedInvoices'
+ ' WHERE DocQueue_ID = ' + Ap + AbraEnt.getDocQueue('Code=FO1').ID + Ap
+ ' AND VarSymbol = ' + Ap + CustomerVarSymbol + Ap;
Open;
// zákazníkovi se ještě vůbec nefakturovalo
PrvniFakturace := Fields[0].AsInteger = 0;
Close;
end;
// ještě podle data aktivace (po pauze se fakturuje znovu)
if not PrvniFakturace then
PrvniFakturace := (MonthOf(DatumSpusteni) = MonthOf(deDatumDokladu.Date))
and (YearOf(DatumSpusteni) = YearOf(deDatumDokladu.Date));
// redukce ceny připojení
if PrvniFakturace then
Redukce := ((YearOf(deDatumDokladu.Date) - YearOf(DatumSpusteni)) * 12 // rozdíl let * 12
+ MonthOf(deDatumDokladu.Date) - MonthOf(DatumSpusteni) // + rozdíl měsíců + poměrná část 1. měsíce
+ (DaysInMonth(DatumSpusteni) - DayOf(DatumSpusteni) + 1) / DaysInMonth(DatumSpusteni));
// poslední fakturace
PosledniFakturace := (MonthOf(DatumUkonceni) = MonthOf(deDatumDokladu.Date))
and (YearOf(DatumUkonceni) = YearOf(deDatumDokladu.Date));
if PosledniFakturace then
Redukce := DayOf(DatumUkonceni) / DaysInMonth(DatumUkonceni); // poměrná část měsíce
// datum spuštění i ukončení je ve stejném měsíci
if PrvniFakturace and PosledniFakturace then
Redukce := (DayOf(DatumUkonceni) - DayOf(DatumSpusteni) + 1) / DaysInMonth(DatumUkonceni); // poměrná část měsíce
// pro VoIP
//SmlouvaVoIP := Copy(DesU.qrZakos.FieldByName('tariff_name').AsString, 1, 2) = 'EP'; // potřeba vynechat kreditni VoIP (tariff_id = 2)
SmlouvaVoIP := (DesU.qrZakos.FieldByName('co_tariff_id').AsInteger = 1) OR (DesU.qrZakos.FieldByName('co_tariff_id').AsInteger = 3);
HovorneVoIP := 0;
if SmlouvaVoIP then begin
if not ContainsText(Description, 'VoIP,') then // zabránění vícenásobnému vložení VoIP do Description
Description := Description + 'VoIP, ';
{
if DesU.dbVoIP.Connected then with DesU.qrVoIP do begin
SQLStr := 'SELECT SUM(Amount) FROM VoIP.Invoices_flat'
+ ' WHERE Num = ' + DesU.qrZakos.FieldByName('co_number').AsString
+ ' AND Year = ' + aseRok.Text
+ ' AND Month = ' + aseMesic.Text;
SQL.Text := SQLStr;
Open;
HovorneVoIP := DesU.VAT_MULTIPLIER * Fields[0].AsFloat;
Close;
end else begin
HovorneVoIP := 10;
fmMain.Zprava('Není připojena DB VoIP, hovorné nastaveno na 10 Kč');
end;
}
HovorneVoIP := 10;
fmMain.Zprava('Jen test! Není připojena DB VoIP! Hovorné nastaveno na 10 Kč');
end;
{ CTU, neni uz potreba
// 24.1.2017 zakázky pro ČTÚ - mohou být různé podle smlouvy
with qrAbra do begin
Close;
BusOrderCode := DesU.qrZakos.FieldByName('co_ctu_category').AsString;
// kódy z tabulky contracts se musí předělat
Speed := Copy(BusOrderCode, Pos('_', BusOrderCode), 2);
if Pos('WIFI', BusOrderCode) > 0 then BusOrderCode := 'W' + Speed
else if Pos('FTTH', BusOrderCode) > 0 then BusOrderCode := 'A' + Speed
else if Pos('FTTB', BusOrderCode) > 0 then BusOrderCode := 'B' + Speed
else if Pos('PON', BusOrderCode) > 0 then BusOrderCode := 'P' + Speed
else BusOrderCode := '1';
SQLStr := 'SELECT Id FROM BusOrders'
+ ' WHERE Code = ' + Ap + BusOrderCode + Ap;
SQL.Text := SQLStr;
Open;
BusOrder_Id := Fields[0].AsString;
Close;
end;
}
// cena za tarif
if (FieldByName('bi_is_tariff').AsInteger = 1) then begin
CenaTarifu := DesU.qrZakos.FieldByName('bi_price').AsFloat;
if not SmlouvaVoIP then begin
// připojení k Internetu
boRowAA := NewInvoice.createNew1Row( Format('podle smlouvy %s službu %s',
[FieldByName('co_number').AsString, FieldByName('bi_description').AsString]));
// boRowAA['BusOrder_ID'] := BusOrder_Id; // CTU, neni uz potreba
if DesU.qrZakos.FieldByName('co_type').AsString = 'TvContract' then
boRowAA['BusOrder_ID'] := '1700000101';
boRowAA['BusTransaction_ID'] := BusTransaction_Id;
boRowAA['TotalPrice'] := Format('%f', [CenaTarifu * Redukce]);
if isDRC then begin
boRowAA['VATMode'] := 1;
boRowAA['VATIndex_ID'] := AbraEnt.getVatIndex('Code=VýstR' + DesU.VAT_RATE).ID;
boRowAA['DRCArticle_ID'] := AbraEnt.getDrcArticle('Code=21').ID; // typ plnění 21, nemá spojitost s DPH
boRowAA['TotalPrice'] := Format('%f', [FieldByName('bi_price').AsFloat * Redukce / DesU.VAT_MULTIPLIER ]);
end;
end else begin // smlouva je VoIP
if HovorneVoIP > 0 then begin
// hovorné
boRowAA := NewInvoice.createNew1Row('hovorné VoIP');
boRowAA['BusOrder_ID'] := '1500000101';
boRowAA['BusTransaction_ID'] := BusTransaction_Id;
boRowAA['TotalPrice'] := Format('%f', [HovorneVoIP]);
HovorneVoIP := 0;
end;
/// paušál
boRowAA := NewInvoice.createNew1Row(Format('podle smlouvy %s měsíční platbu VoIP %s',
[FieldByName('co_number').AsString, FieldByName('bi_description').AsString]));
boRowAA['BusOrder_ID'] := '2000000101';
boRowAA['BusTransaction_ID'] := BusTransaction_Id;
boRowAA['TotalPrice'] := Format('%f', [CenaTarifu * Redukce]);
end; // tarif VoIP
// něco jiného než tarif
end else begin
boRowAA := NewInvoice.createNew1Row(FieldByName('bi_description').AsString);
// boRowAA['BusOrder_ID'] := BusOrder_Id; // CTU, neni uz potreba
if DesU.qrZakos.FieldByName('co_type').AsString = 'TvContract' then
boRowAA['BusOrder_ID'] := '1700000101';
boRowAA['BusTransaction_ID'] := BusTransaction_Id;
if Pos('auce', FieldByName('bi_description').AsString) > 0 then
boRowAA['IncomeType_ID'] := '1000000101'; // kauce
boRowAA['TotalPrice'] := Format('%f', [FieldByName('bi_price').AsFloat * Redukce]);
if FieldByName('bi_vat_name').AsString = '21%' then begin // 4.1.2013, DPH je 21%
if isDRC then begin // 19.10.2016
boRowAA['VATMode'] := 1;
boRowAA['VATIndex_ID'] := AbraEnt.getVatIndex('Code=VýstR' + DesU.VAT_RATE).ID;
boRowAA['DRCArticle_ID'] := AbraEnt.getDrcArticle('Code=21').ID; // typ plnění 21, nemá spojitost s DPH
boRowAA['TotalPrice'] := Format('%f', [FieldByName('bi_price').AsFloat * Redukce / DesU.VAT_MULTIPLIER]);
end;
end else begin // DPH je 0%
boRowAA['VATRate_ID'] := AbraEnt.getVatIndex('Code=Mevd').VATRate_ID; // 00000X0000
boRowAA['VATIndex_ID'] := AbraEnt.getVatIndex('Code=Mevd').ID; // 7000000000
if Pos('dar ', FieldByName('bi_description').AsString) > 0 then
boRowAA['IncomeType_ID'] := '3000000000'; // OS - Ostatní
end;
end; // if tarif else
Next; // DesU.qrZakos
end; // while not DesU.qrZakos.EOF
// případně řádek s poštovným
if (FieldByName('cu_invoice_sending_method_name').AsString = 'Poštou')
or (FieldByName('cu_invoice_sending_method_name').AsString = 'Se složenkou') then begin // pošta, složenka
boRowAA := NewInvoice.createNew1Row('manipulační poplatek');
boRowAA['BusOrder_ID'] := '1000000101'; // internet Mníšek (Code=1)
boRowAA['BusTransaction_ID'] := BusTransaction_Id;
boRowAA['TotalPrice'] := '62';
end;
NewInvoice.AA['Description'] := Description + CustomerVarSymbol;
if isDebugMode then begin
cas02 := Now;
fmMain.Zprava(debugRozdilCasu(cas01, cas02, ' - čas přípravy dat fa'));
end;
// vytvoření faktury
try
abraWebApiResponse := DesU.abraBoCreateWebApi(NewInvoice.AA, 'issuedinvoice');
if abraWebApiResponse.isOk then begin
abraResponseSO := SO(abraWebApiResponse.Messg);
fmMain.Zprava(Format('%s (%s): Vytvořena faktura %s.', [FirmName, CustomerVarSymbol, abraResponseSO.S['displayname']]));
Ints[0, Radek] := 0;
Cells[2, Radek] := abraResponseSO.S['ordnumber']; // faktura
Cells[3, Radek] := abraResponseSO.S['amount']; // částka
Cells[4, Radek] := FirmName;
end else begin
fmMain.Zprava(Format('%s (%s): Chyba %s: %s', [FirmName, CustomerVarSymbol, abraWebApiResponse.Code, abraWebApiResponse.Messg]));
if Dialogs.MessageDlg( '(' + abraWebApiResponse.Code + ') '
+ abraWebApiResponse.Messg + sLineBreak + 'Pokračovat?',
mtConfirmation, [mbYes, mbNo], 0 ) = mrNo then Prerusit := True;
end;
except on E: exception do
begin
Application.MessageBox(PChar('Problem ' + ^M + E.Message), 'Vytvoření fa');
end;
end;
Close; // DesU.qrZakos
if isDebugMode then begin
cas03 := Now;
fmMain.Zprava(debugRozdilCasu(cas02, cas03, ' - čas zapsání fa do ABRA'));
end;
end; // with
end;
end.
|
unit CamCaptureUnit;
interface
uses Windows,Graphics,AviCap32Unit;
type TCamera=class
protected
FWidth : integer;
FHeight : integer;
FCamIndex : integer;
Fh : THandle;
FName : string;
FVer : string;
public
Constructor Create;
Destructor Destroy; override;
function Start():boolean;
function CaptureBMP(bmp:TBitmap;X:integer;Y:integer):boolean;
property CamIndex:integer read FCamIndex write FCamIndex;
property Name:string read FName write FName;
property Ver:string read FVer write FVer;
end;
TCamList=class
protected
FList : array of TCamera;
function FGetCount:integer;
function FGetItem(index:integer):TCamera;
public
procedure Emumerate();
property count:integer read FGetCount;
property List[index:integer]:TCamera read FGetItem; default;
end;
implementation
Constructor TCamera.Create;
begin
inherited;
Fh:=0;
FWidth:=640;
FHeight:=480;
end;
Destructor TCamera.Destroy;
begin
if(Fh<>0)then CloseHandle(Fh);
inherited;
end;
function TCamera.Start():boolean;
begin
Fh:=capCreateCaptureWindowA('video',
WS_VISIBLE or WS_CHILD,
10000,
10000,
FWidth,
FHeight,
GetDesktopWindow,
0);
if(fh<>0)then
begin
SendMessage(Fh, WM_CAP_DRIVER_CONNECT, 0, 0);
result:=true;
end else
begin
result:=false;
end;
end;
function TCamera.CaptureBMP(bmp:TBitmap;x:integer;y:integer):boolean;
begin
SendMessage(Fh, WM_CAP_GRAB_FRAME,X,Y);
bmp.Width:=FWidth;
bmp.Height:=FHeight;
BitBlt(BMP.Canvas.Handle,0,0,FWidth,FHeight,GetDC(Fh),0,0,SRCCOPY);
result:=true;
end;
function TCamList.FGetCount:integer;
begin
result:=length(FList);
end;
function TCamList.FGetItem(index:integer):TCamera;
begin
result:=FList[index];
end;
procedure TCamList.Emumerate();
var i : integer;
name : array[0..255]of AnsiChar;
ver : array[0..255]of AnsiChar;
cam : TCamera;
begin
for i:=0 to 9 do
begin
if(capGetDriverDescriptionA(i,@name,SizeOf(name),@ver,SizeOf(ver)))then
begin
cam:=TCamera.Create;
cam.Name:=string(name);
cam.Ver:=string(ver);
cam.CamIndex:=i;
SetLength(FList,length(FList)+1);
FList[High(FList)]:=cam;
end;
end;
end;
end.
|
{$A+} { Align Data Switch }
{$B-} { Boolean Evaluation Switch }
{$D-} { Debug Information Switch }
{$E-} { Emulation Switch - this doesn't affect a unit only a program }
{$F-} { Force Far Calls Switch }
{$G+} { Generate 80286 Code Switch }
{$I-} { Input/Output-Checking Switch }
{$I Defines.INC} { This file is used to define some conditionals according }
{ with user preferences. }
{$L-} { Local Symbol Information Switch }
{$N+} { Numeric Coprocessor Switch }
{$Q-} { Overflow Checking Switch }
{$R-} { Range-Checking Switch }
{$S-} { Stack-Overflow Checking Switch }
{$V-} { Var-String Checking Switch }
{$Y+} { Symbol Reference Information Switch - just afect the Unit size, and }
{ it's very good when you run BP, because you can go directly to the }
{ line where the source begins! Study, to know more!!! }
Program Vesa_Demo_7; { Testing 2D/3D Demo -- Stars I (Rotation Stars) }
{ The Original Code was made by Bas Van Gaalen }
{ I just modified and optimized it to work in all Vesa modes. The final use }
{ of this code is just to demonstrate my VESA unit. }
{ Fernando J.A. Silva ( ^Magico^ ) 15/Oct/1997 }
Uses
Crt, Vesa;
Const
NofPoints = 255;
Speed = 3;
Xc : real = 0;
Yc : real = 0;
Zc : real = 150;
SinTab : Array [0..255] OF integer = (
0,2,5,7,10,12,15,17,20,22,24,27,29,31,34,36,38,41,43,45,47,49,52,54,
56,58,60,62,64,66,67,69,71,73,74,76,78,79,81,82,83,85,86,87,88,90,91,
92,93,93,94,95,96,97,97,98,98,99,99,99,100,100,100,100,100,100,100,
100,99,99,99,98,98,97,97,96,95,95,94,93,92,91,90,89,88,87,85,84,83,
81,80,78,77,75,73,72,70,68,66,65,63,61,59,57,55,53,51,48,46,44,42,40,
37,35,33,30,28,26,23,21,18,16,14,11,9,6,4,1,-1,-4,-6,-9,-11,-14,-16,
-18,-21,-23,-26,-28,-30,-33,-35,-37,-40,-42,-44,-46,-48,-51,-53,-55,
-57,-59,-61,-63,-65,-66,-68,-70,-72,-73,-75,-77,-78,-80,-81,-83,-84,
-85,-87,-88,-89,-90,-91,-92,-93,-94,-95,-95,-96,-97,-97,-98,-98,-99,
-99,-99,-100,-100,-100,-100,-100,-100,-100,-100,-99,-99,-99,-98,-98,
-97,-97,-96,-95,-94,-93,-93,-92,-91,-90,-88,-87,-86,-85,-83,-82,-81,
-79,-78,-76,-74,-73,-71,-69,-67,-66,-64,-62,-60,-58,-56,-54,-52,-49,
-47,-45,-43,-41,-38,-36,-34,-31,-29,-27,-24,-22,-20,-17,-15,-12,-10,
-7,-5,-2,0);
Type
PointRec = Record
X,Y,Z : integer;
End;
PointPos = Array [0..NofPoints] OF PointRec;
Var
Point : PointPos;
MaxX, MaxY : Word;
{----------------------------------------------------------------------------}
PROCEDURE Init;
Var
I : Word;
Begin
Randomize;
FOR I := 0 TO NofPoints DO
Begin
Point[I].X := random(250)-125;
Point[I].Y := random(250)-125;
Point[I].Z := random(250)-125;
End;
End;
{----------------------------------------------------------------------------}
PROCEDURE DoRotation;
Const
Xstep = 1;
Ystep = 1;
Zstep = -2;
Var
Xp,Yp : array[0..NofPoints] of word;
X,Y,Z,X1,Y1,Z1 : real;
PhiX,PhiY,PhiZ : byte;
I,Color : Longint;
CenterX, CenterY : Word;
FUNCTION Sinus(Idx : byte) : Real;
Begin
Sinus := SinTab[Idx]/100;
End;
FUNCTION Cosinus(Idx : byte) : Real;
Begin
Cosinus := SinTab[(Idx+192) mod 255]/100;
End;
Begin
PhiX := 0;
PhiY := 0;
PhiZ := 0;
CenterX := (MaxX DIV 2);
CenterY := (MaxY DIV 2);
Repeat
While (port[$3da] AND 8) <> 8 DO;
While (port[$3da] AND 8) = 8 DO;
FOR I := 0 TO NofPoints DO
Begin
IF (Xp[I]+CenterX < MaxX) AND (Yp[I]+CenterY < MaxY) Then
DrawPixel(Xp[I]+(MaxX DIV 2),Yp[I]+(MaxY DIV 2),0);
X1 := Cosinus(PhiY)*Point[I].X-Sinus(PhiY)*Point[I].Z;
Z1 := Sinus(PhiY)*Point[I].X+Cosinus(PhiY)*Point[I].Z;
X := Cosinus(PhiZ)*X1+Sinus(PhiZ)*Point[I].Y;
Y1 := Cosinus(PhiZ)*Point[I].Y-Sinus(PhiZ)*X1;
Z := Cosinus(PhiX)*Z1-Sinus(PhiX)*Y1;
Y := Sinus(PhiX)*Z1+Cosinus(PhiX)*Y1;
Xp[I] := round((Xc*Z-X*Zc)/(Z-Zc));
Yp[I] := round((Yc*Z-Y*Zc)/(Z-Zc));
IF (Xp[I]+CenterX < MaxX) AND (Yp[I]+CenterY < MaxY) Then
Begin
Color := 31+round(Z/7);
IF Color > 31 Then Color := 31
Else IF Color < 16 Then Color := 16;
DrawPixel(Xp[I]+(MaxX DIV 2),Yp[I]+(MaxY DIV 2),Color);
End;
Inc(Point[I].Z,Speed);
IF Point[I].Z > 125 Then Point[I].Z := -125;
End;
Inc(PhiX,Xstep);
Inc(PhiY,Ystep);
Inc(PhiZ,Zstep);
Until keypressed;
End;
{----------------------------------------------------------------------------}
Begin
SetMode($103);
MaxX := VesaMode.Width;
MaxY := VesaMode.Height;
Init;
DoRotation;
CloseVesaMode;
End.
|
unit uTestDiagram;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, GdiPlus, GdiPlusHelpers, uGlobals, uTheme, uTests;
const
MAX_GRADUATION = TASK_COUNT;
type
TLineGraduation = array[0..MAX_GRADUATION - 1] of Tline;
TaxisAngle = double;
TTopicResult = record
topic: TTopicInfo;
test: PTestInfo;
labelRect:TGPRectF;
labelPoint: TGPPointF;
curvePoint: TGPPointF;
MaxP1: TGPPointF;
ResultP1, ResultP2: TGPPointF;
pie: IGPGraphicsPath;
DisplayLabel: string;
end;
TTopicResultList = array of TTopicResult;
TfrmTestDiagram = class(TForm)
img: TImage;
private
Graphic: IGPGraphics;
Pen: IGPPen;
FontFamily: IGPFontFamily;
Font: IGPFont;
SolidBrush: IGPBrush;
ColorBrush: IGPBrush;
bmp: TBitmap;
AXIS_ANGLE: double;
center: TGPPointF;
// centerX, centerY: double;
CircleRect:TGPRectF;
axis: array of TLine;
axisAngle: array of TaxisAngle;
scale : array of TLineGraduation;
topicResultList: TTopicResultList;
israndom: boolean;
procedure createCircle(axisCount: integer);
procedure createScale();
procedure createResultList();
procedure createDisplayLabel(pts: double; i: integer);
procedure createCurvePoints(i: integer);
procedure Render();
public
{ Public declarations }
procedure createNewBmp(useRandom: boolean);
procedure showTestDiagram();
end;
implementation
uses uOGE, uData;
{$R *.dfm}
const
colors: array[0..3] of cardinal = (TGPColor.Red, TGPColor.Green, TGPColor.Aqua, TGPColor.Lime);
{ TfrmTestDiagram }
procedure TfrmTestDiagram.createCircle(axisCount: integer);
var i, rect_width: integer;
angle: double;
begin
if axisCount = 0 then abort;
setLength(axis, axisCount);
setLength(axisAngle, length(axis));
AXIS_ANGLE := 360 div length(axis);
rect_Width := trunc(bmp.height / 1.2);
CircleRect.X := (bmp.Width - RECT_WIDTH) / 2;
CircleRect.Y := ((bmp.Height - RECT_WIDTH) / 2);
CircleRect.Width := RECT_WIDTH;
CircleRect.Height := RECT_WIDTH;
// Центр круга
center.X := (CircleRect.Left + CircleRect.Right) / 2;
center.Y := (CircleRect.Top + CircleRect.Bottom) / 2;
axis[0].p1.x := center.X;
axis[0].p1.y := center.Y;
axis[0].p2.x := (CircleRect.Left + CircleRect.Right) / 2;
axis[0].p2.y := CircleRect.Top;
axis[0].len := lineLen(axis[0]);
axisAngle[0] := 0;
angle := AXIS_ANGLE;
for i := 1 to high(axis) do
begin
// if (angle mod 90) = 0 then incLen := 40 else incLen := 0;
axis[i] := rotateLine(angle, axis[0], center);
axisAngle[i] := angle;
angle := angle + AXIS_ANGLE;
end;
end;
procedure TfrmTestDiagram.createCurvePoints(i: integer);
var angle: integer;
points: array[0..2] of TGPPointF;
begin
topicResultList[i].pie := TGPGraphicsPath.Create;
angle := trunc(AXIS_ANGLE / 2);
topicResultList[i].curvePoint := rotatePoint(angle, center, topicResultList[i].ResultP1);
points[0] := topicResultList[i].ResultP1;
points[1] := topicResultList[i].curvePoint;
points[2] := topicResultList[i].ResultP2;
topicResultList[i].pie.AddCurve(points);
points[0] := center;
points[1] := topicResultList[i].ResultP1;
points[2] := topicResultList[i].ResultP2;
topicResultList[i].pie.AddPolygon(points);
end;
procedure TfrmTestDiagram.createDisplayLabel(pts: double; i: integer);
var s: string;
txtH, txtW: double;
angle: integer;
begin
with topicResultList[i] do
s := format('%s - %f', [topic.displayLabel, pts]);
MeasureDisplayStringWidthAndHeight(Graphic, Font, s, txtW, txtH);
topicResultList[i].DisplayLabel := s;
txtH := txtH * 2;
txtW := txtW - 10;
angle := trunc(axisAngle[i]);
with topicResultList[i] do
begin
if (angle >= 0) and (angle <= 79) then // in [0..79]
begin
labelRect.X := labelPoint.X;
labelRect.Y := labelPoint.Y - txtH;
end
else if (angle >= 80) and (angle <= 179) then // in [80..179]
begin
labelRect.X := labelPoint.X;
labelRect.Y := labelPoint.Y;
end
else if (angle >= 180) and (angle < 270) then
begin
labelRect.X := labelPoint.X - txtW;
labelRect.Y := labelPoint.Y;
end
else if (angle >= 270) and (angle < 360) then
begin
labelRect.X := labelPoint.X - txtW;
labelRect.Y := labelPoint.Y - txtH;
end;
labelRect.Width := txtW;
labelRect.Height := txtH;
if (labelRect.X < 0) then
begin
labelRect.Width := labelRect.Width + labelRect.X;
labelRect.X := 20;
end;
end;
end;
procedure TfrmTestDiagram.createNewBmp(useRandom: boolean);
begin
if Assigned(bmp) then freeAndNil(bmp);
isRandom := useRandom;
bmp := TBitMap.Create;
bmp.Width := self.Width;
bmp.Height := self.Height;
Graphic := TGPGraphics.Create(bmp.Canvas.Handle);
Graphic.SmoothingMode := SmoothingModeAntiAlias;
Graphic.InterpolationMode := InterpolationModeHighQualityBicubic;
Graphic.PixelOffsetMode := PixelOffsetModeHighQuality;
// Graphic.CompositingQuality := CompositingQualityAssumeLinear;
Pen := TGPPen.Create(TGPColor.Black, 1);
FontFamily := TGPFontFamily.Create('Tahoma');
Font := TGPFont.Create(FontFamily, 10, FontStyleRegular, UnitPoint);
Graphic.TextRenderingHint := TextRenderingHintAntiAlias;
SolidBrush := TGPSolidBrush.Create(TGPColor.Black);
setLength(topicResultList, length(frmOGE.Topics.TopicList));
createCircle(length(topicResultList));
createScale();
createResultList();
Render();
end;
procedure TfrmTestDiagram.createResultList;
var i: integer;
k, l, pts, angle: double;
begin
for i := 0 to length(topicResultList) - 1 do
begin
with topicResultList[i] do
begin
topic := frmOGE.Topics.TopicList[i];
test := getTestByTopic(topic.id, frmOGE.Tests.Tests);
if isRandom then pts := random(11)
else if assigned(test) then pts := test.points
else pts := 0;
// define result points
l := (axis[i].len / MAX_GRADUATION) * pts;
k := l / axis[i].len;
MaxP1 := axis[i].p2;
ResultP1.X := center.X + (MaxP1.X - center.X) * k;
ResultP1.Y := center.Y + (MaxP1.Y - center.Y) * k;
ResultP2 := rotatePoint(AXIS_ANGLE, center, ResultP1);
// define labelPoint
angle := axisAngle[i] + (AXIS_ANGLE / 2);
labelPoint := rotatePoint(angle, center, topicResultList[0].MaxP1);
// create labels
createDisplayLabel(pts, i);
// define curve points
createCurvePoints(i);
end;
end;
end;
procedure TfrmTestDiagram.createScale;
var scalewidth, scaleHeight, len: double;
i, j: integer;
angle: double;
begin
scaleWidth := 10;
scaleHeight := axis[0].len / TASK_COUNT;
setLength(scale, length(axis));
scale[0][0].p1.X := center.X + (scaleWidth / 2);
scale[0][0].p1.Y := center.Y - scaleHeight;
scale[0][0].p2.X := center.X - (scaleWidth / 2);
scale[0][0].p2.Y := center.Y - scaleHeight;
scale[0][0].len := lineLen(scale[0][0]);
len := scale[0][0].len;
for i := 1 to MAX_GRADUATION - 1 do
begin
scale[0][i].p1.X := center.X + (scaleWidth / 2);
scale[0][i].p1.Y := center.Y - scaleHeight * i;
scale[0][i].p2.X := center.X - (scaleWidth / 2);
scale[0][i].p2.Y := center.Y - scaleHeight * i;
scale[0][i].len := len;
end;
for i := 1 to MAX_GRADUATION - 1 do
begin
angle := AXIS_ANGLE;
for j := 1 to length(scale) - 1 do
begin
scale[j][i] := rotateLine(angle, scale[0][i], center);
angle := angle + AXIS_ANGLE;
end;
end;
end;
procedure TfrmTestDiagram.Render;
var i, j, c: integer;
begin
graphic.DrawEllipse(Pen, CircleRect);
for i := 0 to length(axis) - 1 do
graphic.DrawLine(pen, axis[i].p1, axis[i].p2);
c := 0;
for i := 0 to length(topicResultList) - 1 do
begin
graphic.DrawString(topicResultList[i].DisplayLabel,
font, topicResultList[i].labelRect, nil, SolidBrush);
if assigned(topicResultList[i].pie) then
begin
ColorBrush := TGPSolidBrush.Create(colors[c]);
graphic.FillPath(ColorBrush, topicResultList[i].pie);
inc(c);
if c > 3 then c := 0;
end;
end;
for i := 0 to length(scale) - 1 do
for j := 0 to MAX_GRADUATION - 1 do
graphic.DrawLine(pen, scale[i][j].p1, scale[i][j].p2);
img.Picture.Assign(bmp);
end;
procedure TfrmTestDiagram.showTestDiagram();
begin
show;
end;
end.
|
unit Connect;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, Spin, Menus,ShellApi, ExtCtrls,Math;
type
TConnectForm = class
private
{ Private declarations }
public
{ Public declarations }
passwordOk:boolean;
procedure Disconnect(Handle:HWND; var Text:string);
procedure SetupConnection(Handle:HWND; var Text:string);
function ShowStatus(Status:Integer; LastOpr:string):string;
function GetMode:Integer;
procedure Start;
function GetChannelConnected : boolean;
function Connection(Handle:HWND; var Text:string) : boolean;
end;
var
ConnectForm: TConnectForm;
type
MyPChar=Array[0..63] of Char;
TReserved=Array[0..83] of Byte;
CWORD = word;
CDWORD = Cardinal;
CSHORT = SmallInt;
CBOOL = LongBool;
CCHAR = MyPChar;
pPcdConn = ^Cardinal;
pPCDOPENDATA = ^PCDOPENDATA;
pREQSTATION = ^REQSTATION;
REQSTATION = record //@Field Complete station number information <t REQSTATION>
SbusStation: CWORD; //@Field S-Bus station number
FdlStation : CWORD; //@Field Profi-S-Bus station number
TcpPort : CWORD; //@Field Tcp port number
IpAddress : CDWORD; //@Field Ip address<nl>format "1.2.3.4" = 0x01020304
end;
PCDOPENDATA = record
Port : CSHORT; //Port number TAPI,RAS,COMx,SOCKET <t enumComPort>
Device : CSHORT; //COM port number or Socket Port.
bPguMode : CBOOL; //TRUE=using PGU mode (S-BUS/P800)
SbusMode : CDWORD; //S-BUS mode: <t enumSBusModes>
Protocol : CDWORD; //Type of protocol, <t enumProtocol>
BaudRate : CDWORD; //110..38400 <t enumBaudRate>
TsDelay : CDWORD; //S-BUS training sequence delay, mS
TnDelay : CDWORD; //S-BUS turnaround time, mS
Timeout : CDWORD; //S-BUS timeout in mS
BreakLen : CDWORD; //S-BUS break length in chars, PCD_BREAK mode
UartFifoLen : CDWORD; //Number of characters in UART Fifo buffer (to wait for RTS)
bDontClose : CBOOL; //Do not close the port.
bPortOpen : CBOOL; //The port is open.
bConnected : CBOOL; //The port is connected with the function PcdConnectChannel
// connection
dwType : CDWORD; //Channel type.
Channel : CCHAR; //string[64]; //Channel name 'PGU'.
Section : CCHAR; //string[64]; //Name of the section in INI file or Registry
ModeToTry : CDWORD; //Mode to connect, <t enumSBusModesToTry>
Cpu : CDWORD; //CPU number: 0..6
bAutoStn : CBOOL; //TRUE=send "read S-BUS station" telegram
Retry : CDWORD; //Retry count, default = 3
// for TAPI, RAS or Socket
DeviceName : CCHAR; //string[64]; //TAPI, RAS or Socket IP Address device name.
// TAPI connection
bUseModem : CBOOL; //Use dialing (TAPI modem).
bAutoAnswer : CBOOL; //Open the TAPI port in AutoAnswer mode.
PhoneNumber : CCHAR; //string[64]; //Phone number for TAPI or RAS dialing.
CountryCode : CDWORD; //Country code (Switzerland 41).
AreaCode : CDWORD; //Area code (Morat 26).
Location : CCHAR; //string[64]; //Location name.
bUseDialing : CBOOL; //Use dialing (translate phone number).
DialRetry : CDWORD; //Number of retry when dialing.
// Bues Connection
bBues : CBOOL; //Bues flag
// password dialog box parent window
hPWDlgParentWnd : HWND; //Parent window for password dialog box <t PcdSetParentWnd>.
//station
ReqStation : REQSTATION;
SrcSap : CSHORT; //@Field Source service access point for Profi-S-Bus communication
DstSap : CSHORT; //@Field Destination service access point for Profi-S-Bus communication
BDstSap : CSHORT; //@Field Broadcast Destination service access point for Profi-S-Bus communication
Reserved : TReserved; //Reserved for future extension
end;
type
lpDataType = Array [0..49] of Cardinal;
lpDataDB = Array [0..1005] of Cardinal;
var
mOpenData : PCDOPENDATA;
lpData : lpDataType;
lpDB : lpDataDB;
PcdConn : Cardinal;
respons : integer;
lpLength : lpDataType;
//C:\Program Files\SAIA-Burgess\PG5\
//init-exit
function PcdInitInterface():boolean;stdcall; external 'ScommDll.dll' name 'PcdInitInterface';
function PcdComUnloadDrv(unload:boolean):integer;stdcall; external 'ScommDll.dll' name 'PcdComUnloadDrv';
procedure PcdExitInterface;stdcall; external 'ScommDll.dll' name 'PcdExitInterface';
function PcdPoll(PcdConn :Cardinal):integer;stdcall; external 'ScommDll.dll' name 'PcdPoll';
//service
function PcdClear(PcdConn:Cardinal;Typ:Char):integer;stdcall; external 'ScommDll.dll' name 'PcdClear';
function PcdRun(PcdConn:Cardinal; Cpu:Cardinal):integer;stdcall; external 'ScommDll.dll' name 'PcdRun';
function PcdStop(PcdConn:Cardinal;Cpu:Cardinal):integer;stdcall; external 'ScommDll.dll' name 'PcdStop';
function PcdRestart(PcdConn:Cardinal; Cpu, WarmCold:Cardinal):integer;stdcall; external 'ScommDll.dll' name 'PcdRestart';
//setup
function PcdRdChanSetupFromIni( szIniName , szAppName:MyPChar;lpOpenData:pPCDOPENDATA):integer;stdcall; external 'ScommDll.dll' name 'PcdRdChanSetupFromIni';
function PcdWrChanSetupToIni ( szIniName , szAppName:MyPChar;const lpOpenData:pPCDOPENDATA):integer;stdcall; external 'ScommDll.dll' name 'PcdWrChanSetupToIni';
function PcdConnectionDialog(hParentWnd:HWND; lpOpenData:pPCDOPENDATA):integer;stdcall; external 'ScommUsr.dll' name 'PcdConnectionDialog';
function PcdChannelList(hParentWnd:HWND; lpOpenData:pPCDOPENDATA):integer;stdcall; external 'ScommUsr.dll' name 'PcdChannelList';
//connect-disconnect
function PcdConnectChannel(lpPcdConn:pPcdConn; lpOpenData:pPCDOPENDATA; dwFlags : Cardinal; hCallbackWnd:HWND):integer;stdcall; external 'ScommDll.dll' name 'PcdConnectChannel';
function PcdDisconnectChannel(PcdConn , dwFlags:Cardinal; hCallbackWnd:HWND):integer;stdcall; external 'ScommDll.dll' name 'PcdDisconnectChannel';
function PcdComOpen(lpPcdConn:pPcdConn; lpOpenData : pPCDOPENDATA; dwFlags:Cardinal; hCallbackWnd:HWND):integer;stdcall; external 'ScommDll.dll' name 'PcdComOpen';
function PcdComClose(PcdConn : Cardinal; dwFlags : Cardinal; hCallbackWnd:HWND):integer;stdcall; external 'ScommDll.dll' name 'PcdComClose';
function PcdGetPortName(lpOpenData:pPCDOPENDATA; lpszName :PChar; MaxNameSize: Cardinal):integer;stdcall; external 'ScommDll.dll' name 'PcdGetPortName';
function PcdGetBaudrateName(lpOpenData:pPCDOPENDATA; lpszName :PChar; MaxNameSize: Cardinal):integer;stdcall; external 'ScommDll.dll' name 'PcdGetBaudrateName';
function PcdGetOpenData(PcdConn : Cardinal; lpOpenData:pPCDOPENDATA):integer;stdcall; external 'ScommDll.dll' name 'PcdGetOpenData';
//read-write res
function PcdRdRTC(PcdConn:Cardinal; Typ:Char; Address, Count:Cardinal; lpData:lpDataType):integer;stdcall; external 'ScommDll.dll' name 'PcdRdRTC';
function PcdWrRTC(PcdConn:Cardinal; Typ:Char; Address, Count:Cardinal; lpData:lpDataType):integer;stdcall; external 'ScommDll.dll' name 'PcdWrRTC';
function PcdRdIOF(PcdConn:Cardinal; Typ:Char; Address, Count:Cardinal; lpData:PChar):integer;stdcall; external 'ScommDll.dll' name 'PcdRdIOF';
function PcdWrOF (PcdConn:Cardinal; Typ:Char; Address, Count:Cardinal; lpData:PChar):integer;stdcall; external 'ScommDll.dll' name 'PcdWrOF';
function PcdMessage(Status:integer):PChar;stdcall; external 'ScommDll.dll' name 'PcdMessage';
function PcdSetClockDialog(PcdConn:Cardinal; hParentWnd:HWND):integer;stdcall; external 'ScommUsr.dll' name 'PcdSetClockDialog';
function PcdRdEEPROM(PcdConn:Cardinal; Address, Count:Cardinal; lpData:lpDataType):integer;stdcall; external 'ScommDll.dll' name 'PcdRdEEPROM';
function PcdWrEEPROM(PcdConn:Cardinal; Address, Data:Cardinal):integer;stdcall; external 'ScommDll.dll' name 'PcdWrEEPROM';
//station
function PcdRdStation(PcdConn:Cardinal; Station:lpDataType):integer;stdcall; external 'ScommDll.dll' name 'PcdRdStation';
function PcdWrStation(PcdConn:Cardinal; Station:Cardinal):integer;stdcall; external 'ScommDll.dll' name 'PcdWrStation';
function PcdSetStation(PcdConn:Cardinal; Station:Cardinal):integer;stdcall; external 'ScommDll.dll' name 'PcdSetStation';
//extra
function PcdRdText(PcdConn:Cardinal; Number:Cardinal; lpLength:lpDataType; lpData:PChar):integer;stdcall; external 'ScommDll.dll' name 'PcdRdText';
{function PcdWrText not working yet!}
function PcdWrText(PcdConn:Cardinal; Number, Size:Cardinal; lpszText:PChar):integer;stdcall; external 'ScommDll.dll' name 'PcdWrText';
function PcdRdTextChar(PcdConn:Cardinal; Number, Offset:Cardinal; lpLength:lpDataType; lpData:PChar):integer;stdcall; external 'ScommDll.dll' name 'PcdRdTextChar';
function PcdWrTextChar(PcdConn:Cardinal; Number, Offset, Size:Cardinal; lpszText:PChar):integer;stdcall; external 'ScommDll.dll' name 'PcdWrTextChar';
//data blocks
function PcdRdDBItem(PcdConn:Cardinal; Number, Item:Cardinal; lpItems: lpDataType; lpData:lpDataDB):integer;stdcall; external 'ScommDll.dll' name 'PcdRdDBItem';
function PcdRdDB(PcdConn:Cardinal; Number:Cardinal; lpItems, lpData: lpDataType):integer;stdcall; external 'ScommDll.dll' name 'PcdRdDB';
implementation
{$R *.DFM}
function TConnectForm.GetMode:Integer;
begin
result:=mOpenData.Protocol;
end;
procedure TConnectForm.Start;
begin
PcdMessage(PcdRdChanSetupFromIni('SkidSim.ini', 'GoOnline', @mOpenData));
end;
function TConnectForm. GetChannelConnected(): boolean;
begin
if(PcdGetOpenData(PcdConn, @mOpenData) = 0) then
Result := mOpenData.bConnected
else Result := false;
end;
function TConnectForm.Connection(Handle:HWND; var Text:string): boolean;
var
str1 : string;
str2 : string;
TempString : array[0..32] of Char;
Buffer : PChar;
begin
Result := false;
if ((GetChannelConnected = false) {and (mOpenData.Protocol = 0)}) then
begin
Buffer := @TempString;
respons := PcdConnectChannel(Addr(PcdConn), @mOpenData, 0, Handle);
Text:=ShowStatus(respons ,'Connection : ');
if (respons = 0) then
begin
PcdGetPortName( @mOpenData,Buffer,32);
str1 := string(Buffer);
PcdGetBaudrateName( @mOpenData,Buffer,32);
str2 := string(Buffer);
Text:=Text+' '+ str1+ ', '+ str2 +' bps';
Result := mOpenData.bConnected
end
else Text := 'Disconnected';
end
else MessageDlg('Second connection!',mtWarning,[mbOk],0);
end;
procedure TConnectForm.SetupConnection(Handle:HWND; var Text:string);
begin
if (GetChannelConnected) then
begin
MessageDlg('Disconnect before changing communication options!',mtWarning,[mbOk],0);
if (MessageDlg('Disconnect?',mtConfirmation,[mbYes, mbNo],0)=mrYes) then
begin
Text:=ShowStatus(PcdDisconnectChannel(PcdConn , 0,Handle),'Disconnect : ');
if (respons = 0) then
begin
Text := 'Disconnected';
end;
end;
end
else
begin
respons := PcdRdChanSetupFromIni('SkidSim.ini', 'GoOnline', @mOpenData);
if(PcdConnectionDialog(handle, @mOpenData)= IDOK) then
begin
respons := PcdWrChanSetupToIni('SkidSim.ini', 'GoOnline', @mOpenData);
end;
Text:=ShowStatus(respons, 'Read - write setup to ini.');
end;
end;
procedure TConnectForm.Disconnect(Handle:HWND; var Text:string);
begin
if GetChannelConnected=true then
begin
respons := PcdDisconnectChannel(PcdConn , 0,Handle);
Text:=ShowStatus(respons, 'Disconnect : ');
if (respons = 0) then
begin
Text:= 'Disconnected';
end;
end
else Text:= 'Disconnected';
end;
function TConnectForm.ShowStatus(Status:Integer; LastOpr:string):string;
begin
result := LastOpr + StrPas(PcdMessage(Status));
end;
end.
|
{ Cette proc‚dure fournit les routines de base permettant de faire
fonctionner l'affichage VGA en mode 360x240 en 256 couleurs.
}
Program Routines360x240c256;
Type
{Tableau d'octet infini...}
TByte=Array[0..65520]of Byte;
{ModeInfoVideo}
MIV=Record
Mode:Word; { Mode vid‚o actuel (vm???)}
IbmLogic, { Mode dans la logique IBM (pas hors cas texte … la SVGA...)}
BiosSupport, { Mode support‚ par le Bios (Par exemple, la GS en 16 couleurs le Bios ne le connaŒt pas) }
Color, { Mode couleur? Sinon monochrome for‡‚ment...}
Graf, { Mode graphique? Sinon texte}
Direct, { M‚thode directe? Sinon Bios ou Dos}
Blink, { Clignotement?}
Snow:Boolean; { Neige lors de l'envoie de donn‚e dans le tampon vid‚o?}
SegVideo:Word; { Segment vid‚o (A000h,B000h,B800h,...)}
HeightChar:Byte; { Hauteur de la police de caractŠre actuel}
NumXPixels, { Nombre de pixels horizontal qu'affiche l'‚cran}
NumYPixels:Word; { Nombre de pixels vertical qu'affiche l'‚cran}
NumXTexts,NumYTexts, { Nombre de caractŠre texte horizontal/vertical qu'affiche l'‚cran}
NumVideoPages:Byte; { Nombre de page vid‚o que supporte le mode actuel}
NumColors:LongInt; { Nombre de couleurs affich‚}
BitsPerPixel:Byte; { Nombre de Bit(s) utilis‚ pour l'affichage d'un pixel}
BytesPerLine:Word; { Nombre d'octet par ligne affich‚ (trŠs relatif en VGA...)}
Page:Byte; { Num‚ro de la page vid‚o de travail}
AddrPage:Word; { En texte, adresse en m‚moire vid‚o de la page actuel}
ShowPage:Byte; { Num‚ro de la page vid‚o actuellement affich‚}
TextMatrix:^TByte; { Pointeur sur la police de caractŠre courante}
ScreenSize:LongInt; { Taille de l'‚cran}
SizeBank:Word; { Taille d'un page de la banque (0=64Ko)}
SegBuf:Word; { Segment du tampon d'acc‚l‚ration}
IsDoubleMatrixx:Boolean; { Y a-t-il utilisation d'une police de 512 caractŠres?}
XCursor,YCursor:Byte; { Position actuel du curseur}
StartCur,EndCur:Byte; { Ligne de d‚part et de fin du curseur}
End;
{ Voici un tableau de donn‚es utiliser pour l'affichage des ‚l‚ments
dans l'‚cran.
}
Procedure DataVideo;Assembler;ASM
DW 0 {Mode: Mode vid‚o actuel (vm???)}
DB False {IbmLogic: Mode dans la logique IBM (pas hors cas texte … la SVGA...)}
DB False {BiosSupport: Mode support‚ par le Bios (Par exemple, la GS en 16 couleurs le Bios ne le connaŒt pas)}
DB True {Color: Mode couleur? Sinon monochrome for‡‚ment...}
DB True {Graf: Mode graphique? Sinon texte}
DB True {Direct: M‚thode directe? Sinon Bios ou Dos}
DB False {Blink: Clignotement}
DB False {Snow: Neige lors de l'envoie de donn‚e dans le tampon vid‚o?}
DW 0A000h {SegVideo: Segment vid‚o (A000h,B000h,B800h,...) }
DB 8 {HeightChar: Hauteur de la police de caractŠre actuel}
DW 360 {NumXPixels: Nombre de pixels horizontal qu'affiche l'‚cran}
DW 240 {NumYPixels: Nombre de pixels vertical qu'affiche l'‚cran}
DB 45,30 {NumXTxts,NumYTxts:Nombre de caractŠre texte horizontal/vertical qu'affiche l'‚cran}
DB 2 {NumVideoPages: Nombre de page vid‚o que supporte le mode actuel}
DD 256 {NumColors: Nombre de couleurs affich‚}
DB 8 {BitsPerPixel: Nombre de Bit(s) utilis‚ pour l'affichage d'un pixel}
DW 90 {BytesPerLine: Nombre d'octet par ligne affich‚ (trŠs relatif en VGA...)}
DB 0 {Page: Num‚ro de la page vid‚o de travail}
DW 0 {AddrPage: En texte, adresse en m‚moire vid‚o de la page actuel}
DB 0 {ShowPage: Num‚ro de la page vid‚o actuellement affich‚}
DD 0 {TextMatrix: Pointeur sur la police de caractŠre courante}
DD 86400 {ScreenSize: Taille de l'‚cran}
DW 0 {SizeBank: Taille d'un page de la banque (0=64 Ko) }
DW 0 {SegBuf: Segment du tampon d'acc‚l‚ration}
DB 0 {IsDoubleMatrix: Y a-t-il une police de 512 caractŠres?}
DB 0,0 {XCursor,YCursor: Position actuel du curseur}
DB 0,0 {StartCur,EndCur: D‚but et fin du curseur}
END;
{Coordonn‚e brute de chacune des lignes afin d'obtenir de meilleur performance}
Procedure RealRawY;Assembler;ASM
{0 … 199}
DW 0, 90, 180, 270, 360, 450, 540, 630, 720, 810, 900, 990{0 … 11}
DW 1080, 1170, 1260, 1350, 1440, 1530, 1620, 1710, 1800, 1890, 1980, 2070{12 … 23}
DW 2160, 2250, 2340, 2430, 2520, 2610, 2700, 2790, 2880, 2970, 3060, 3150{24 … 35}
DW 3240, 3330, 3420, 3510, 3600, 3690, 3780, 3870, 3960, 4050, 4140, 4230{36 … 47}
DW 4320, 4410, 4500, 4590, 4680, 4770, 4860, 4950, 5040, 5130, 5220, 5310{48 … 63}
DW 5400, 5490, 5580, 5670, 5760, 5850, 5940, 6030, 6120, 6210, 6300, 6390{64 … 75}
DW 6480, 6570, 6660, 6750, 6840, 6930, 7020, 7110, 7200, 7290, 7380, 7470{76 … 87}
DW 7560, 7650, 7740, 7830, 7920, 8010, 8100, 8190, 8280, 8370, 8460, 8550{88 … 95}
DW 8640, 8730, 8820, 8910, 9000, 9090, 9180, 9270, 9360, 9450, 9540, 9630{96 … 107}
DW 9720, 9810, 9900, 9990,10080,10170,10260,10350,10440,10530,10620,10710{108 … 119}
DW 10800,10890,10980,11070,11160,11250,11340,11430,11520,11610,11700,11790{120 … 131}
DW 11880,11970,12060,12150,12240,12330,12420,12510,12600,12690,12780,12870{132 … 143}
DW 12960,13050,13140,13230,13320,13410,13500,13590,13680,13770,13860,13950{144 … 155}
DW 14040,14130,14220,14310,14400,14490,14580,14670,14760,14850,14940,15030{156 … 167}
DW 15120,15210,15300,15390,15480,15570,15660,15750,15840,15930,16020,16110{168 … 179}
DW 16200,16290,16380,16470,16560,16650,16740,16830,16920,17010,17100,17190{180 … 191}
DW 17280,17370,17460,17550,17640,17730,17820,17910
{ 200 … 399 }
DW 18000,18090,18180,18270,18360,18450,18540,18630,18720,18810,18900,18990
DW 19080,19170,19260,19350,19440,19530,19620,19710,19800,19890,19980,20070
DW 20160,20250,20340,20430,20520,20610,20700,20790,20880,20970,21060,21150
DW 21240,21330,21420,21510,21600,21690,21780,21870,21960,22050,22140,22230
DW 22320,22410,22500,22590,22680,22770,22860,22950,23040,23130,23220,23310
DW 23400,23490,23580,23670,23760,23850,23940,24030,24120,24210,24300,24390
DW 24480,24570,24660,24750,24840,24930,25020,25110,25200,25290,25380,25470
DW 25560,25650,25740,25830,25920,26010,26100,26190,26280,26370,26460,26550
DW 26640,26730,26820,26910,27000,27090,27180,27270,27360,27450,27540,27630
DW 27720,27810,27900,27990,28080,28170,28260,28350,28440,28530,28620,28710
DW 28800,28890,28980,29070,29160,29250,29340,29430,29520,29610,29700,29790
DW 29880,29970,30060,30150,30240,30330,30420,30510,30600,30690,30780,30870
DW 30960,31050,31140,31230,31320,31410,31500,31590,31680,31770,31860,31950
DW 32040,32130,32220,32310,32400,32490,32580,32670,32760,32850,32940,33030
DW 33120,33210,33300,33390,33480,33570,33660,33750,33840,33930,34020,34110
DW 34200,34290,34380,34470,34560,34650,34740,34830,34920,35010,35100,35190
DW 35280,35370,35460,35550,35640,35730,35820,35910
{ 400 … 479 }
DW 36000,36090,36180,36270,36360,36450,36540,36630,36720,36810,36900,36990 { 400 … 411 }
DW 37080,37170,37260,37350,37440,37530,37620,37710,37800,37890,37980,38070 { 412 … 423 }
DW 38160,38250,38340,38430,38520,38610,38700,38790,38880,38970,39060,39150 { 424 … 435 }
DW 39240,39330,39420,39510,39600,39690,39780,39870,39960,40050,40140,40230 { 436 … 447 }
DW 40320,40410,40500,40590,40680,40770,40860,40950,41040,41130,41220,41310 { 448 … 459 }
DW 41400,41490,41580,41670,41760,41850,41940,42030,42120,42210,42300,42390 { 460 … 471 }
DW 42480,42570,42660,42750,42840,42930,43020,43110,43200 { 472 … 480 }
{ 481 … ...: Hors limite!!!! }
DW 43290,43380,43470,43560,43650,43740,43830,43920,44010,44100,44190,44280 { 481 … 492 }
DW 44370,44460,44550,44640,44730,44820,44910,45000,45090,45180,45270,45360 { 493 … 504 }
DW 45450,45540,45630,45720,45810,45900,45990,46080,46170,46260,46350,46440 { 505 … 516 }
DW 46530,46620,46710,46800,46890,46980,47070,47160,47250,47340,47430,47520 { 517 … 528 }
DW 47610,47700,47790,47880,47970,48060,48150,48240,48330,48420,48510,48600 { 529 … 540 }
DW 48690,48780,48870,48960,49050,49140,49230,49320,49410,49500,49590,49680 { 541 … 552 }
DW 49770,49860,49950,50040,50130,50220,50310,50400,50490,50580,50670,50760 { 553 … 564 }
DW 50850,50940,51030,51120,51210,51300,51390,51480,51570,51660,51750,51840 { 565 … 576 }
DW 51930,52020,52110,52200,52290,52380,52470,52560,52650,52740,52830,52920 { 577 … 588 }
DW 53010,53100,53190,53280,53370,53460,53550,53640,53730,53820,53910,54000 { 589 … 600 }
{ 700 … ... }
DW 54090,54180,54270,54360,54450,54540,54630,54720,54810,54900,54990,55080 { 601 … 612 }
DW 55170,55260,55350,55440,55530,55620,55710,55800,55890,55980,56070,56160 { 613 … 624 }
DW 56250,56340,56430,56520,56610,56700,56790,56880,56970,57060,57150,57240 { 625 … 636 }
DW 57330,57420,57510,57600,57690,57780,57870,57960,58050,58140,58230,58320 { 637 … 648 }
DW 58410,58500,58590,58680,58770,58860,58950,59040,59130,59220,59310,59400 { 649 … 660 }
DW 59490,59580,59670,59760,59850,59940,60030,60120,60210,60300,60390,60480 { 661 … 672 }
DW 60570,60660,60750,60840,60930,61020,61110,61200,61290,61380,61470,61560 { 673 … 684 }
DW 61650,61740,61830,61920,62010,62100,62190,62280,62370,62460,62550,62640 { 685 … 696 }
DW 62730,62820,62910,63000,63090,63180,63270,63360,63450,63540,63630,63720 { 697 … 708 }
DW 63810,63900,63990,64080,64170,64260,64350,64440,64530,64620,64710,64800 { 709 … 720 }
DW 64890,64980,65070,65160,65250,65340,65430,65520 { 721 … 728 }
END;
Procedure SetMode360x240c256;Begin
ASM
{ Fixe le mode graphique 320x200 en 256 couleurs }
MOV AX,0013h
INT 10h
{ Reprogramme les registres pour le mode 360x240 en 256 couleurs }
MOV DX,03C4h
MOV AX,0604h
OUT DX,AX
MOV AX,0100h
OUT DX,AX
MOV DX,03C2h
MOV AL,0E7h
OUT DX,AL
MOV DX,03C4h
MOV AX,0300h
OUT DX,AX
MOV DX,03D4h
MOV AL,011h
OUT DX,AL
INC DX
IN AL,DX
AND AL,07Fh
OUT DX,AL
MOV DX,03D4h
CLD
JMP @Next
@DataSeq:
DW 06B00h { Total horizontal }
DW 05901h { Horizontal affich‚ }
DW 05A02h { D‚but de la p‚riode de blanc horizontal }
DW 08E03h { Fin de la p‚riode de blanc horizontal }
DW 05E04h { Position de retour de balayage horizontal }
DW 08A05h { Fin de retour de balyage horizontal }
DW 00D06h { Total vertical }
DW 03E07h { Bit 8 et 9 compl‚mentaires }
DW 04109h { Hauteur d'une cellule }
DW 0EA10h { Ligne de d‚clenchement du retour vertical de balayage }
DW 0AC11h { Ligne o— s'arrˆte le retour de balayage vertical et bit de protection }
DW 0DF12h { DerniŠre ligne de balayage affich‚e }
DW 02D13h { ®Offset¯ entre 2 lignes }
DW 00014h { Adressage en double mot ferm‚ }
DW 0E715h { Position de d‚part vertical o— le rayon cathodique est d‚sactiv‚ }
DW 00616h { Position de fin vertical o— le rayon cathodique est d‚sactiv‚ }
DW 0E317h { Fixe le mode octet activ‚ }
@Next:
MOV SI,Offset @DataSeq
MOV CX,17
PUSH DS
PUSH CS
POP DS
@@1:
LODSW
OUT DX,AX
LOOP @@1
POP DS
END;
MemW[0:$44A]:=45;
Mem[0:$484]:=30;
Mem[0:$485]:=8;
End;
{ Constante de plane 0 }
Procedure Plane0;Assembler;ASM
DB 0,3,2,1
END;
{ Constante de plane 1 }
Procedure Plane1;Assembler;ASM
DB 1,0,3,2
END;
{ Constante de plane 2 }
Procedure Plane2;Assembler;ASM
DB 2,1,0,3
END;
{ Constante de plane 3 }
Procedure Plane3;Assembler;ASM
DB 3,2,1,0
END;
{ Cette proc‚dure permet de lire une partie de l'‚cran … partir d'un
tampon de fa‡on totalement lin‚aire (et non pas par groupe de quatre
comme les routines de Hacker!). Ainsi le premier offset lin‚aire
correspondra au pixel (0,0), le deuxiŠme au pixel (1,0) et ainsi
de suite...
}
Procedure ReadBank(OffsetLinear:LongInt;L:Word;Var Buffer);Assembler;
Var
Start,StartPlane:Word;
Length:Integer;
ASM
LES AX,Buffer
MOV CX,ES
OR CX,AX
JZ @End
PUSH DS
MOV AX,L
{$IFOPT G+}
SHR AX,2
{$ELSE}
SHR AX,1
SHR AX,1
{$ENDIF}
MOV Length,AX
DEC L
LES AX,OffsetLinear
MOV DX,ES
MOV BX,AX
AND BX,3
MOV StartPlane,BX
SHR DX,1
RCR AX,1
SHR DX,1
RCR AX,1
SUB AX,BX
MOV Start,AX
{$IFDEF DPMI}
MOV DS,SegA000
{$ELSE}
MOV DS,DataVideo.MIV.SegVideo
{$ENDIF}
CLD
@Restart:
{ Fixe la plage 0 }
MOV DX,03CEh
MOV AX,4+(0 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon... ®P <- _AX¯ }
MOV BX,StartPlane
MOV AL,Byte Ptr Plane0[BX]
XOR AH,AH
{ Calcul le suppl‚ment de P1 ®_DI:=Byte(StartPlane>0);¯ }
XOR SI,SI
OR BL,BL
JZ @0
INC SI
@0:
{ Calcul l'incr‚mentation de P1 ®_DI+:=Start+StartPlane;¯ }
ADD SI,Start
ADD SI,BX
{ Calcul le ®LenSub¯ ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1
CMP DX,AX
JNAE @1
INC CX
@1:{For J:=0to(Len)do Begin
Buffer[P]:=Mem[_A000:P1];
Inc(P,4);Inc(P1)
End;}
LES DI,Buffer
ADD DI,AX
ADD CX,Length
JCXZ @3
@2:
MOVSB
INC DI
INC DI
INC DI
LOOP @2
@3:
{ Fixe la plage 1 }
MOV DX,03CEh
MOV AX,4+(1 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon...}
MOV BX,StartPlane
MOV AL,Byte Ptr Plane1[BX]
XOR AH,AH
{ Calcul le suppl‚ment de P1 ®_DI:=Byte(StartPlane>1);¯ }
XOR SI,SI
CMP BL,1
JNA @0b
INC SI
@0b:
{ Calcul l'incr‚mentation de P1 ®_DI+:=Start+StartPlane;¯ }
ADD SI,Start
ADD SI,BX
{ Calcul le LenSub ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1b
CMP DX,AX
JNAE @1b
INC CX
@1b:
{For J:=0to(Len)do Begin
Buffer[P]:=Mem[_A000:P1];
Inc(P,4);Inc(P1)
End;}
LES DI,Buffer
ADD DI,AX
ADD CX,Length
JCXZ @3b
@2b:
MOVSB
INC DI
INC DI
INC DI
LOOP @2b
@3b:
{ Fixe la plage 2 }
MOV DX,03CEh
MOV AX,4+(2 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon...}
MOV BX,StartPlane
MOV AL,Byte Ptr Plane2[BX]
XOR AH,AH
{ Calcul le suppl‚ment de P1 ®_DI:=Byte(StartPlane>2);¯ }
XOR SI,SI
CMP BL,2
JNA @0c
INC SI
@0c:
{ Calcul l'incr‚mentation de P1 ®_DI+:=Start+StartPlane;¯ }
ADD SI,Start
ADD SI,BX
{ Calcul le LenSub ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1c
CMP DX,AX
JNAE @1c
INC CX
@1c:
LES DI,Buffer
ADD DI,AX
ADD CX,Length
JCXZ @3c
@2c:
MOVSB
INC DI
INC DI
INC DI
LOOP @2c
@3c:
{ Fixe la plage 3 }
MOV DX,03CEh
MOV AX,4+(3 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon...}
MOV BX,StartPlane
MOV AL,Byte Ptr Plane3[BX]
XOR AH,AH
{ Calcul l'incr‚mentation de P1 ®_DI:=Start+StartPlane;¯ }
MOV SI,Start
ADD SI,BX
{ Calcul le LenSub ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1d
CMP DX,AX
JNAE @1d
INC CX
@1d:
LES DI,Buffer
ADD DI,AX
ADD CX,Length
JCXZ @3d
@2d:
MOVSB
INC DI
INC DI
INC DI
LOOP @2d
@3d:
POP DS
@End:
END;
{ Cette proc‚dure permet d'‚crire une partie de l'‚cran … partir d'un
tampon de fa‡on totalement lin‚aire (et non pas par groupe de quatre
comme les routines de Hacker!). Ainsi le premier offset lin‚aire
correspondra au pixel (0,0), le deuxiŠme au pixel (1,0) et ainsi
de suite...
}
Procedure WriteBank(OffsetLinear:LongInt;L:Word;Var Buffer);Assembler;
Var
Start,StartPlane:Word;
Length:Integer;
ASM
PUSH DS
MOV AX,L
{$IFOPT G+}
SHR AX,2
{$ELSE}
SHR AX,1
SHR AX,1
{$ENDIF}
MOV Length,AX
DEC L
LES AX,OffsetLinear
MOV DX,ES
MOV BX,AX
AND BX,3
MOV StartPlane,BX
SHR DX,1
RCR AX,1
SHR DX,1
RCR AX,1
SUB AX,BX
MOV Start,AX
MOV ES,DataVideo.MIV.SegVideo
CLD
@Restart:
{ Fixe la plage 0 }
MOV DX,$3C4
MOV AX,2+(1 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon... ®P==_AX¯ }
MOV BX,StartPlane
MOV AL,Byte Ptr Plane0[BX]
XOR AH,AH
{ Calcul le suppl‚ment de P1 ®_DI:=Byte(StartPlane>0);¯ }
XOR DI,DI
OR BL,BL
JZ @0
INC DI
@0:
{ Calcul l'incr‚mentation de P1 ®_DI+:=Start+StartPlane;¯ }
ADD DI,Start
ADD DI,BX
{ Calcul le LenSub ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1
CMP DX,AX
JNAE @1
INC CX
@1:{For J:=0to(Len)do Begin;Mem[_A000:P1]:=Buf[P];Inc(P,4);Inc(P1)End;}
LDS SI,Buffer
ADD SI,AX
ADD CX,Length
JCXZ @3
@2:LODSW
INC SI
INC SI
STOSB
LOOP @2
@3:
{ Fixe la plage 1 }
MOV DX,$3C4
MOV AX,2+(2 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon...}
MOV BX,StartPlane
MOV AL,Byte Ptr Plane1[BX]
XOR AH,AH
{ Calcul le suppl‚ment de P1 ®_DI:=Byte(StartPlane>1);¯ }
XOR DI,DI
CMP BL,1
JNA @0b
INC DI
@0b:
{ Calcul l'incr‚mentation de P1 ®_DI+:=Start+StartPlane;¯ }
ADD DI,Start
ADD DI,BX
{ Calcul le LenSub ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1b
CMP DX,AX
JNAE @1b
INC CX
@1b:
{For J:=0to(Len)do Begin;Mem[_A000:P1]:=Buf[P];Inc(P,4);Inc(P1)End;}
LDS SI,Buffer
ADD SI,AX
ADD CX,Length
JCXZ @3b
@2b:
LODSW
INC SI
INC SI
STOSB
LOOP @2b
@3b:
{ Fixe la plage 2 }
MOV DX,03C4h
MOV AX,2+(4 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon...}
MOV BX,StartPlane
MOV AL,Byte Ptr Plane2[BX]
XOR AH,AH
{ Calcul le suppl‚ment de P1 ®_DI:=Byte(StartPlane>2);¯ }
XOR DI,DI
CMP BL,2
JNA @0c
INC DI
@0c:
{ Calcul l'incr‚mentation de P1 ®_DI+:=Start+StartPlane;¯ }
ADD DI,Start
ADD DI,BX
{ Calcul le LenSub ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1c
CMP DX,AX
JNAE @1c
INC CX
@1c:
{For J:=0to(Len)do Begin
Mem[_A000:P1]:=Buffer[P];
Inc(P,4);Inc(P1)
End;}
LDS SI,Buffer
ADD SI,AX
ADD CX,Length
JCXZ @3c
@2c:LODSW
INC SI
INC SI
STOSB
LOOP @2c
@3c:
{ Fixe la plage 3 }
MOV DX,03C4h
MOV AX,2+(8 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon...}
MOV BX,StartPlane
MOV AL,Byte Ptr Plane3[BX]
XOR AH,AH
{ Calcul le suppl‚ment de P1 ®_DI:=Byte(StartPlane>3);¯ }
XOR DI,DI
CMP BL,3
JNA @0d
INC DI
@0d:
{ Calcul l'incr‚mentation de P1 ®_DI+:=Start+StartPlane;¯ }
ADD DI,Start
ADD DI,BX
{ Calcul le LenSub ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1d
CMP DX,AX
JNAE @1d
INC CX
@1d:
{For J:=0to(Len)do Begin;Mem[_A000:P1]:=Buf[P];Inc(P,4);Inc(P1)End;}
LDS SI,Buffer
ADD SI,AX
ADD CX,Length
JCXZ @3d
@2d:
LODSW
INC SI
INC SI
STOSB
LOOP @2d
@3d:
POP DS
END;
{ Cette proc‚dure permet d'effacer une partie de l'‚cran de fa‡on
totalement lin‚aire (et non pas par groupe de quatre comme les
routines de Hacker!). Ainsi le premier offset lin‚aire correspondra
au pixel (0,0), le deuxiŠme au pixel (1,0) et ainsi de suite...
}
Procedure FillBank(OffsetLinear:LongInt;L,Color:Word);Assembler;
Var
Start,StartPlane:Word;
Length:Integer;
ASM
MOV AX,L
{$IFOPT G+}
SHR AX,2
{$ELSE}
SHR AX,1
SHR AX,1
{$ENDIF}
MOV Length,AX
DEC L
LES AX,OffsetLinear
MOV DX,ES
MOV BX,AX
AND BX,3
MOV StartPlane,BX
SHR DX,1
RCR AX,1
SHR DX,1
RCR AX,1
SUB AX,BX
MOV Start,AX
MOV ES,DataVideo.MIV.SegVideo
CLD
@Restart:
{ Fixe la plage 0 }
MOV DX,03C4h
MOV AX,2+(1 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon... ®P <- _AX¯ }
MOV BX,StartPlane
MOV AL,Byte Ptr Plane0[BX]
XOR AH,AH
{ Calcul le suppl‚ment de P1 ®_DI:=Byte(StartPlane>0);¯ }
XOR DI,DI
OR BL,BL
JZ @0
INC DI
@0:
{ Calcul l'incr‚mentation de P1 ®_DI+:=Start+StartPlane;¯ }
ADD DI,Start
ADD DI,BX
{ Calcul le LenSub ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1
CMP DX,AX
JNAE @1
INC CX
@1:{For J:=0to(Length)do Begin
Mem[_A000:P1]:=Color;
Inc(P1)
End;}
ADD CX,Length
MOV AL,Byte Ptr Color
MOV AH,AL
SHR CX,1
REP STOSW
ADC CX,CX
REP STOSB
{ Fixe la plage 1 }
MOV DX,03C4h
MOV AX,2+(2 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon...}
MOV BX,StartPlane
MOV AL,Byte Ptr Plane1[BX]
XOR AH,AH
{ Calcul le suppl‚ment de P1 ®_DI:=Byte(StartPlane>1);¯ }
XOR DI,DI
CMP BL,1
JNA @0b
INC DI
@0b:
{ Calcul l'incr‚mentation de P1 ®_DI+:=Start+StartPlane;¯ }
ADD DI,Start
ADD DI,BX
{ Calcul le LenSub ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1b
CMP DX,AX
JNAE @1b
INC CX
@1b:
{For J:=0to(Length)do Begin
Mem[_A000:P1]:=Color;
Inc(P1)
End;}
ADD CX,Length
MOV AL,Byte Ptr Color
MOV AH,AL
SHR CX,1
REP STOSW
ADC CX,CX
REP STOSB
{ Fixe la plage 2 }
MOV DX,03C4h
MOV AX,2+(4 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon...}
MOV BX,StartPlane
MOV AL,Byte Ptr Plane2[BX]
XOR AH,AH
{ Calcul le suppl‚ment de P1 ®_DI:=Byte(StartPlane>2);¯ }
XOR DI,DI
CMP BL,2
JNA @0c
INC DI
@0c:
{ Calcul l'incr‚mentation de P1 ®_DI+:=Start+StartPlane;¯ }
ADD DI,Start
ADD DI,BX
{ Calcul le LenSub ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1c
CMP DX,AX
JNAE @1c
INC CX
@1c:
ADD CX,Length
MOV AL,Byte Ptr Color
MOV AH,AL
SHR CX,1
REP STOSW
ADC CX,CX
REP STOSB
{ Fixe la plage 3 }
MOV DX,03C4h
MOV AX,2+(8 shl 8)
OUT DX,AX
{ Calcule le point de d‚part dans le tampon...}
MOV BX,StartPlane
MOV AL,Byte Ptr Plane3[BX]
XOR AH,AH
{ Calcul l'incr‚mentation de P1 ®_DI:=Start+StartPlane;¯ }
MOV DI,Start
ADD DI,BX
{ Calcul le LenSub ®_CX:=(L ï 3 < 3) ï (L ï 3 >= P) ? 1 : 0;¯}
XOR CX,CX
MOV DX,L
AND DX,3
CMP DX,3
JNB @1d
CMP DX,AX
JNAE @1d
INC CX
@1d:
ADD CX,Length
MOV AL,Byte Ptr Color
MOV AH,AL
SHR CX,1
REP STOSW
ADC CX,CX
REP STOSB
END;
{ Cette proc‚dure permet d'effacer l'‚cran avec la couleur d‚sir‚
}
Procedure ClearScreen(Color:Byte);Assembler;ASM
CLD
MOV AL,Color
MOV AH,AL
MOV CX,32000
XOR DI,DI
{$IFDEF DPMI}
MOV ES,SegA000
{$ELSE}
MOV ES,DataVideo.MIV.SegVideo
{$ENDIF}
REP STOSW
END;
{ Cette proc‚dure permet d'effacer l'‚cran avec la couleur noir.
}
Procedure ClearScreenBlack;Begin
ClearScreen(0);
End;
{ Cette proc‚dure permet de tracer une ligne de longueur ®Length¯
… partir de la coordonn‚e (X,Y) avec la couleur ®Color¯.
}
Procedure ClearLineHor(X,Y,Length:Word;Color:Byte);Assembler;ASM
MOV BX,Y
CMP BX,DataVideo.MIV.NumYPixels
JAE @End
SHL BX,1
MOV AX,Word Ptr RealRawY[BX]
ADD AX,DataVideo.MIV.AddrPage
XOR DX,DX
SHL AX,1
RCL DX,1
SHL AX,1
RCL DX,1
ADD AX,X
ADC DX,0
PUSH DX
PUSH AX
PUSH Length
PUSH Word Ptr Color
CALL FillBank
@End:
END;
{ Cette proc‚dure permet d'afficher un pixel … l'‚cran.
}
Procedure SetPixel(X,Y:Word;Color:Byte);Assembler;ASM
TEST X,8000h
JNZ @End
{$IFDEF DPMI}
MOV ES,SegA000
{$ELSE}
MOV ES,DataVideo.MIV.SegVideo
{$ENDIF}
MOV CX,X
AND CX,3
MOV AX,1
SHL AX,CL
MOV AH,AL
MOV DX,3C4h
MOV AL,2
OUT DX,AX
MOV DI,Y
SHL DI,1
MOV DI,Word Ptr RealRawY[DI]
MOV AX,X
{$IFOPT G+}
SHR AX,2
{$ELSE}
SHR AX,1
SHR AX,1
{$ENDIF}
ADD DI,AX
ADD DI,DataVideo.MIV.AddrPage
MOV AL,Byte Ptr Color
STOSB
@End:
END;
{ Cette proc‚dure permet de programmer une palette de couleur RVB (RGB)
avec une couleur des valeurs comprise entre 0 et 255.
}
Procedure SetPaletteRGB(Color,R,G,B:Byte);Assembler;ASM
MOV DX,3C8h
MOV AL,Byte Ptr Color
OUT DX,AL
INC DX
MOV AL,R
{$IFOPT G+}
SHR AL,2
{$ELSE}
SHR AL,1
SHR AL,1
{$ENDIF}
OUT DX,AL
MOV AL,G
{$IFOPT G+}
SHR AL,2
{$ELSE}
SHR AL,1
SHR AL,1
{$ENDIF}
OUT DX,AL
MOV AL,B
{$IFOPT G+}
SHR AL,2
{$ELSE}
SHR AL,1
SHR AL,1
{$ENDIF}
OUT DX,AL
END;
Var I:Word;
BEGIN
SetMode360x240c256;
ClearScreenBlack;
For I:=0to 239do SetPixel(I,I,I);
ClearLineHor(20,10,100,15);
{ Attend que l'utilisateur presse une touche }
ASM
XOR AX,AX
INT 16h
END;
END. |
unit ItemsView;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Data.DB, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids,
Generics.Collections,
Aurelius.Bind.Dataset,
Data.Repositories.IItemsRepository,
Data.Entities.Item;
type
TfrmItemsView = class(TForm)
DBGridItems: TDBGrid;
PanelTop: TPanel;
AureliusDatasetItems: TAureliusDataset;
DataSourceItems: TDataSource;
AureliusDatasetItemsId: TIntegerField;
AureliusDatasetItemsTitle: TStringField;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure AureliusDatasetItemsObjectInsert(Dataset: TDataSet; AObject: TObject);
procedure AureliusDatasetItemsObjectRemove(Dataset: TDataSet; AObject: TObject);
procedure AureliusDatasetItemsObjectUpdate(Dataset: TDataSet; AObject: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FRepository: IItemsRepository;
FItems: TList<TItem>;
public
{ Public declarations }
end;
var
frmItemsView: TfrmItemsView;
implementation
uses
Spring.Services,
DSharp.Aspects.Weaver;
{$R *.dfm}
procedure TfrmItemsView.AureliusDatasetItemsObjectInsert(Dataset: TDataSet;
AObject: TObject);
begin
FRepository.Add(AObject as TItem);
end;
procedure TfrmItemsView.AureliusDatasetItemsObjectRemove(Dataset: TDataSet;
AObject: TObject);
begin
FRepository.Remove(AObject as TItem);
end;
procedure TfrmItemsView.AureliusDatasetItemsObjectUpdate(Dataset: TDataSet;
AObject: TObject);
begin
FRepository.Update(AObject as TItem);
end;
procedure TfrmItemsView.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmItemsView.FormCreate(Sender: TObject);
begin
//FRepository := ServiceLocator.GetService<IItemsRepository>;
//TODO: find a way to assign Proxifier to global ServiceLocator service.
FRepository := AspectWeaver.Proxify<IItemsRepository>(ServiceLocator.GetService<IItemsRepository>);
FItems := FRepository.GetAll;
AureliusDatasetItems.SetSourceList(FItems);
AureliusDatasetItems.Open;
end;
end.
|
unit FrmAddUsers;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, RzButton, StdCtrls, RzCmboBx, Mask, RzEdit, uDefine,
FrmBase, uTransform, uDBFieldData, ActiveX, uControlInf;
type
TAddUsersForm = class(TBaseForm)
pnl1: TPanel;
rzbtbtnOK: TRzBitBtn;
rzbtbtnCancel: TRzBitBtn;
lblLocation: TLabel;
lblUserID: TLabel;
lblUserName: TLabel;
cbbLocation: TRzComboBox;
edtUserID: TRzEdit;
edtUserName: TRzEdit;
procedure FormShow(Sender: TObject);
procedure rzbtbtnCancelClick(Sender: TObject);
procedure rzbtbtnOKClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
class function DisplayOutForm(AHandle: THandle): Boolean;
end;
implementation
{$R *.dfm}
{ TAddUsersForm }
class function TAddUsersForm.DisplayOutForm(AHandle: THandle): Boolean;
var
AddUsersForm: TAddUsersForm;
begin
AddUsersForm := TAddUsersForm.Create(Application, AHandle);
try
if AddUsersForm.ShowModal = mrOk then
begin
Result := True;
end
else
Result := False;
finally
if Assigned(AddUsersForm) then
FreeAndNil(AddUsersForm);
end;
end;
procedure TAddUsersForm.FormShow(Sender: TObject);
var
i: Integer;
sDBNameAndCondition, sCondition: string;
begin
//LocationTypeId = 1 只查找场内部门,因为员工只归属于场内部门
sCondition := ' where LocationTypeId = 1 ';
sDBNameAndCondition := Format(' %s %s ', [CSLocationDBName, sCondition]);
ReloadDBItemToCombox(cbbLocation, sDBNameAndCondition, CSName);
//ReloadDBItemToCombox(cbBrand, CSBrandDBName, CSName);
for i := 0 to pnl1.ControlCount - 1 do
begin
if pnl1.Controls[i] is TRzEdit then
TRzEdit(pnl1.Controls[i]).Clear;
if pnl1.Controls[i] is TRzComboBox then
TRzComboBox(pnl1.Controls[i]).ItemIndex := 0;
end;
//cbOperationType.Items.AddStrings(DMForm.stOperationType);
end;
procedure TAddUsersForm.rzbtbtnCancelClick(Sender: TObject);
begin
if MessageDlg('确定返回?', mtConfirmation, [MbYES, MbNo], 0) = MrYES then Self.ModalResult := mrCancel;
end;
procedure TAddUsersForm.rzbtbtnOKClick(Sender: TObject);
var
IXMLDBData: IXMLGuoSenDeviceSystemType;
IXMLRowItem: IXMLRowItemType;
IXMLFieldItem: IXMLFieldType;
begin
//有效性判断
if Trim(cbbLocation.Text) = '' then begin cbbLocation.SetFocus; raise Exception.Create('场内部门不能为空!'); exit; end;
if Trim(edtUserID.Text) = '' then begin edtUserID.SetFocus; raise Exception.Create('员工Lotus号不能为空!'); exit; end;
if Trim(edtUserName.Text) = '' then begin edtUserName.SetFocus; raise Exception.Create('员工姓名不能为空!'); exit; end;
//重复性检查
//写入数据库
CoInitialize(nil);
IXMLDBData := NewGuoSenDeviceSystem;
try
IXMLDBData.DBData.OperaterType := 'write';
IXMLDBData.DBData.DBTable := CSUserDBName;
AddUserInfoColData(IXMLDBData);
IXMLRowItem := IXMLDBData.DBData.RowData.Add;
IXMLFieldItem := IXMLRowItem.Add;
IXMLFieldItem.Name := CSUserId;
IXMLFieldItem.Value := edtUserID.Text;
IXMLFieldItem := IXMLRowItem.Add;
IXMLFieldItem.Name := CSUserName;
IXMLFieldItem.Value := edtUserName.Text;
IXMLFieldItem := IXMLRowItem.Add;
IXMLFieldItem.Name := CSLocationId;
IXMLFieldItem.Value := IntToStr(gDatabaseControl.GetDBIdByDBName(CSLocationDBName, CSName, cbbLocation.Text));
gDatabaseControl.AddUserFromXMLData(IXMLDBData);
Self.ModalResult := mrOk;
finally
IXMLDBData := nil;
CoUninitialize;
end;
end;
end.
|
unit uMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, notifyIntf;
type
TClsMgr = class(TObject)
private
FFrmCls: TFormClass;
public
constructor Create(FrmClass: TFormClass);
destructor Destroy; override;
function CreateForm(AOwner: TComponent): TForm;
end;
TFrmMain = class(TForm, IClsRegister)
lst_sel: TListBox;
pnl_view: TPanel;
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lst_selClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FCurrFrom: TForm;
procedure load;
{IClsRegister}
procedure RegCls(const aName: string; cls: TFormClass);
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
uses SysSvc, NotifyServiceIntf;
{$R *.dfm}
procedure TFrmMain.load;
var intf: INotifyService;
begin
if SysService.QueryInterface(INotifyService, Intf) = S_OK then
begin
self.lst_sel.Clear;
Intf.SendNotify(NotifyFlag, self, 0);
end;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
FCurrFrom := nil;
end;
procedure TFrmMain.FormDestroy(Sender: TObject);
var i: Integer;
begin
for i := 0 to self.lst_sel.Items.Count - 1 do
self.lst_sel.Items.Objects[i].Free;
end;
procedure TFrmMain.FormShow(Sender: TObject);
begin
load;
end;
procedure TFrmMain.lst_selClick(Sender: TObject);
var ClsMgr: TClsMgr;
idx: Integer;
begin
idx := lst_sel.ItemIndex;
if idx <> -1 then
begin
if FCurrFrom <> nil then
FCurrFrom.Free;
ClsMgr := TClsMgr(self.lst_sel.Items.Objects[idx]);
FCurrFrom := ClsMgr.CreateForm(self);
FCurrFrom.Parent := self.pnl_view;
FCurrFrom.BorderStyle := bsNone;
FCurrFrom.Align := alClient;
FCurrFrom.Show;
end;
end;
{ TClsMgr }
constructor TClsMgr.Create(FrmClass: TFormClass);
begin
self.FFrmCls := FrmClass;
end;
function TClsMgr.CreateForm(AOwner: TComponent): TForm;
begin
Assert(self.FFrmCls <> nil);
Result := self.FFrmCls.Create(AOwner);
end;
destructor TClsMgr.Destroy;
begin
inherited;
end;
procedure TFrmMain.RegCls(const aName: string; cls: TFormClass);
var ClsMgr: TClsMgr;
begin
ClsMgr := TClsMgr.Create(cls);
self.lst_sel.AddItem(aName, ClsMgr);
end;
end.
|
unit aOPCChartMessureTool;
{$I VCL.DC.inc}
interface
uses
System.Classes, System.SysUtils, System.Types,
Winapi.Windows, Controls,
{$IFDEF TEEVCL}
VCLTee.Series, VCLTee.TeEngine, VCLTee.TeCanvas, VCLTee.TeeProcs, VCLTee.TeeTools,
{$ELSE}
Series, TeEngine, TeCanvas, TeeProcs, TeeTools,
{$ENDIF}
uDCObjects;
const
TeeMsg_OPCMessureTool = 'Messure';
TeeMsg_OPCMessureToolDesc = 'Allow messure series values.';
TeeMsg_OPCMessureBandTool = 'Messure Band';
TeeMsg_OPCMessureBandToolDesc = 'Allow select and messure series values.';
type
TaOPCMessureLine = class(TColorLineTool)
end;
TaOPCMessureBand = class(TColorBandTool)
private
IDragging: Boolean;
FShift: Double;
FDragRepaint: Boolean;
FNoLimitDrag: Boolean;
FAllowDrag: Boolean;
function Chart: TCustomAxisPanel;
protected
procedure ChartMouseEvent(AEvent: TChartMouseEvent; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
function LimitValue(const AValue: Double): Double; // 7.0 moved from private
function Clicked(X, Y: Integer): Boolean; // 6.02
published
property AllowDrag: Boolean read FAllowDrag write FAllowDrag default True;
property DragRepaint: Boolean read FDragRepaint write FDragRepaint
default True;
property NoLimitDrag: Boolean read FNoLimitDrag write FNoLimitDrag
default False;
end;
// TaOPCTextShape = class(TTextShape)
// public
//
// end;
TDCCustomMessureTool = class(TRectangleTool)
protected
FAxis: TChartAxis;
procedure SetAxis(const Value: TChartAxis); virtual;
function CalcSeriesValue(aSeries: TFastLineSeries; x: Double; var aValue: Double): Boolean;
function GetSeriesValueStr(aSeries: TFastLineSeries; x: Double): string;
published
property Axis: TChartAxis read FAxis write SetAxis stored False;
end;
TaOPCMessureTool = class(TDCCustomMessureTool)
private
FLine: TaOPCMessureLine;
function NewColorLine: TaOPCMessureLine;
procedure DragLine(Sender: TColorLineTool);
protected
procedure SetAxis(const Value: TChartAxis); override;
procedure PaintLine;
procedure SetParentChart(const Value: TCustomAxisPanel); override;
procedure ChartEvent(AEvent: TChartToolEvent); override;
// procedure DoDrawText; overload; override;
Procedure DoDrawText(const AParent: TCustomAxisPanel); overload; override;
procedure ShapeDrawText(Panel: TCustomAxisPanel; R: TRect; XOffset, NumLines: Integer);
public
property Line: TaOPCMessureLine read FLine;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function Description: String; override;
class function LongDescription: String; override;
end;
TaOPCMessureBandTool = class(TDCCustomMessureTool)
private
FBand: TaOPCMessureBand;
function NewBand: TaOPCMessureBand;
procedure DragLine(Sender: TColorLineTool);
protected
procedure SetAxis(const Value: TChartAxis); override;
// procedure PaintBand;
procedure SetParentChart(const Value: TCustomAxisPanel); override;
procedure ChartEvent(AEvent: TChartToolEvent); override;
// procedure DrawText; overload; override;
procedure DoDrawText(const AParent: TCustomAxisPanel); overload; override;
procedure ShapeDrawText(Panel: TCustomAxisPanel; R: TRect; XOffset, NumLines: Integer);
public
property Band: TaOPCMessureBand read FBand;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function Description: String; override;
class function LongDescription: String; override;
end;
implementation
uses
aOPCUtils,
aOPCLineSeries;
{ TaOPCMessureTool }
procedure TaOPCMessureTool.ChartEvent(AEvent: TChartToolEvent);
begin
inherited;
case AEvent of
// cteBeforeDrawAxes: if DrawBehindAxes then PaintBand;
cteBeforeDrawSeries:
PaintLine;
// cteAfterDraw: if (not DrawBehind) and (not DrawBehindAxes) then PaintBand;
end;
end;
constructor TaOPCMessureTool.Create(AOwner: TComponent);
begin
inherited;
with Shape do
begin
Shadow.Size := 2;
Transparency := 0;
ShapeBounds.Left := 10;
ShapeBounds.Top := 10;
Width := 150;
Height := 50;
end;
FLine := NewColorLine;
FLine.Pen.Width := 0;
end;
class function TaOPCMessureTool.Description: String;
begin
Result := TeeMsg_OPCMessureTool;
end;
destructor TaOPCMessureTool.Destroy;
begin
FreeAndNil(FLine);
inherited;
end;
procedure TaOPCMessureTool.DragLine(Sender: TColorLineTool);
// var
// tmpWidth: Integer;
begin
// tmpWidth := Shape.Width;
// Shape.Left := Axis.CalcPosValue(Line.Value) + 5;
// Shape.Width := tmpWidth;
end;
procedure TaOPCMessureTool.DoDrawText(const AParent: TCustomAxisPanel);
var
// tmpTo : TPoint;
// tmpMid : TPoint;
// tmpFrom : TPoint;
tmpR: TRect;
tmpN, tmpX, tmpY: Integer;
begin
Shape.Text := ''; //GetText;
tmpR := GetTextBounds(tmpN, tmpX); // ,tmpY);
// Shape.DrawText(ParentChart, tmpR, GetXOffset, tmpN);
ShapeDrawText(ParentChart, tmpR, GetXOffset, tmpN);
// with Callout do
// if Visible or Arrow.Visible then
// begin
// tmpTo:=TeePoint(XPosition,YPosition);
// tmpFrom:=CloserPoint(tmpR,tmpTo);
//
// if Distance<>0 then
// tmpTo:=PointAtDistance(tmpFrom,tmpTo,Distance);
//
// tmpMid.X:=0;
// tmpMid.Y:=0;
//
// {$IFDEF LCL}Self.Callout.{$ENDIF}Draw(clNone,tmpTo,tmpMid,tmpFrom,ZPosition);
// end;
end;
class function TaOPCMessureTool.LongDescription: String;
begin
Result := TeeMsg_OPCMessureToolDesc;
end;
function TaOPCMessureTool.NewColorLine: TaOPCMessureLine;
begin
Result := TaOPCMessureLine.Create(nil);
Result.Active := False;
Result.DragRepaint := True;
Result.OnDragLine := Self.DragLine;
// result.Pen.OnChange := CanvasChanged;
// Result.ParentChart := nil;
end;
procedure TaOPCMessureTool.PaintLine;
begin
if Assigned(Axis) then
begin
if FLine.Active then
begin
// FLine.Value := StartValue;
FLine.InternalDrawLine(False);
end;
end;
end;
procedure TaOPCMessureTool.SetAxis(const Value: TChartAxis);
begin
FAxis := Value;
FLine.Axis := Value;
end;
procedure TaOPCMessureTool.SetParentChart(const Value: TCustomAxisPanel);
begin
inherited;
if Assigned(FLine) then
FLine.ParentChart := Value;
end;
procedure TaOPCMessureTool.ShapeDrawText(Panel: TCustomAxisPanel; R: TRect;
XOffset, NumLines: Integer);
var
X: Integer;
t: Integer;
// tmp : String;
tmpTop: Integer;
tmpHeight: Integer;
saveColor: Integer;
// v: Double;
vStr: string;
begin
OffsetRect(R, Panel.ChartBounds.Left, Panel.ChartBounds.Top);
if Shape.Visible then
{$IFDEF TEEVCL}
Shape.Draw(Panel, R);
{$ELSE}
Shape.DrawRectRotated(Panel, R);
{$ENDIF}
With Panel.Canvas do
begin
if Self.ClipText then
ClipRectangle(R);
try
BackMode := cbmTransparent;
case TextAlignment of
taLeftJustify:
begin
TextAlign := TA_LEFT;
X := R.Left + Shape.Margins.Size.Left;
if Self.Pen.Visible then
Inc(X, Self.Pen.Width);
end;
taCenter:
begin
TextAlign := ta_Center;
with R do
X := 1 + ((Left + Shape.Margins.Size.Left + Right -
Shape.Margins.Size.Right) div 2);
end;
else
begin
TextAlign := ta_Right;
X := R.Right - Shape.Margins.Size.Right;
end;
end;
AssignFont(Shape.Font);
tmpHeight := FontHeight;
tmpTop := R.Top + Shape.Margins.Size.Top;
TextOut(X + XOffset, tmpTop, FormatDateTime('dd.mm.yyyy HH:MM:SS',
FLine.Value), Shape.TextFormat = ttfHtml);
saveColor := Font.Color;
for t := 0 to ParentChart.SeriesCount - 1 do
begin
if ParentChart.Series[t] is TaOPCLineSeries then
begin
//vStr := TaOPCLineSeries(ParentChart.Series[t]).GetSerieValueStr(FLine.Value);
vStr := TaOPCLineSeries(ParentChart.Series[t]).GetSerieValueAndDurationStr(FLine.Value, True);
Font.Color := ParentChart.Series[t].Color;
TextOut(X + XOffset, tmpTop + (t + 1) * tmpHeight, vStr, Shape.TextFormat = ttfHtml);
end;
end;
Font.Color := saveColor;
if (ParentChart.SeriesCount + 1) * tmpHeight + 5 > Shape.Height then
Shape.Height := (ParentChart.SeriesCount + 1) * tmpHeight + 5;
finally
if Shape.ClipText then
UnClipRectangle;
end;
end;
end;
{ TaOPCMessureBandTool }
// procedure TaOPCMessureBandTool.ChartEvent(AEvent: TChartToolEvent);
// begin
// inherited;
//
// end;
function TDCCustomMessureTool.CalcSeriesValue(aSeries: TFastLineSeries; x: Double; var aValue: Double): Boolean;
var
i: Integer;
i1,i2: Integer;
begin
i2 := -1;
// ищем время больше заданного (возможен бинарный поиск, т.к. время только возрастает)
for i := 0 to aSeries.XValues.Count - 1 do
begin
// нашли точное соотверствие
if aSeries.XValues[i] = x then
begin
aValue := aSeries.YValues[i];
Exit(True);
end;
// нашли индекс точки с большим временем
if aSeries.XValues[i] > x then
begin
i2 := i;
Break;
end;
end;
// все точки имеют МЕНЬШЕЕ время
if i2 = -1 then
Exit(False);
// все точки имеют БОЛЬШЕЕ время
if i2 = 0 then
Exit(False);
// мы что-то нашли
Result := True;
// результат где-то между i1 и i2
i1 := i2 - 1;
if (aSeries.Stairs) or (aSeries.YValues[i1] = aSeries.YValues[i2]) then
aValue := aSeries.YValues[i1]
else
begin
// y = y2 - (y2-y1)*(x2-x)/(x2-x1)
aValue := aSeries.YValues[i2] - (aSeries.YValues[i2] - aSeries.YValues[i1])*
(aSeries.XValues[i2] - x)/(aSeries.XValues[i2] - aSeries.XValues[i1]);
end;
end;
function TDCCustomMessureTool.GetSeriesValueStr(aSeries: TFastLineSeries; x: Double): string;
var
v: Double;
begin
if not CalcSeriesValue(aSeries, x, v) then
Result := ''
else
Result := FormatFloat(Axis.AxisValuesFormat, v);
end;
procedure TDCCustomMessureTool.SetAxis(const Value: TChartAxis);
begin
FAxis := Value;
end;
procedure TaOPCMessureBandTool.ChartEvent(AEvent: TChartToolEvent);
begin
inherited;
case AEvent of
// cteBeforeDrawAxes: if DrawBehindAxes then PaintBand;
cteBeforeDrawSeries:
Band.ChartEvent(cteBeforeDrawSeries); // PaintBand;
cteAfterDraw:
DoDrawText;
// cteAfterDraw: if (not DrawBehind) and (not DrawBehindAxes) then PaintBand;
end;
end;
constructor TaOPCMessureBandTool.Create(AOwner: TComponent);
begin
inherited;
with Shape do
begin
Shadow.Size := 2;
Transparency := 0;
ShapeBounds.Left := 10;
ShapeBounds.Top := 10;
Width := 300;
Height := 40;
end;
FBand := NewBand;
FBand.StartLine.Pen.Width := 0;
FBand.EndLine.Pen.Width := 0;
end;
class function TaOPCMessureBandTool.Description: String;
begin
Result := TeeMsg_OPCMessureBandTool;
end;
destructor TaOPCMessureBandTool.Destroy;
begin
FreeAndNil(FBand);
inherited;
end;
procedure TaOPCMessureBandTool.DragLine(Sender: TColorLineTool);
begin
end;
procedure TaOPCMessureBandTool.DoDrawText(const AParent: TCustomAxisPanel);
var
tmpR: TRect;
tmpN, tmpX, tmpY: Integer;
begin
Shape.Text := ''; //GetText;
tmpR := GetTextBounds(tmpN, tmpX); // ,tmpY);
ShapeDrawText(ParentChart, tmpR, GetXOffset, tmpN);
end;
class function TaOPCMessureBandTool.LongDescription: String;
begin
Result := TeeMsg_OPCMessureBandToolDesc;
end;
function TaOPCMessureBandTool.NewBand: TaOPCMessureBand;
begin
Result := TaOPCMessureBand.Create(nil);
Result.Active := False;
Result.StartLine.DragRepaint := True;
// result.StartLine.OnDragLine := Self.DragLine;
Result.EndLine.DragRepaint := True;
// result.EndLine.OnDragLine := Self.DragLine;
end;
// procedure TaOPCMessureBandTool.PaintBand;
// begin
// if Assigned(Axis) then
// begin
// if FBand.Active then
// begin
/// / FLine.Value := StartValue;
// FBand.InternalDrawBand(False);
// end;
// end;
// end;
procedure TaOPCMessureBandTool.SetAxis(const Value: TChartAxis);
begin
FAxis := Value;
Band.Axis := Value;
end;
procedure TaOPCMessureBandTool.SetParentChart(const Value: TCustomAxisPanel);
begin
inherited;
if Assigned(FBand) then
FBand.ParentChart := Value;
end;
procedure TaOPCMessureBandTool.ShapeDrawText(Panel: TCustomAxisPanel; R: TRect;
XOffset, NumLines: Integer);
var
X: Integer;
t: Integer;
tmpTop: Integer;
tmpHeight: Integer;
saveColor: Integer;
vStr: string;
aText: string;
xLeft, xRight, xCenter: Integer;
v1, v2: Double;
aSeries: TaOPCLineSeries;
function TimeView(aTime: TDateTime): string;
begin
if aTime < 1 then
Result := FormatDateTime('HH:MM:SS', aTime)
else
Result := FormatFloat('# ##0.## д.', aTime);
end;
begin
OffsetRect(R, Panel.ChartBounds.Left, Panel.ChartBounds.Top);
if Shape.Visible then
{$IFDEF TEEVCL}
Shape.Draw(Panel, R);
{$ELSE}
Shape.DrawRectRotated(Panel, R);
{$ENDIF}
With Panel.Canvas do
begin
if Self.ClipText then
ClipRectangle(R);
try
BackMode := cbmTransparent;
xLeft := R.Left + Shape.Margins.Size.Left;
if Self.Pen.Visible then
Inc(xLeft, Self.Pen.Width);
xRight := R.Right - Shape.Margins.Size.Right;
xCenter := 1 + ((R.Left + Shape.Margins.Size.Left + R.Right - Shape.Margins.Size.Right) div 2);
AssignFont(Shape.Font);
tmpHeight := FontHeight;
tmpTop := R.Top + Shape.Margins.Size.Top;
if Axis.IsDateTime then
begin
TextAlign := TA_LEFT;
TextOut(xLeft + XOffset, tmpTop, FormatDateTime('dd.mm.yyyy HH:MM:SS', Band.StartValue), Shape.TextFormat = ttfHtml);
TextAlign := ta_Center;
TextOut(xCenter, tmpTop, TimeView(Band.EndValue - Band.StartValue), Shape.TextFormat = ttfHtml);
TextAlign := ta_Right;
TextOut(xRight, tmpTop, FormatDateTime('dd.mm.yyyy HH:MM:SS', Band.EndValue), Shape.TextFormat = ttfHtml);
end
else
begin
TextAlign := TA_LEFT;
TextOut(xLeft + XOffset, tmpTop, FormatFloat(Axis.AxisValuesFormat, Band.StartValue), Shape.TextFormat = ttfHtml);
TextAlign := ta_Center;
TextOut(xCenter, tmpTop, FormatFloat(Axis.AxisValuesFormat, Band.EndValue - Band.StartValue), Shape.TextFormat = ttfHtml);
TextAlign := ta_Right;
TextOut(xRight, tmpTop, FormatFloat(Axis.AxisValuesFormat, Band.EndValue), Shape.TextFormat = ttfHtml);
end;
// aText :=
// '<table>'+
// '<tr>'+
// '<td>'+FormatDateTime('dd.mm.yyyy HH:MM:SS', Band.StartValue)+'</td>'+
// '<td>'+FormatDateTime('dd.mm.yyyy HH:MM:SS', Band.StartValue)+'</td>'+
// '</tr>'+
// '</table>';
// TextOut( x+XOffset,
// tmpTop,
// aText,
// True);
saveColor := Font.Color;
var aLineCount: Integer := 1;
for t := 0 to ParentChart.SeriesCount - 1 do
begin
if not ParentChart.Series[t].Visible then
Continue;
if ParentChart.Series[t] is TaOPCLineSeries then
begin
aSeries := TaOPCLineSeries(ParentChart.Series[t]);
Font.Color := aSeries.Color;
// Font.Color := ParentChart.Series[t].Color;
vStr := aSeries.GetSerieValueStr(Band.StartValue);
TextAlign := TA_LEFT;
TextOut(xLeft + XOffset, tmpTop + aLineCount * tmpHeight, vStr,
Shape.TextFormat = ttfHtml);
vStr := aSeries.GetSerieValueStr(Band.EndValue);
TextAlign := ta_Right;
TextOut(xRight - XOffset, tmpTop + aLineCount * tmpHeight, vStr,
Shape.TextFormat = ttfHtml);
if aSeries.CalcSeriesValue(Band.StartValue, v1) and aSeries.CalcSeriesValue(Band.EndValue, v2) then
begin
vStr := FormatFloat(aSeries.DisplayFormat, v2 - v1);
TextAlign := ta_Center;
TextOut(xCenter, tmpTop + aLineCount * tmpHeight, vStr, Shape.TextFormat = ttfHtml);
end
end
else if ParentChart.Series[t] is TFastLineSeries then
begin
var s := TFastLineSeries(ParentChart.Series[t]);
Font.Color := s.Color;
// Font.Color := ParentChart.Series[t].Color;
vStr := GetSeriesValueStr(s, Band.StartValue);
TextAlign := TA_LEFT;
TextOut(xLeft + XOffset, tmpTop + aLineCount * tmpHeight, vStr, Shape.TextFormat = ttfHtml);
vStr := GetSeriesValueStr(s, Band.EndValue);
TextAlign := ta_Right;
TextOut(xRight - XOffset, tmpTop + aLineCount * tmpHeight, vStr, Shape.TextFormat = ttfHtml);
if CalcSeriesValue(s, Band.StartValue, v1) and CalcSeriesValue(s, Band.EndValue, v2) then
begin
vStr := FormatFloat(Axis.AxisValuesFormat, v2 - v1); // FloatToStr(v2 - v1); //FormatFloat(aSeries.DisplayFormat, v2 - v1);
TextAlign := ta_Center;
TextOut(xCenter, tmpTop + aLineCount * tmpHeight, vStr, Shape.TextFormat = ttfHtml);
end
end;
Inc(aLineCount);
end;
Font.Color := saveColor;
//if aLineCount * tmpHeight + 5 > Shape.Height then
Shape.Height := aLineCount * tmpHeight + 5;
finally
if Shape.ClipText then
UnClipRectangle;
end;
end;
end;
{ TaOPCMessureBand }
function TaOPCMessureBand.Chart: TCustomAxisPanel;
begin
Result := StartLine.ParentChart;
if not Assigned(Result) then
Result := ParentChart;
end;
procedure TaOPCMessureBand.ChartMouseEvent(AEvent: TChartMouseEvent;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
tmp: Integer;
tmpNew: Double;
tmpDoDraw: Boolean;
begin
// inherited;
// Exit;
if not IDragging then
begin
if StartLine.Active then
TaOPCMessureLine(StartLine).ChartMouseEvent(AEvent, Button, Shift, X, Y);
if EndLine.Active and (not ParentChart.CancelMouse) then
TaOPCMessureLine(EndLine).ChartMouseEvent(AEvent, Button, Shift, X, Y);
end;
if ParentChart.CancelMouse then
Exit;
tmpDoDraw := False;
if AllowDrag and Assigned(Axis) then
begin
case AEvent of
cmeUp:
if IDragging then // 7.0
begin
{ force repaint }
if not FDragRepaint then
Repaint;
{ call event }
// DoEndDragLine;
IDragging := False;
end;
cmeMove:
begin
if IDragging then
begin
if Axis.Horizontal then
tmp := X
else
tmp := Y;
{ calculate new position }
tmpNew := Axis.CalcPosPoint(tmp);
{ check inside axis limits }
if not NoLimitDrag then // (already implicit AllowDrag=True)
tmpNew := LimitValue(tmpNew);
tmpNew := tmpNew - FShift;
// if FDragRepaint then { 5.02 }
begin
// Value := tmpNew { force repaint whole chart }
EndValue := (tmpNew - StartValue) + EndValue;
StartValue := tmpNew;
end;
// else
// begin
//
// tmpDoDraw := CalcValue <> tmpNew;
//
// if tmpDoDraw then
// begin
// { draw line in xor mode, to avoid repaint the whole chart }
// with Chart.Canvas do
// begin
// AssignVisiblePen(Self.Pen);
// Pen.Mode := pmNotXor;
// end;
//
// { hide previous line }
// DrawColorLine(True);
// DrawColorLine(False);
//
// { set new value }
// FStyle := clCustom;
// FValue := tmpNew;
// end;
// end;
Chart.CancelMouse := True;
{ call event, allow event to change Value }
// if Assigned(FOnDragLine) then
// FOnDragLine(Self);
// if tmpDoDraw then { 5.02 }
// begin
// { draw at new position }
// DrawColorLine(True);
// DrawColorLine(False);
//
// { reset pen mode }
// Chart.Canvas.Pen.Mode := pmCopy;
// end;
end
else
begin
// is mouse on band?
if Clicked(X, Y) then
// or StartLine.Clicked(X, Y) or EndLine.Clicked(X, Y) then
begin
Chart.CancelMouse := (not ParentChart.Panning.Active) and
(not ParentChart.Zoom.Active);
if Chart.CancelMouse then
Chart.Cursor := crHandPoint;
end
// else if StartLine.Clicked(X, Y) or EndLine.Clicked(X, Y) then
// begin
// { show appropiate cursor }
// if Axis.Horizontal then
// Chart.Cursor:=crHSplit
// else
// Chart.Cursor:=crVSplit;
// Chart.CancelMouse:=True;
// //Chart.CancelMouse := (not ParentChart.IPanning.Active) and (not ParentChart.Zoom.Active);
// end;
end;
end;
cmeDown:
begin
if Button = mbLeft then
begin
{ is mouse over? }
IDragging := Clicked(X, Y);
Chart.CancelMouse := IDragging;
if Axis.Horizontal then
tmp := X
else
tmp := Y;
{ calculate new position }
FShift := Axis.CalcPosPoint(tmp) - StartValue;
// if IDragging and Assigned(FOnBeginDragLine) then // 7.0
// FOnBeginDragLine(Self);
end;
// if Assigned(FOnClick) and Clicked(X, Y) then
// FOnClick(Self, Button, Shift, X, Y);
end;
end;
end;
end;
function TaOPCMessureBand.Clicked(X, Y: Integer): Boolean;
var
R: TRect;
P: TFourPoints;
begin
// ParentChart.Canvas.FourPointsFromRect(BoundsRect,ZPosition,P);
// result:=PointInPolygon(TeePoint(X,Y),P);
R := BoundsRect;
InflateRect(R, -StartLine.Pen.Width, 0);
ParentChart.Canvas.FourPointsFromRect(R, ZPosition, P);
Result := PointInPolygon(TeePoint(X, Y), P);
end;
constructor TaOPCMessureBand.Create(AOwner: TComponent);
begin
inherited;
FAllowDrag := True;
FNoLimitDrag := False;
FDragRepaint := True;
end;
function TaOPCMessureBand.LimitValue(const AValue: Double): Double;
var
tmpLimit: Double;
tmpStart: Integer;
tmpEnd: Integer;
begin
Result := AValue;
tmpStart := Axis.IEndPos; // 6.01 Fix for Inverted axes
tmpEnd := Axis.IStartPos;
if Axis.Horizontal then
SwapInteger(tmpStart, tmpEnd);
if Axis.Inverted then
SwapInteger(tmpStart, tmpEnd);
// do not use Axis Minimum & Maximum, we need the "real" min and max
tmpLimit := Axis.CalcPosPoint(tmpStart);
if Result < tmpLimit then
Result := tmpLimit
else
begin
tmpLimit := Axis.CalcPosPoint(tmpEnd);
if Result > tmpLimit then
Result := tmpLimit;
end;
end;
end.
|
unit mainfrm;
////////////////////////////////////////////////////////////////////////////////
// *************************************************************
// Demo for IPWatch. Simple component determines Online status,
// returns current IP address, and keeps history on IP's issued.
// *************************************************************
// ..
// Author: Dave Nosker
// AfterWave Technologies
// (allbyte@jetlink.net)
// ..
// 5.20.99 First Version
// 5.22.99 Fixed Ip History not displaying Total on startup.
////////////////////////////////////////////////////////////////////////////////
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, ipwatchwinshoe, Buttons;
type
TMainForm = class(TForm)
WinshoeIPWatch1: TWinshoeIPWatch;
HistLb: TListBox;
HistoryPanel: TPanel;
ToolBarPanel: TPanel;
HideHistBtn: TSpeedButton;
ShowHistBtn: TSpeedButton;
MinimizeAppBtn: TSpeedButton;
StayOnTopBtn: TSpeedButton;
Label3: TLabel;
Label4: TLabel;
OnLineDisplay: TPanel;
IPDisplay: TPanel;
PrevIp: TPanel;
NumHist: TPanel;
procedure WinshoeIPWatch1StatusChanged(Sender: TObject);
procedure HistBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure StayOnTopBtnClick(Sender: TObject);
procedure MinimizeAppBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FHistoryShowing : Boolean;
procedure SetHeightLarge(DoLarge : Boolean);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
procedure TMainForm.SetHeightLarge(DoLarge : Boolean);
begin
if DoLarge then
ClientHeight := ToolBarPanel.Height + HistoryPanel.Height + 80
else
ClientHeight := ToolBarPanel.Height + HistoryPanel.Height + 2;
end;
procedure TMainForm.WinshoeIPWatch1StatusChanged(Sender: TObject);
begin
if WinshoeIPWatch1.IsOnline then
begin
OnLineDisplay.Font.Color := clLime;
OnLineDisplay.Caption := 'Online';
IPDisplay.Visible := true;
IPDisplay.Caption := WinshoeIPWatch1.CurrentIP;
Caption := WinshoeIPWatch1.CurrentIP;
end
else
begin
IPDisplay.Visible := false;
OnLineDisplay.Font.Color := clwhite;
OnLineDisplay.Caption := 'Offline';
Caption := 'Offline';
end;
Application.Title := Caption;
with WinshoeIPWatch1 do
begin
NumHist.Caption := IntToStr(IPHistoryList.count);
if PreviousIP <> '' then PrevIp.Caption := PreviousIP;
// Update HistLb to reflect items in history list...
if IPHistoryList.Count > 0 then
begin
HistLb.Clear;
HistLb.Items.Text := IPHistoryList.Text;
ShowHistBtn.Enabled := True;
end;
end;
end;
procedure TMainForm.HistBtnClick(Sender: TObject);
begin
if Sender = ShowHistBtn then
begin
if FHistoryShowing then Exit;
SetHeightLarge(True);
// Make sure bottom is completely visible...
if (Top + Height) > Screen.Height then
Top := Screen.Height - Height;
end
else
begin
if not FHistoryShowing then Exit;
SetHeightLarge(False);
end;
FHistoryShowing := not FHistoryShowing;
HistLb.Visible := not HistLb.Visible;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
SetHeightLarge(False);
FHistoryShowing := False;
Application.Title := 'IpWatchDemo';
HistLb.Items.Text := WinshoeIPWatch1.IPHistoryList.Text;
NumHist.Caption := IntToStr(WinshoeIPWatch1.IPHistoryList.count);
PrevIp.Caption := WinshoeIPWatch1.PreviousIP;
end;
procedure TMainForm.StayOnTopBtnClick(Sender: TObject);
begin
if StayOnTopBtn.Down then
FormStyle:= fsStayOnTop
else FormStyle:= fsNormal;
end;
procedure TMainForm.MinimizeAppBtnClick(Sender: TObject);
begin
Application.Minimize;
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
// Force the first showings position to Bottom
// left of the screen...
Top := Screen.Height - (Height+30);
Left := 20;
end;
end.
|
unit Calib;
{ ===================================================
CHART - Calibration wizard module
(c) J. Dempster, University of Strathclyde, 1996-98
===================================================
24/9/4 Calibration bug corrected }
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, ExtCtrls, SysUtils, Shared, use1902, ValEdit,
ValidatedEdit, dialogs ;
type
TCalibFrm = class(TForm)
Panel1: TPanel;
bBack: TButton;
bNext: TButton;
bFinish: TButton;
bCancel: TButton;
Panel2: TPanel;
Instructions: TMemo;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Timer1: TTimer;
cbChannels: TComboBox;
edCalibrationValue: TValidatedEdit;
edVoltageLevel: TValidatedEdit;
edUnits: TEdit;
Label4: TLabel;
procedure Timer1Timer(Sender: TObject);
procedure bNextClick(Sender: TObject);
procedure bBackClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure bFinishClick(Sender: TObject);
procedure bCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cbChannelsChange(Sender: TObject);
procedure edCalibrationValueKeyPress(Sender: TObject; var Key: Char);
procedure edUnitsKeyPress(Sender: TObject; var Key: Char);
procedure edUnitsChange(Sender: TObject);
private
{ Private declarations }
procedure SetCalibrationValue ;
public
{ Public declarations }
end;
var
CalibFrm: TCalibFrm;
implementation
uses Main;
{$R *.DFM}
type
TState = ( SelectChannel,
ApplyCalibration,
RemoveCalibration,
EnterCalibrationValue ) ;
var
State : TState ;
NewState : Boolean ;
// ChCal : Integer ;
iADC : Integer ;
V,VCal,VZero : Single ;
procedure TCalibFrm.FormActivate(Sender: TObject);
{ --------------------------------------
Initialisations when form is activated
--------------------------------------}
var
ch : Integer ;
begin
{ Fill channel selection list }
cbChannels.Clear ;
for ch := 0 to MainFrm.SESLabIO.ADCNumChannels-1 do
cbChannels.items.add( ' ' + MainFrm.SESLabIO.ADCChannelName[ch] ) ;
{ Start with channel 0 selected }
// ChCal := 0 ;
cbChannels.ItemIndex := 0 ;
SetCalibrationValue ;
Timer1.Enabled := True ;
{ Set CED 1902 settings }
if CED1902.InUse then CED1902.UpdateAmplifier ;
State := SelectChannel ;
bNext.Enabled := True ;
bBack.Enabled := False ;
bFinish.Enabled := False ;
NewState := True ;
end;
procedure TCalibFrm.SetCalibrationValue ;
// ---------------------
// Set calibration value
// ---------------------
begin
edCalibrationValue.Units := MainFrm.SESLabIO.ADCChannelUnits[cbChannels.ItemIndex] ;
edCalibrationValue.Value := Mainfrm.ADCCalibrationValue[cbChannels.ItemIndex] ;
edUnits.Text := MainFrm.SESLabIO.ADCChannelUnits[cbChannels.ItemIndex] ;
end ;
procedure TCalibFrm.Timer1Timer(Sender: TObject);
{ ---------------------
Timed event scheduler
---------------------}
begin
{ Read A/D channel }
iADC := Mainfrm.SESLabIO.ReadADC( cbChannels.ItemIndex ) ;
V := (iADC * MainFrm.SESLabIO.ADCChannelVoltageRange[cbChannels.ItemIndex])/
(Mainfrm.SESLabIO.ADCMaxValue*Mainfrm.SESLabIO.ADCChannelGain[cbChannels.ItemIndex]) ;
edVoltageLevel.Value := V ;
if NewState then begin
NewState := False ;
case State of
SelectChannel : Begin
if MainFrm.SESLabIO.ADCNumChannels > 1 then begin
Instructions.lines[0] := ' CALIBRATION STEP 1 of 4 ' ;
Instructions.lines[1] := ' Select the "Input Channel" to be calibrated. ' ;
Instructions.lines[2] := ' Then click the "Next" button to continue.' ;
Instructions.lines[3] := ' ' ;
Instructions.Lines[4] := ' ' ;
end
else begin
State := ApplyCalibration ;
NewState := True ;
end ;
end ;
ApplyCalibration : Begin
Instructions.lines[0] := ' CALIBRATION STEP 2 of 4 ' ;
Instructions.lines[1] := ' Apply a calibration weight to the transducer. ' ;
Instructions.Lines[2] := ' Wait till the Voltage Level reading settles down.' ;
Instructions.lines[3] := ' Then click the "Next" button to continue.' ;
Instructions.Lines[4] := ' ' ;
end ;
RemoveCalibration : Begin
Instructions.lines[0] := ' CALIBRATION STEP 3 of 4 ' ;
Instructions.lines[1] := ' Remove the calibration weight. ' ;
Instructions.Lines[2] := ' Wait till the Voltage Level reading settles down.' ;
Instructions.lines[3] := ' Then click the "Next" button to continue.' ;
Instructions.Lines[4] := ' ' ;
VCal := V ;
end ;
EnterCalibrationValue : Begin
Instructions.lines[0] := ' CALIBRATION STEP 4 of 4 ' ;
Instructions.lines[1] := ' Enter the value of the calibration weight into' ;
Instructions.lines[2] := ' the "Calibration Value" box.' ;
Instructions.lines[3] := ' Then click the "Finish" button to complete the' ;
Instructions.Lines[4] := ' calibration.' ;
VZero := V ;
{ Use this as the zero level }
Mainfrm.ADCChannelZero[cbChannels.ItemIndex] := iADC ;
end ;
end ;
end ;
end;
procedure TCalibFrm.bNextClick(Sender: TObject);
{ -----------------------------------------------
Move forward a stage in the calibration process
-----------------------------------------------}
begin
if State = SelectChannel then State := ApplyCalibration
else if State = ApplyCalibration then State := RemoveCalibration
else if State = RemoveCalibration then State := EnterCalibrationValue ;
if State = EnterCalibrationValue then begin
bNext.Enabled := False ;
bFinish.Enabled := True ;
end ;
bBack.enabled := True ;
NewState := True ;
end;
procedure TCalibFrm.bBackClick(Sender: TObject);
{ --------------------------------------------
Move back a stage in the calibration process
--------------------------------------------}
begin
if State = EnterCalibrationValue then State := RemoveCalibration
else if State = RemoveCalibration then State := ApplyCalibration
else if State = ApplyCalibration then State := SelectChannel ;
if State = SelectChannel then bBack.Enabled := False ;
bFinish.Enabled := False ;
bNext.Enabled := True ;
NewState := True ;
end;
procedure TCalibFrm.bFinishClick(Sender: TObject);
{ ------------------------------
Finish the calibration process
------------------------------}
var
VDiff,OldFactor : Single ;
ADCScaleTo16Bit : Integer ;
begin
ADCScaleTo16Bit := (MainFrm.ADCMaxValue+1) div MainFrm.SESLabIO.ADCMaxValue ;
Mainfrm.ADCCalibrationValue[cbChannels.ItemIndex] := edCalibrationValue.Value ;
MainFrm.SESLabIO.ADCChannelUnits[cbChannels.ItemIndex] := edUnits.Text ;
VDiff := VCal - VZero ;
OldFactor := Mainfrm.ADCChannelVoltsPerUnit[cbChannels.ItemIndex] ;
try
Mainfrm.SESLabIO.ADCChannelVoltsPerUnit[cbChannels.ItemIndex] := (VDiff/Mainfrm.ADCCalibrationValue[cbChannels.ItemIndex])
*ADCScaleTo16Bit ;
except
on EZeroDivide do begin
ShowMessage('Calibration step too small! Reverting to old value.');
Mainfrm.ADCChannelVoltsPerUnit[cbChannels.ItemIndex] := OldFactor ;
end ;
on EInvalidOp do begin
Mainfrm.ADCChannelVoltsPerUnit[cbChannels.ItemIndex] := OldFactor ;
ShowMessage('Calibration step too small! Reverting to old value.');
end ;
end ;
Timer1.Enabled := False ;
end;
procedure TCalibFrm.bCancelClick(Sender: TObject);
begin
Timer1.Enabled := False ;
end;
procedure TCalibFrm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Timer1.Enabled := False ;
end;
procedure TCalibFrm.cbChannelsChange(Sender: TObject);
begin
SetCalibrationValue ;
end;
procedure TCalibFrm.edCalibrationValueKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Mainfrm.ADCCalibrationValue[cbChannels.ItemIndex] := edCalibrationValue.Value ;
SetCalibrationValue ;
end ;
end;
procedure TCalibFrm.edUnitsKeyPress(Sender: TObject; var Key: Char);
begin
edCalibrationValue.Units := edUnits.Text ;
end;
procedure TCalibFrm.edUnitsChange(Sender: TObject);
begin
edCalibrationValue.Units := edUnits.Text ;
MainFrm.SESLabIO.ADCChannelUnits[cbChannels.ItemIndex] := edUnits.Text ;
end;
end.
|
unit Core.Observable;
interface
uses
System.SysUtils
, System.Classes
, System.Rtti
{Spring}
, Spring
, Spring.DesignPatterns
, Spring.Collections
, Generics.Collections
{BowlingGame}
, Core.BaseInterfaces
;
type
TGameObserver = class(TInterfacedObject, IGameObserver)
public
procedure Update(const AData: TValue); virtual; abstract;
end;
TGameObservable = class(TObservable<IGameObserver>)
strict private
FGameData: TValue;
protected
procedure DoNotify(const AObserver: IGameObserver); override;
public
procedure UpdateView(const AGameData: TValue);
end;
implementation
{ TGameObservable }
procedure TGameObservable.DoNotify(const AObserver: IGameObserver);
begin
inherited;
AObserver.Update(FGameData);
end;
procedure TGameObservable.UpdateView(const AGameData: TValue);
begin
FGameData := AGameData;
Notify;
end;
end.
|
unit UFormSelectLocalDes;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, siComp, UMainForm;
type
TfrmSelectLocalDes = class(TForm)
LvDestination: TListView;
Panel1: TPanel;
btnOK: TButton;
btnCancel: TButton;
Panel2: TPanel;
Label1: TLabel;
edtBackupSource: TEdit;
siLang_frmSelectLocalDes: TsiLang;
procedure btnOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure siLang_frmSelectLocalDesChangeLanguage(Sender: TObject);
public
procedure SetLocalSource( SourcePath : string );
procedure SetBackupItem( DesPathList : TStringList );
function getSelectItems : TStringList;
end;
var
frmSelectLocalDes: TfrmSelectLocalDes;
implementation
uses UIconUtil;
{$R *.dfm}
procedure TfrmSelectLocalDes.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmSelectLocalDes.btnOKClick(Sender: TObject);
begin
Close;
ModalResult := mrOk;
end;
procedure TfrmSelectLocalDes.FormCreate(Sender: TObject);
begin
LvDestination.SmallImages := MyIcon.getSysIcon;
siLang_frmSelectLocalDesChangeLanguage( nil );
end;
procedure TfrmSelectLocalDes.FormShow(Sender: TObject);
begin
ModalResult := mrCancel;
end;
function TfrmSelectLocalDes.getSelectItems: TStringList;
var
i : Integer;
begin
Result := TStringList.Create;
for i := 0 to LvDestination.Items.Count - 1 do
if LvDestination.Items[i].Checked then
Result.Add( LvDestination.Items[i].Caption );
end;
procedure TfrmSelectLocalDes.SetBackupItem(DesPathList: TStringList);
var
i : Integer;
DesPath : string;
begin
LvDestination.Clear;
for i := 0 to DesPathList.Count - 1 do
begin
DesPath := DesPathList[i];
with LvDestination.Items.Add do
begin
Caption := DesPath;
ImageIndex := MyIcon.getIconByFilePath( DesPath );
Checked := True;
end;
end;
end;
procedure TfrmSelectLocalDes.SetLocalSource(SourcePath: string);
begin
edtBackupSource.Text := SourcePath;
end;
procedure TfrmSelectLocalDes.siLang_frmSelectLocalDesChangeLanguage(
Sender: TObject);
begin
LvDestination.Columns[0].Caption := siLang_frmSelectLocalDes.GetText( 'lvDestination' );
end;
end.
|
{@unit RLConsts - Variáveis de internacionalização e variáveis de configuração. }
unit RLConsts;
interface
uses
SysUtils;
const
CommercialVersion = 4;
ReleaseVersion = 0;
CommentVersion = '0';
const
{@const ScreenPPI - Resolução do monitor em pixels por polegada.
Representa a quantidade de pixels por polegada do vídeo. O valor real varia de monitor para monitor mas,
para facilitar cálculos e tornar os projetos independentes do terminal, essa valor é assumido como sendo 96. :/}
ScreenPPI=96;
{@const InchAsMM - Fator de conversão de polegada para milímetros.
Este fator é utilizado em diversos pontos para conversões de coordenadas. :/}
InchAsMM=254/10;
{@const MMAsPixels - Fator de conversão de milímetros para pixels de tela.
@links ScreenPPI, InchAsMM. :/}
MMAsPixels=ScreenPPI/InchAsMM;
const
CS_CopyrightStr = 'Copyright © 1999-2004 Fortes Informática';
CS_ProductTitleStr = 'FortesReport';
CS_URLStr = 'http://www.fortesreport.com.br';
CS_AuthorNameStr = 'Ronaldo Moreira';
var
{@var LS_PrintingInProgressStr - Variável de internacionalização para "Imprimindo o relatório..." :/}
LS_PrintingInProgressStr:string;
{@var LS_FilterInProgressStr - Variável de internacionalização para "Salvando o relatório..." :/}
LS_FilterInProgressStr :string;
{@var LS_PreparingReportStr - Variável de internacionalização para "Preparando o relatório..." :/}
LS_PreparingReportStr :string;
{@var LS_PrinterNotFoundStr - Variável de internacionalização para "Nenhuma impressora encontrada" :/}
LS_PrinterNotFoundStr :string;
{@var LS_NoPathToPrinterStr - Variável de internacionalização para "Caminho inválido para a impressora" :/}
LS_NoPathToPrinterStr :string;
{@var LS_LoadDefaultConfigStr - Variável de internacionalização para "Será carregada a configuração padrão" :/}
LS_LoadDefaultConfigStr :string;
{@var LS_PrinterDriverErrorStr - Variável de internacionalização para "Erro no driver da impressora" :/}
LS_PrinterDriverErrorStr:string;
{@var LS_PageStr - Variável de internacionalização para "Página" :/}
LS_PageStr :string;
{@var LS_PrepareErrorStr - Variável de internacionalização para "Erro durante a preparação do relatório" :/}
LS_PrepareErrorStr :string;
{@var LS_PageBreakStr - Variável de internacionalização para "Continua..." :/}
LS_PageBreakStr :string;
{@var LS_PageMendStr - Variável de internacionalização para "Continuação" :/}
LS_PageMendStr :string;
{@var LS_ReportEndStr - Variável de internacionalização para "Fim" :/}
LS_ReportEndStr :string;
{@var LS_FileNotFoundStr - Variável de internacionalização para "Arquivo não encontrado" :/}
LS_FileNotFoundStr :string;
{@var LS_FileNameStr - Variável de internacionalização para "Nome do arquivo" :/}
LS_FileNameStr :string;
{@var LS_AllFileTypesStr - Variável de internacionalização para "Todos os arquivos" :/}
LS_AllFileTypesStr :string;
{@var LS_LoadReportStr - Variável de internacionalização para "Carregar relatório" :/}
LS_LoadReportStr :string;
{@var LS_NotFoundStr - Variável de internacionalização para "Não encontrado" :/}
LS_NotFoundStr :string;
{@var LS_WaitStr - Variável de internacionalização para "Aguarde..." :/}
LS_WaitStr :string;
{@var LS_FinishedStr - Variável de internacionalização para "Concluído" :/}
LS_FinishedStr :string;
{@var LS_CancelStr - Variável de internacionalização para "Cancelar" :/}
LS_CancelStr :string;
{@var LS_CloseStr - Variável de internacionalização para "Fechar" :/}
LS_CloseStr :string;
{@var LS_SaveStr - Variável de internacionalização para "Salvar" :/}
LS_SaveStr :string;
{@var LS_SendStr - Variável de internacionalização para "Enviar" :/}
LS_SendStr :string;
{@var LS_PrintStr - Variável de internacionalização para "Imprimir" :/}
LS_PrintStr :string;
{@var LS_AboutTheStr - Variável de internacionalização para "Sobre o" :/}
LS_AboutTheStr :string;
{@var LS_PreviewStr - Variável de internacionalização para "Pré-visualização" :/}
LS_PreviewStr :string;
{@var LS_OfStr - Variável de internacionalização para "de" :/}
LS_OfStr :string;
{@var LS_ZoomStr - Variável de internacionalização para "Zoom" :/}
LS_ZoomStr :string;
{@var LS_FirstPageStr - Variável de internacionalização para "Primeira página" :/}
LS_FirstPageStr :string;
{@var LS_PriorPageStr - Variável de internacionalização para "Página anterior" :/}
LS_PriorPageStr :string;
{@var LS_NextPageStr - Variável de internacionalização para "Próxima página" :/}
LS_NextPageStr :string;
{@var LS_LastPageStr - Variável de internacionalização para "Última página" :/}
LS_LastPageStr :string;
{@var LS_EntirePageStr - Variável de internacionalização para "Página inteira" :/}
LS_EntirePageStr :string;
{@var LS_EntireWidthStr - Variável de internacionalização para "Largura da página" :/}
LS_EntireWidthStr :string;
{@var LS_MultiplePagesStr - Variável de internacionalização para "Várias páginas" :/}
LS_MultiplePagesStr :string;
{@var LS_ConfigPrinterStr - Variável de internacionalização para "Configurar impressora" :/}
LS_ConfigPrinterStr :string;
{@var LS_SaveToFileStr - Variável de internacionalização para "Salvar em disco" :/}
LS_SaveToFileStr :string;
{@var LS_SendToStr - Variável de internacionalização para "Enviar para" :/}
LS_SendToStr :string;
{@var LS_PrinterStr - Variável de internacionalização para "Impressora" :/}
LS_PrinterStr :string;
{@var LS_NameStr - Variável de internacionalização para "Nome" :/}
LS_NameStr :string;
{@var LS_PrintToFileStr - Variável de internacionalização para "Imprimir em arquivo" :/}
LS_PrintToFileStr :string;
{@var LS_PrintInBackgroundStr - Variável de internacionalização para "Imprimir em segundo plano" :/}
LS_PrintInBackgroundStr :string;
{@var LS_SaveInBackground - Variável de internacionalização para "Salvar em segundo plano" :/}
LS_SaveInBackground :string;
{@var LS_PageRangeStr - Variável de internacionalização para "Intervalo de páginas" :/}
LS_PageRangeStr :string;
{@var LS_RangeFromStr - Variável de internacionalização para "de" :/}
LS_RangeFromStr :string;
{@var LS_RangeToStr - Variável de internacionalização para "até" :/}
LS_RangeToStr :string;
{@var LS_AllStr - Variável de internacionalização para "Tudo" :/}
LS_AllStr :string;
{@var LS_PagesStr - Variável de internacionalização para "Páginas" :/}
LS_PagesStr :string;
{@var LS_SelectionStr - Variável de internacionalização para "Seleção" :/}
LS_SelectionStr :string;
{@var LS_CopiesStr - Variável de internacionalização para "Cópias" :/}
LS_CopiesStr :string;
{@var LS_NumberOfCopiesStr - Variável de internacionalização para "Número de cópias" :/}
LS_NumberOfCopiesStr :string;
{@var LS_OkStr - Variável de internacionalização para "Ok" :/}
LS_OkStr :string;
{@var LS_DivideScreenStr - Variável de internacionalização para "Dividir a tela" :/}
LS_DivideScreenStr :string;
{@var LS_InvalidNameStr - Variável de internacionalização para "Nome inválido" :/}
LS_InvalidNameStr :string;
{@var LS_DuplicateNameStr - Variável de internacionalização para "Nome já utilizado" :/}
LS_DuplicateNameStr :string;
{@var LS_UseFilterStr - Variável de internacionalização para "Usar Filtro" :/}
LS_UseFilterStr :string;
{@var LS_WebPageStr - Variável de internacionalização para "Página da Web" :/}
LS_WebPageStr :string;
{@var LS_RichFormatStr - Variável de internacionalização para "Formato RichText" :/}
LS_RichFormatStr :string;
{@var LS_PDFFormatStr - Variável de internacionalização para "Documento PDF" :/}
LS_PDFFormatStr :string;
{@var LS_XLSFormatStr - Variável de internacionalização para "Planilha Excel" :/}
LS_XLSFormatStr :string;
{@var LS_AtStr - Variável de internacionalização para "em" :/}
LS_AtStr :string;
{@var LS_FormStr - Variável de internacionalização para "Formulário" :/}
LS_FormStr :string;
{@var LS_DefaultStr - Variável de internacionalização para "Padrão" :/}
LS_DefaultStr :string;
{@var LS_ColsStr - Variável de internacionalização para "cols" :/}
LS_ColsStr :string;
{@var LS_ZoomInStr - Variável de internacionalização para "Aumentar o zoom" :/}
LS_ZoomInStr :string;
{@var LS_ZoomOutStr - Variável de internacionalização para "Diminuir o zoom" :/}
LS_ZoomOutStr :string;
{@var LS_CopyStr - Variável de internacionalização para "Copiar" :/}
LS_CopyStr :string;
{@var LS_EditStr - Variável de internacionalização para "Editar" :/}
LS_EditStr :string;
{@var LS_FindCaptionStr - Variável de internacionalização para "Procurar" :/}
LS_FindCaptionStr :string;
{@var LS_TextToFindStr - Variável de internacionalização para "Te&xto" :/}
LS_TextToFindStr :string;
{@var LS_FindNextStr - &Variável de internacionalização para "Próxima" :/}
LS_FindNextStr :string;
{@var LS_WholeWordsStr - Variável de internacionalização para "Palavras &inteiras" :/}
LS_WholeWordsStr :string;
{@var LS_MatchCaseStr - Variável de internacionalização para "Diferenciar &maiúsculas de minúsculas" :/}
LS_MatchCaseStr :string;
{@var LS_DirectionUpStr - Variável de internacionalização para "A&cima" :/}
LS_DirectionUpStr :string;
{@var LS_DirectionDownStr - Variável de internacionalização para "A&baixo" :/}
LS_DirectionDownStr :string;
{@var LS_DirectionCaptionStr - Variável de internacionalização para "Direção" :/}
LS_DirectionCaptionStr :string;
const
RLFILEEXT='.rpf';
procedure DetectLocale;
procedure LoadPortugueseStrings;
procedure LoadEnglishStrings;
procedure LoadFrenchStrings;
procedure LoadSpanishStrings;
{/@unit}
implementation
procedure LoadPortugueseStrings;
begin
LS_PrintingInProgressStr:='Imprimindo o relatório...';
LS_FilterInProgressStr :='Salvando o relatório...';
LS_PreparingReportStr :='Preparando o relatório...';
LS_PrinterNotFoundStr :='Nenhuma impressora encontrada';
LS_NoPathToPrinterStr :='Caminho inválido para a impressora';
LS_LoadDefaultConfigStr :='Será carregada a configuração padrão';
LS_PrinterDriverErrorStr:='Erro no driver da impressora';
LS_PageStr :='Página';
LS_PrepareErrorStr :='Erro durante a preparação do relatório';
LS_PageBreakStr :='Continua...';
LS_PageMendStr :='Continuação';
LS_ReportEndStr :='Fim';
LS_FileNotFoundStr :='Arquivo não encontrado';
LS_FileNameStr :='Nome do arquivo';
LS_AllFileTypesStr :='Todos os arquivos';
LS_LoadReportStr :='Carregar relatório';
LS_NotFoundStr :='Não encontrado';
LS_WaitStr :='Aguarde...';
LS_FinishedStr :='Concluído';
LS_CancelStr :='Cancelar';
LS_CloseStr :='Fechar';
LS_SaveStr :='Salvar';
LS_SendStr :='Enviar';
LS_PrintStr :='Imprimir';
LS_AboutTheStr :='Sobre o';
LS_PreviewStr :='Pré-visualização';
LS_OfStr :='de';
LS_ZoomStr :='Zoom';
LS_FirstPageStr :='Primeira página';
LS_PriorPageStr :='Página anterior';
LS_NextPageStr :='Próxima página';
LS_LastPageStr :='Última página';
LS_EntirePageStr :='Página inteira';
LS_EntireWidthStr :='Largura da página';
LS_MultiplePagesStr :='Várias páginas';
LS_ConfigPrinterStr :='Configurar impressora';
LS_SaveToFileStr :='Salvar em disco';
LS_SendToStr :='Enviar para';
LS_PrinterStr :='Impressora';
LS_NameStr :='Nome';
LS_PrintToFileStr :='Imprimir em arquivo';
LS_PrintInBackgroundStr :='Imprimir em segundo plano';
LS_SaveInBackground :='Salvar em segundo plano';
LS_PageRangeStr :='Intervalo de páginas';
LS_RangeFromStr :='de';
LS_RangeToStr :='até';
LS_AllStr :='Tudo';
LS_PagesStr :='Páginas';
LS_SelectionStr :='Seleção';
LS_CopiesStr :='Cópias';
LS_NumberOfCopiesStr :='Número de cópias';
LS_OkStr :='Ok';
LS_DivideScreenStr :='Dividir a tela';
LS_InvalidNameStr :='Nome inválido';
LS_DuplicateNameStr :='Nome já utilizado';
LS_UseFilterStr :='Usar Filtro';
LS_WebPageStr :='Página da Web';
LS_RichFormatStr :='Formato RichText';
LS_PDFFormatStr :='Documento PDF';
LS_XLSFormatStr :='Planilha Excel';
LS_AtStr :='em';
LS_FormStr :='Formulário';
LS_DefaultStr :='Padrão';
LS_ColsStr :='cols';
LS_ZoomInStr :='Aumentar o zoom';
LS_ZoomOutStr :='Diminuir o zoom';
LS_CopyStr :='Copiar';
LS_EditStr :='Editar';
LS_FindCaptionStr :='Procurar';
LS_TextToFindStr :='Te&xto';
LS_FindNextStr :='&Próxima';
LS_WholeWordsStr :='Palavras &inteiras';
LS_MatchCaseStr :='Diferenciar &maiúsculas de minúsculas';
LS_DirectionUpStr :='A&cima';
LS_DirectionDownStr :='A&baixo';
LS_DirectionCaptionStr :='Direção';
end;
procedure LoadEnglishStrings;
begin
LS_PrintingInProgressStr:='Printing in progress...';
LS_FilterInProgressStr :='Saving report...';
LS_PreparingReportStr :='Preparing report...';
LS_PrinterNotFoundStr :='Printer not found';
LS_NoPathToPrinterStr :='Invalid printer path';
LS_LoadDefaultConfigStr :='Load default configuration';
LS_PrinterDriverErrorStr:='Printer driver error';
LS_PageStr :='Page';
LS_PrepareErrorStr :='Error while preparing report';
LS_PageBreakStr :='Continues...';
LS_PageMendStr :='Continuation';
LS_ReportEndStr :='End';
LS_FileNotFoundStr :='File not found';
LS_FileNameStr :='File Name';
LS_AllFileTypesStr :='All files';
LS_LoadReportStr :='Load report';
LS_NotFoundStr :='Not found';
LS_WaitStr :='Wait...';
LS_FinishedStr :='Finished';
LS_CancelStr :='Cancel';
LS_CloseStr :='Close';
LS_SaveStr :='Save';
LS_SendStr :='Send';
LS_PrintStr :='Print';
LS_AboutTheStr :='About';
LS_PreviewStr :='Preview';
LS_OfStr :='of';
LS_ZoomStr :='Zoom';
LS_FirstPageStr :='First page';
LS_PriorPageStr :='Prior page';
LS_NextPageStr :='Next page';
LS_LastPageStr :='Last page';
LS_EntirePageStr :='Entire page';
LS_EntireWidthStr :='Entire width';
LS_MultiplePagesStr :='Multiple pages';
LS_ConfigPrinterStr :='Configure printer';
LS_SaveToFileStr :='Save to file';
LS_SendToStr :='Send to';
LS_PrinterStr :='Printer';
LS_NameStr :='Name';
LS_PrintToFileStr :='Print to file';
LS_PrintInBackgroundStr :='Print in background';
LS_SaveInBackground :='Save in background';
LS_PageRangeStr :='Page range';
LS_RangeFromStr :='from';
LS_RangeToStr :='to';
LS_AllStr :='All';
LS_PagesStr :='Pages';
LS_SelectionStr :='Selection';
LS_CopiesStr :='Copies';
LS_NumberOfCopiesStr :='Number of copies';
LS_OkStr :='Ok';
LS_DivideScreenStr :='Divide the screen';
LS_InvalidNameStr :='Invalid name';
LS_DuplicateNameStr :='Name already in use';
LS_UseFilterStr :='Use filter';
LS_WebPageStr :='Web page';
LS_RichFormatStr :='RichText Format';
LS_PDFFormatStr :='PDF Document';
LS_XLSFormatStr :='Excel spreadsheet';
LS_AtStr :='at';
LS_FormStr :='Form';
LS_DefaultStr :='Default';
LS_ColsStr :='cols';
LS_ZoomInStr :='Increase zoom';
LS_ZoomOutStr :='Decrease zoom';
LS_CopyStr :='Copy';
LS_EditStr :='Edit';
LS_FindCaptionStr :='Find';
LS_TextToFindStr :='Te&xt';
LS_FindNextStr :='Find &Next';
LS_WholeWordsStr :='&Whole words only';
LS_MatchCaseStr :='&Match Case';
LS_DirectionUpStr :='&Up';
LS_DirectionDownStr :='&Down';
LS_DirectionCaptionStr :='Direction';
end;
procedure LoadFrenchStrings;
begin
LS_PrintingInProgressStr:='Impression du rapport...';
LS_FilterInProgressStr :='Sauver le rapport...';
LS_PreparingReportStr :='Préparation du rapport...';
LS_PrinterNotFoundStr :='Imprimante non trouvée';
LS_NoPathToPrinterStr :='Invalid printer path';
LS_LoadDefaultConfigStr :='Chargement de la configuration standard';
LS_PrinterDriverErrorStr:='Erreur dans le driver d''impression';
LS_PageStr :='Page';
LS_PrepareErrorStr :='Erreur durant la prépartaion du rapport';
LS_PageBreakStr :='Saut de page...';
LS_PageMendStr :='A suivre';
LS_ReportEndStr :='Fin';
LS_FileNotFoundStr :='Fichier non trouvé';
LS_FileNameStr :='Nom de Fichier';
LS_AllFileTypesStr :='Tous les fichiers';
LS_LoadReportStr :='Ouvrir rapport';
LS_NotFoundStr :='Non trouvé';
LS_WaitStr :='Patientez...';
LS_FinishedStr :='Fini';
LS_CancelStr :='Annulé';
LS_CloseStr :='Fermé';
LS_SaveStr :='Sauver';
LS_SendStr :='Envoyez';
LS_PrintStr :='Imprimer';
LS_AboutTheStr :='A propos de';
LS_PreviewStr :='Aperçu avant impression';
LS_OfStr :='de';
LS_ZoomStr :='Zoom';
LS_FirstPageStr :='Première page';
LS_PriorPageStr :='Page précédente';
LS_NextPageStr :='Page suivante';
LS_LastPageStr :='Dernière page';
LS_EntirePageStr :='Page entière';
LS_EntireWidthStr :='Pleine largeur';
LS_MultiplePagesStr :='Plusieurs pages';
LS_ConfigPrinterStr :='Configuration de l''imprimante';
LS_SaveToFileStr :='Enregistrer sous';
LS_SendToStr :='Envoyez à';
LS_PrinterStr :='Imprimante';
LS_NameStr :='Nom';
LS_PrintToFileStr :='Imprimer dans un fichier';
LS_PrintInBackgroundStr :='Imprimer dans background';
LS_SaveInBackground :='Enregistrer dans background';
LS_PageRangeStr :='Intervalle de pages';
LS_RangeFromStr :='de';
LS_RangeToStr :='à';
LS_AllStr :='Tout';
LS_PagesStr :='Pages';
LS_SelectionStr :='Sélection';
LS_CopiesStr :='Copies';
LS_NumberOfCopiesStr :='Nombre de copies';
LS_OkStr :='Ok';
LS_DivideScreenStr :='Dividir a tela';
LS_InvalidNameStr :='Nom inadmissible';
LS_DuplicateNameStr :='Nom reproduit';
LS_UseFilterStr :='Use filter';
LS_WebPageStr :='Page de Web';
LS_RichFormatStr :='Formato RichText';
LS_PDFFormatStr :='Documento PDF';
LS_XLSFormatStr :='Excel tableur';
LS_AtStr :='à';
LS_FormStr :='Formulaire';
LS_DefaultStr :='Défaut';
LS_ColsStr :='cols';
LS_ZoomInStr :='Grandir zoom';
LS_ZoomOutStr :='Réduire zoom';
LS_CopyStr :='Copier';
LS_EditStr :='Edit';
LS_FindCaptionStr :='Trouvaille';
LS_TextToFindStr :='Te&xte';
LS_FindNextStr :='A&près';
LS_WholeWordsStr :='Mots &entiers seulement';
LS_MatchCaseStr :='Cas d''allu&mette';
LS_DirectionUpStr :='Le &Haut';
LS_DirectionDownStr :='Le &bas';
LS_DirectionCaptionStr :='Direction';
end;
procedure LoadSpanishStrings;
begin
LS_PrintingInProgressStr:='Impresión en marcha...';
LS_FilterInProgressStr :='Guardando el informe...';
LS_PreparingReportStr :='Preparación del informe...';
LS_PrinterNotFoundStr :='Impresora no encontrada';
LS_NoPathToPrinterStr :='Caminho inválido para a impressora';
LS_LoadDefaultConfigStr :='Cargar la configuración estándar';
LS_PrinterDriverErrorStr:='Error en driver de la impresora';
LS_PageStr :='Página';
LS_PrepareErrorStr :='Un error ocurrió mientras se preparaba el informe';
LS_PageBreakStr :='Continúa...';
LS_PageMendStr :='Continuación';
LS_ReportEndStr :='Extremo';
LS_FileNotFoundStr :='Archivo no encontrado';
LS_FileNameStr :='Nombre del Archivo';
LS_AllFileTypesStr :='Todos los archivos';
LS_LoadReportStr :='Cargar el informe';
LS_NotFoundStr :='No encontrado';
LS_WaitStr :='Espera...';
LS_FinishedStr :='Finalizado';
LS_CancelStr :='Cancelar';
LS_CloseStr :='Cerrar';
LS_SaveStr :='Guardar';
LS_SendStr :='Enviar';
LS_PrintStr :='Imprimir';
LS_AboutTheStr :='Sobre';
LS_PreviewStr :='Ver';
LS_OfStr :='de';
LS_ZoomStr :='Zoom';
LS_FirstPageStr :='Primera página';
LS_PriorPageStr :='Página anterior';
LS_NextPageStr :='Página siguiente';
LS_LastPageStr :='Última página';
LS_EntirePageStr :='Página entera';
LS_EntireWidthStr :='Ancho completo';
LS_MultiplePagesStr :='Varias páginas';
LS_ConfigPrinterStr :='Configurar la impresora';
LS_SaveToFileStr :='Guardar en un archivo';
LS_SendToStr :='Envíar a';
LS_PrinterStr :='Impresora';
LS_NameStr :='Nombre';
LS_PrintToFileStr :='Imprimir a un archivo';
LS_PrintInBackgroundStr :='Imprimir en background';
LS_SaveInBackground :='Guardar en background';
LS_PageRangeStr :='Intervalo de páginas';
LS_RangeFromStr :='de';
LS_RangeToStr :='a';
LS_AllStr :='Todas';
LS_PagesStr :='Páginas';
LS_SelectionStr :='Selección';
LS_CopiesStr :='Copias';
LS_NumberOfCopiesStr :='Número de copias';
LS_OkStr :='Ok';
LS_DivideScreenStr :='Dividir la pantalla';
LS_InvalidNameStr :='Nombre inválido';
LS_DuplicateNameStr :='Nombre ya en uso';
LS_UseFilterStr :='Usar Filtro';
LS_WebPageStr :='Página Web';
LS_RichFormatStr :='Formato RichText';
LS_PDFFormatStr :='Documento PDF';
LS_XLSFormatStr :='Planilha Excel';
LS_AtStr :='en';
LS_FormStr :='Formulario';
LS_DefaultStr :='Estándar';
LS_ColsStr :='cols';
LS_ZoomInStr :='Aumentar zoom';
LS_ZoomOutStr :='Disminuir zoom';
LS_CopyStr :='Copiar';
LS_EditStr :='Editar';
LS_FindCaptionStr :='Buscar';
LS_TextToFindStr :='Te&xto';
LS_FindNextStr :='&Siguiente';
LS_WholeWordsStr :='Palabras &completas sólamente';
LS_MatchCaseStr :='Diferenciar &mayúsculas y minúsculas';
LS_DirectionUpStr :='En&cima';
LS_DirectionDownStr :='&Abajo';
LS_DirectionCaptionStr :='Dirección';
end;
procedure DetectLocale;
{$ifdef LINUX}
var
dlct:string;
{$endif}
begin
{$ifdef LINUX}
dlct:=AnsiUpperCase(Copy(GetEnvironmentVariable('LANG'),1,2));
if dlct='PT' then
LoadPortugueseStrings
else if dlct='EN' then
LoadEnglishStrings
else if dlct='ES' then
LoadSpanishStrings
else if dlct='FR' then
LoadFrenchStrings
else
LoadEnglishStrings;
{$else}
case SysLocale.PriLangID of
$16 {LANG_PORTUGUESE}: LoadPortugueseStrings;
$09 {LANG_ENGLISH} : LoadEnglishStrings;
$0a {LANG_SPANISH} : LoadSpanishStrings;
$0c {LANG_FRENCH} : LoadFrenchStrings;
else
LoadEnglishStrings;
end;
{$endif}
end;
initialization
DetectLocale;
end.
|
unit U_TIPO;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, DBGrids, ExtCtrls, DBCtrls, StdCtrls, Mask, Buttons, db, dbtables;
type
TFRM_TIPO = class(TForm)
Label1: TLabel;
DBEdit1: TDBEdit;
Label2: TLabel;
DBEdit2: TDBEdit;
DBGrid1: TDBGrid;
Panel1: TPanel;
Spprimeiro: TSpeedButton;
SpAnterior: TSpeedButton;
SpProximo: TSpeedButton;
SpUltimo: TSpeedButton;
SpInserir: TSpeedButton;
Spdeletar: TSpeedButton;
Speditar: TSpeedButton;
SpGravar: TSpeedButton;
SpCancelar: TSpeedButton;
SpSair: TSpeedButton;
procedure SpprimeiroClick(Sender: TObject);
procedure SpAnteriorClick(Sender: TObject);
procedure SpProximoClick(Sender: TObject);
procedure SpUltimoClick(Sender: TObject);
procedure SpSairClick(Sender: TObject);
procedure validanavegacao;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure validainsercaodados;
procedure SpInserirClick(Sender: TObject);
procedure SpdeletarClick(Sender: TObject);
procedure SpeditarClick(Sender: TObject);
procedure SpGravarClick(Sender: TObject);
procedure SpCancelarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FRM_TIPO: TFRM_TIPO;
implementation
uses U_DM;
{$R *.DFM}
procedure TFRM_TIPO.SpprimeiroClick(Sender: TObject);
begin
dm.q_tipo.First;
validanavegacao;
end;
procedure TFRM_TIPO.SpAnteriorClick(Sender: TObject);
begin
dm.q_tipo.Prior;
validanavegacao;
end;
procedure TFRM_TIPO.SpProximoClick(Sender: TObject);
begin
dm.q_tipo.Next;
validanavegacao;
end;
procedure TFRM_TIPO.SpUltimoClick(Sender: TObject);
begin
dm.q_tipo.last;
validanavegacao;
end;
procedure TFRM_TIPO.SpSairClick(Sender: TObject);
begin
close;
end;
procedure TFRM_TIPO.validanavegacao;
begin
spprimeiro.enabled:=not(dm.Q_TIPO.bof);
SpAnterior.enabled:=not(dm.Q_TIPO.bof);
SpProximo.enabled:=not(dm.Q_TIPO.eof);
SpUltimo.enabled:=not(dm.q_tipo.eof);
end;
procedure TFRM_TIPO.FormShow(Sender: TObject);
begin
validanavegacao;
end;
procedure TFRM_TIPO.FormClose(Sender: TObject; var Action: TCloseAction);
begin
dm.q_patri.close;
dm.q_aqui.close;
dm.q_como.close;
dm.q_tipo.close;
end;
procedure TFRM_TIPO.SpInserirClick(Sender: TObject);
begin
dm.q_tipo.insert;
validainsercaodados;
end;
procedure TFRM_TIPO.SpdeletarClick(Sender: TObject);
begin
dm.q_tipo.Edit;
validainsercaodados;
end;
procedure TFRM_TIPO.SpeditarClick(Sender: TObject);
begin
dm.q_tipo.delete;
validainsercaodados;
end;
procedure TFRM_TIPO.SpGravarClick(Sender: TObject);
begin
dm.q_tipo.post;
validainsercaodados;
end;
procedure TFRM_TIPO.SpCancelarClick(Sender: TObject);
begin
dm.q_tipo.Cancel;
validainsercaodados;
end;
procedure TFRM_TIPO.validainsercaodados;
begin
Spprimeiro.enabled:=(dm.Q_COMO.state=dsbrowse);
SpAnterior.enabled:=(dm.Q_COMO.state=dsbrowse);
SpProximo.Enabled:=(dm.Q_COMO.State=dsBrowse);
spultimo.Enabled:=(dm.Q_COMO.State=dsBrowse);
SpInserir.Enabled:=(dm.Q_COMO.State=dsBrowse);
Speditar.Enabled:=(dm.Q_COMO.State=dsBrowse);
Spdeletar.Enabled:=(dm.Q_COMO.State=dsBrowse);
spgravar.enabled:=(dm.Q_COMO.state in [dsinsert,dsedit]);
SpCancelar.Enabled:=(dm.Q_COMO.state in [dsinsert,dsedit]);
spsair.enabled:=(dm.Q_COMO.state=dsBrowse);
end;
end.
|
unit IdWebSocket;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
Uses
SysUtils, Classes,
IdGlobal, IdComponent, IdTCPConnection, IdContext, IdCustomHTTPServer, IdHashSHA, IdCoderMIME;
Type
TIdWebSocketOperation = (wsoNoOp, wsoText, wsoBinary, wsoClose);
TIdWebSocketCommand = record
op : TIdWebSocketOperation;
text : String;
bytes : TIdBytes;
status : integer;
end;
TIdWebSocket = class (TIdComponent)
private
FConnection : TIdTCPConnection;
FRequest: TIdHTTPRequestInfo;
procedure pong;
public
function open(AContext: TIdContext; request: TIdHTTPRequestInfo; response: TIdHTTPResponseInfo) : boolean;
function IsOpen : boolean;
function read(wait : boolean) : TIdWebSocketCommand;
procedure write(s : String);
procedure close;
Property Request : TIdHTTPRequestInfo read FRequest;
end;
implementation
{ TIdWebSocket }
function TIdWebSocket.IsOpen: boolean;
begin
result := assigned(FConnection.IOHandler);
end;
function TIdWebSocket.open(AContext: TIdContext; request: TIdHTTPRequestInfo; response: TIdHTTPResponseInfo): boolean;
var
s : String;
hash : TIdHashSHA1;
base64 : TIdEncoderMIME;
begin
FRequest := request;
if request.RawHeaders.Values['Upgrade'] <> 'websocket' then
raise Exception.Create('Only web sockets supported on this end-point');
s := request.RawHeaders.Values['Sec-WebSocket-Key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
base64 := TIdEncoderMIME.Create(nil);
hash := TIdHashSHA1.Create;
try
s := base64.EncodeBytes(hash.HashString(s, IndyTextEncoding_ASCII));
finally
hash.Free;
base64.Free;
end;
response.ResponseNo := 101;
response.ResponseText := 'Switching Protocols';
response.CustomHeaders.AddValue('Upgrade', 'websocket');
response.Connection := 'Upgrade';
response.CustomHeaders.AddValue('Sec-WebSocket-Accept', s);
if (request.rawHeaders.IndexOfName('Sec-WebSocket-Protocol') > -1) then
response.CustomHeaders.AddValue('Sec-WebSocket-Protocol', 'chat');
response.WriteHeader;
FConnection := AContext.Connection;
result := true;
end;
procedure TIdWebSocket.pong;
var
b : byte;
begin
b := $80 + $10; // close
FConnection.IOHandler.write(b);
b := 0;
FConnection.IOHandler.write(b);
end;
function TIdWebSocket.read(wait : boolean) : TIdWebSocketCommand;
var
h, l : byte;
fin, msk : boolean;
op : byte;
mk : TIdBytes;
len : cardinal;
i : integer;
begin
FillChar(result, sizeof(TIdWebSocketCommand), 0);
if not wait and not FConnection.IOHandler.CheckForDataOnSource then
result.op := wsoNoOp
else
begin
h := FConnection.IOHandler.ReadByte;
fin := (h and $80) > 1;
if not fin then
raise Exception.Create('Multiple frames not done yet');
op := h and $0F;
l := FConnection.IOHandler.ReadByte;
msk := (l and $80) > 0;
len := l and $7F;
if len = 126 then
len := FConnection.IOHandler.ReadWord
else if len = 127 then
len := FConnection.IOHandler.ReadLongWord;
FConnection.IOHandler.ReadBytes(mk, 4);
FConnection.IOHandler.ReadBytes(result.bytes, len);
for i := 0 to length(result.bytes) - 1 do
result.bytes[i] := result.bytes[i] xor mk[i mod 4];
case op of
1: begin
result.op := wsoText;
result.text := IndyTextEncoding_UTF8.GetString(result.bytes);
end;
2: result.op := wsoText;
8: result.op := wsoClose;
9: begin
pong();
result := read(wait);
end;
else
raise Exception.Create('Unknown OpCode '+inttostr(op));
end;
end;
end;
procedure TIdWebSocket.write(s: String);
var
b : byte;
w : word;
bs : TIDBytes;
begin
b := $80 + $01; // text frame, last
FConnection.IOHandler.write(b);
if (length(s) <= 125) then
begin
b := length(s);
FConnection.IOHandler.write(b);
end
else if (length(s) <= $FFFF) then
begin
b := 126;
FConnection.IOHandler.write(b);
w := length(s);
FConnection.IOHandler.write(w);
end
else
begin
b := 127;
FConnection.IOHandler.write(b);
FConnection.IOHandler.write(length(s));
end;
bs := IndyTextEncoding_UTF8.GetBytes(s);
FConnection.IOHandler.write(bs);
end;
procedure TIdWebSocket.close;
var
b : byte;
begin
b := $80 + $08; // close
FConnection.IOHandler.write(b);
b := 0;
FConnection.IOHandler.write(b);
FConnection.IOHandler.Close;
end;
end.
|
unit SmartPointer;
interface
type
TSmartPtr<T: class> = record
private
FRef: T;
FRefCount: PInteger;
procedure Retain; inline;
procedure Release; inline;
public
constructor Create(const ARef: T);
class operator Initialize(out ADest: TSmartPtr<T>);
class operator Finalize(var ADest: TSmartPtr<T>);
class operator Assign(var ADest: TSmartPtr<T>;
const [ref] ASrc: TSmartPtr<T>);
{ For testing only }
function GetRefCount: Integer;
property Ref: T read FRef;
end;
implementation
{ TSmartPtr<T> }
constructor TSmartPtr<T>.Create(const ARef: T);
begin
FRef := ARef;
if (ARef <> nil) then
begin
GetMem(FRefCount, SizeOf(Integer));
FRefCount^ := 0;
end;
Retain;
end;
class operator TSmartPtr<T>.Initialize(out ADest: TSmartPtr<T>);
begin
ADest.FRef := nil;
ADest.FRefCount := nil;
end;
class operator TSmartPtr<T>.Finalize(var ADest: TSmartPtr<T>);
begin
ADest.Release;
end;
class operator TSmartPtr<T>.Assign(var ADest: TSmartPtr<T>;
const [ref] ASrc: TSmartPtr<T>);
begin
if (ADest.FRef <> ASrc.FRef) then
begin
ADest.Release;
ADest.FRef := ASrc.FRef;
ADest.FRefCount := ASrc.FRefCount;
ADest.Retain;
end;
end;
procedure TSmartPtr<T>.Retain;
begin
if (FRefCount <> nil) then
AtomicIncrement(FRefCount^);
end;
procedure TSmartPtr<T>.Release;
begin
if (FRefCount <> nil) then
begin
if (AtomicDecrement(FRefCount^) = 0) then
begin
FRef.Free;
FreeMem(FRefCount);
end;
FRef := nil;
FRefCount := nil;
end;
end;
function TSmartPtr<T>.GetRefCount: Integer;
begin
if (FRefCount = nil) then
Result := 0
else
Result := FRefCount^;
end;
end.
|
program problem_3_1_2;
var
selector: Integer;
a: Integer;
b: Integer;
result: Real;
begin
writeln('Available operations:');
writeln('1) a+b');
writeln('2) a-b');
writeln('3) a*b');
writeln('4) a div b');
writeln('5) a mod b');
writeln('6) a*a');
writeln('Enter operations number');
readln(selector);
case selector of
1:
begin
writeln('Enter two operands');
readln(a,b);
result:= a + b;
end;
2:
begin
writeln('Enter two operands');
readln(a,b);
result:= a - b;
end;
3:
begin
writeln('Enter two operands');
readln(a,b);
result:= a * b;
end;
4:
begin
writeln('Enter two operands');
readln(a,b);
result:= a div b;
end;
5:
begin
writeln('Enter two operands');
readln(a,b);
result:= a mod b;
end;
6:
begin
writeln('Enter one operand');
readln(a);
result:= a * a;
end
else
writeln('Invalid data');
end;
writeln('The result is ', result:0:2);
readln();
end. |
unit GenericClassCtor_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TFormGenericClassCtor = class(TForm)
BtnInt: TButton;
Memo1: TMemo;
BtnString: TButton;
BtnSequence: TButton;
procedure BtnIntClick(Sender: TObject);
procedure BtnSequenceClick(Sender: TObject);
procedure BtnStringClick(Sender: TObject);
private
{ Private declarations }
public
procedure Log (const StrMsg: string);
end;
var
FormGenericClassCtor: TFormGenericClassCtor;
implementation
{$R *.dfm}
uses GenericClassCtor_Classes;
type
TGenDouble = TGenericWithClassCtor <Double>;
procedure TFormGenericClassCtor.BtnIntClick(Sender: TObject);
var
GenInt: TGenericWithClassCtor <SmallInt>;
begin
GenInt := TGenericWithClassCtor <SmallInt>.Create;
GenInt.Data := 100;
Log ('Size: ' + IntToStr (GenInt.DataSize));
GenInt.Free;
end;
procedure TFormGenericClassCtor.BtnSequenceClick(Sender: TObject);
begin
Log (Trim(ListSequence.Text));
end;
procedure TFormGenericClassCtor.BtnStringClick(Sender: TObject);
var
GenStr: TGenericWithClassCtor <string>;
begin
GenStr := TGenericWithClassCtor <string>.Create;
GenStr.Data := '100';
Log ('Size: ' + IntToStr (GenStr.DataSize));
GenStr.Free;
end;
procedure TFormGenericClassCtor.Log(const StrMsg: string);
begin
Memo1.Lines.Add(StrMsg)
end;
end.
|
{
Number lexing errors.
See http://bofh.srv.ualberta.ca/beck/c415/s_pal.pdf "Lexical Entities" 3.
and http://pascal-central.com/docs/iso10206.pdf Section 6.1.7
## All errors are written in filename:line:character format ##
1.pal:44:14 -- Real number needs digits before decimal point.
1.pal:45:18 -- Real number needs also digits after decimal point not only E.
1.pal:46:18 -- Real number needs digits after E.
}
program lexerrorNumbers(input, output);
begin
{ Legal numbers }
writeln( 123 );
writeln( 123.4 );
writeln( 123E10 );
writeln( 123E+10 );
writeln( 123E-10 );
writeln( 123.4E10 );
writeln( 123.4E+10 );
writeln( 123.4E-10 );
writeln( 0 );
writeln( 0.0 );
writeln( 0E0 );
writeln( 0.0E0 );
writeln( 0E+0 );
writeln( 0E-0 );
writeln( 0.0E+0 );
writeln( 0.0E-0 );
writeln( 000 );
writeln( 000.00 );
writeln( 1 );
writeln( 1E1 );
writeln( 1.1 );
writeln( 1.1E1 );
writeln( 01 );
writeln( 01E01 );
writeln( 01.01 );
writeln( 01.01E01 );
{ Illegal numbers }
writeln( .999 );
writeln( 999.E10 );
writeln( 999E );
{ LEGAL NUMBERS }
writeln( 1-1 );
end.
{ vim: set ft=pascal: }
|
unit dao.Cliente;
interface
uses
UConstantes,
classes.ScriptDDL,
model.Cliente,
System.StrUtils, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FireDAC.Comp.Client, FireDAC.Comp.DataSet;
type
TClienteDao = class(TObject)
strict private
class var aInstance : TClienteDao;
private
aDDL : TScriptDDL;
aModel : TCliente;
aLista : TClientes;
aOperacao : TTipoOperacaoDao;
constructor Create();
procedure SetValues(const aDataSet : TFDQuery; const aObject : TCliente);
procedure ClearLista;
public
property Model : TCliente read aModel write aModel;
property Lista : TClientes read aLista write aLista;
property Operacao : TTipoOperacaoDao read aOperacao;
procedure Load(const aBusca : String);
procedure Insert();
procedure Update();
procedure Delete();
procedure Limpar();
procedure Sincronizado();
procedure AddLista; overload;
procedure AddLista(aCliente : TCliente); overload;
procedure CarregarDadosToSynchrony;
function Find(const aCodigo : Currency; const IsLoadModel : Boolean) : Boolean; overload;
function Find(const aID : TGUID; const aCpfCnpj : String; const IsLoadModel : Boolean) : Boolean; overload;
function GetCount() : Integer;
function GetCountSincronizar() : Integer;
function PodeExcluir : Boolean;
class function GetInstance : TClienteDao;
end;
implementation
{ TClienteDao }
uses
UDM, app.Funcoes;
procedure TClienteDao.AddLista;
var
I : Integer;
o : TCliente;
begin
I := High(aLista) + 2;
o := TCliente.Create;
if (I <= 0) then
I := 1;
SetLength(aLista, I);
aLista[I - 1] := o;
end;
procedure TClienteDao.AddLista(aCliente: TCliente);
var
I : Integer;
begin
I := High(aLista) + 2;
if (I <= 0) then
I := 1;
SetLength(aLista, I);
aLista[I - 1] := aCliente;
end;
procedure TClienteDao.CarregarDadosToSynchrony;
var
aQry : TFDQuery;
aCliente : TCliente;
aFiltro : String;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Select');
SQL.Add(' c.* ');
SQL.Add('from ' + aDDL.getTableNameCliente + ' c');
SQL.Add('where (sn_sincronizado = ' + QuotedStr(FLAG_NAO) +')');
SQL.EndUpdate;
if OpenOrExecute then
begin
ClearLista;
if (RecordCount > 0) then
while not Eof do
begin
aCliente := TCliente.Create;
SetValues(aQry, aCliente);
AddLista(aCliente);
Next;
end;
end;
aQry.Close;
end;
finally
aQry.DisposeOf;
end;
end;
procedure TClienteDao.ClearLista;
begin
SetLength(aLista, 0);
end;
constructor TClienteDao.Create;
begin
inherited Create;
aDDL := TScriptDDL.GetInstance;
aModel := TCliente.Create;
aOperacao := TTipoOperacaoDao.toBrowser;
SetLength(aLista, 0);
end;
procedure TClienteDao.Delete;
var
aQry : TFDQuery;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Delete from ' + aDDL.getTableNameCliente);
SQL.Add('where id_cliente = :id_cliente ');
SQL.EndUpdate;
ParamByName('id_cliente').AsString := GUIDToString(aModel.ID);
ExecSQL;
aOperacao := TTipoOperacaoDao.toExcluido;
end;
finally
aQry.DisposeOf;
end;
end;
function TClienteDao.Find(const aID: TGUID; const aCpfCnpj: String; const IsLoadModel: Boolean): Boolean;
var
aQry : TFDQuery;
aRetorno : Boolean;
begin
aRetorno := False;
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Select');
SQL.Add(' c.* ');
SQL.Add('from ' + aDDL.getTableNameCliente + ' c');
SQL.Add('where (c.id_cliente = :id_cliente)');
SQL.Add(' or (c.nr_cpf_cnpj = :nr_cpf_cnpj)');
SQL.EndUpdate;
ParamByName('id_cliente').AsString := aID.ToString;
ParamByName('nr_cpf_cnpj').AsString := aCpfCnpj.Trim();
if OpenOrExecute then
begin
aRetorno := (RecordCount > 0);
if aRetorno and IsLoadModel then
SetValues(aQry, aModel);
end;
aQry.Close;
end;
finally
aQry.DisposeOf;
Result := aRetorno;
end;
end;
function TClienteDao.Find(const aCodigo: Currency;
const IsLoadModel: Boolean): Boolean;
var
aQry : TFDQuery;
aRetorno : Boolean;
begin
aRetorno := False;
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Select');
SQL.Add(' c.* ');
SQL.Add('from ' + aDDL.getTableNameCliente + ' c');
SQL.Add('where c.cd_cliente = ' + CurrToStr(aCodigo));
SQL.EndUpdate;
if OpenOrExecute then
begin
aRetorno := (RecordCount > 0);
if aRetorno and IsLoadModel then
SetValues(aQry, aModel);
end;
aQry.Close;
end;
finally
aQry.DisposeOf;
Result := aRetorno;
end;
end;
function TClienteDao.GetCount: Integer;
var
aRetorno : Integer;
aQry : TFDQuery;
begin
aRetorno := 0;
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Select ');
SQL.Add(' count(*) as qt_clientes');
SQL.Add('from ' + aDDL.getTableNameCliente);
SQL.EndUpdate;
OpenOrExecute;
aRetorno := FieldByName('qt_clientes').AsInteger;
aQry.Close;
end;
finally
aQry.DisposeOf;
Result := aRetorno;
end;
end;
function TClienteDao.GetCountSincronizar: Integer;
var
aRetorno : Integer;
aQry : TFDQuery;
begin
aRetorno := 0;
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Select ');
SQL.Add(' count(*) as qt_clientes');
SQL.Add('from ' + aDDL.getTableNameCliente);
SQL.Add('where (sn_sincronizado = ' + QuotedStr(FLAG_NAO) +')');
SQL.EndUpdate;
OpenOrExecute;
aRetorno := FieldByName('qt_clientes').AsInteger;
aQry.Close;
end;
finally
aQry.DisposeOf;
Result := aRetorno;
end;
end;
class function TClienteDao.GetInstance: TClienteDao;
begin
if not Assigned(aInstance) then
aInstance := TClienteDao.Create();
Result := aInstance;
end;
procedure TClienteDao.Insert;
var
aQry : TFDQuery;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Insert Into ' + aDDL.getTableNameCliente + '(');
SQL.Add(' id_cliente ');
SQL.Add(' , cd_cliente ');
SQL.Add(' , nm_cliente ');
SQL.Add(' , tp_cliente ');
SQL.Add(' , nr_cpf_cnpj ');
SQL.Add(' , ds_contato ');
SQL.Add(' , nr_telefone ');
SQL.Add(' , nr_celular ');
SQL.Add(' , ds_email ');
SQL.Add(' , ds_endereco ');
SQL.Add(' , ds_observacao ');
SQL.Add(' , sn_ativo ');
SQL.Add(' , sn_sincronizado ');
if (aModel.Referencia <> GUID_NULL) then
SQL.Add(' , cd_referencia ');
SQL.Add(') values (');
SQL.Add(' :id_cliente ');
SQL.Add(' , :cd_cliente ');
SQL.Add(' , :nm_cliente ');
SQL.Add(' , :tp_cliente ');
SQL.Add(' , :nr_cpf_cnpj ');
SQL.Add(' , :ds_contato ');
SQL.Add(' , :nr_telefone ');
SQL.Add(' , :nr_celular ');
SQL.Add(' , :ds_email ');
SQL.Add(' , :ds_endereco ');
SQL.Add(' , :ds_observacao ');
SQL.Add(' , :sn_ativo ');
SQL.Add(' , :sn_sincronizado ');
if (aModel.Referencia <> GUID_NULL) then
SQL.Add(' , :cd_referencia ');
SQL.Add(')');
SQL.EndUpdate;
if (aModel.ID = GUID_NULL) then
aModel.NewID;
if (aModel.Codigo = 0) then
aModel.Codigo := GetNewID(aDDL.getTableNameCliente, 'cd_cliente', EmptyStr);
ParamByName('id_cliente').AsString := GUIDToString(aModel.ID);
ParamByName('cd_cliente').AsCurrency := aModel.Codigo;
ParamByName('nm_cliente').AsString := aModel.Nome;
ParamByName('tp_cliente').AsString := GetTipoClienteStr(aModel.Tipo);
ParamByName('nr_cpf_cnpj').AsString := aModel.CpfCnpj;
ParamByName('ds_contato').AsString := aModel.Contato;
ParamByName('nr_telefone').AsString := aModel.Telefone;
ParamByName('nr_celular').AsString := aModel.Celular;
ParamByName('ds_email').AsString := aModel.Email;
ParamByName('ds_endereco').AsString := aModel.Endereco;
ParamByName('ds_observacao').AsString := aModel.Observacao;
ParamByName('sn_ativo').AsString := IfThen(aModel.Ativo, FLAG_SIM, FLAG_NAO);
ParamByName('sn_sincronizado').AsString := IfThen(aModel.Sincronizado, FLAG_SIM, FLAG_NAO);
if (aModel.Referencia <> GUID_NULL) then
ParamByName('cd_referencia').AsString := GUIDToString(aModel.Referencia);
ExecSQL;
aOperacao := TTipoOperacaoDao.toIncluido;
end;
finally
aQry.DisposeOf;
end;
end;
procedure TClienteDao.Limpar;
var
aQry : TFDQuery;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Delete from ' + aDDL.getTableNameCliente);
SQL.EndUpdate;
ExecSQL;
aOperacao := TTipoOperacaoDao.toExcluir;
end;
finally
aQry.DisposeOf;
end;
end;
procedure TClienteDao.Load(const aBusca: String);
var
aQry : TFDQuery;
aCliente : TCliente;
aFiltro : String;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
aFiltro := AnsiUpperCase(Trim(aBusca));
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Select');
SQL.Add(' c.* ');
SQL.Add('from ' + aDDL.getTableNameCliente + ' c');
if (StrToCurrDef(aFiltro, 0) > 0) then
SQL.Add('where c.cd_cliente = ' + aFiltro)
else
if StrIsGUID(aBusca) then
SQL.Add('where c.id_cliente = ' + QuotedStr(aFiltro))
else
if (Trim(aBusca) <> EmptyStr) then
begin
aFiltro := '%' + StringReplace(aFiltro, ' ', '%', [rfReplaceAll]) + '%';
SQL.Add('where c.nm_cliente like ' + QuotedStr(aFiltro));
end;
SQL.Add('order by');
SQL.Add(' c.nm_cliente ');
SQL.EndUpdate;
if OpenOrExecute then
begin
ClearLista;
if (RecordCount > 0) then
while not Eof do
begin
aCliente := TCliente.Create;
SetValues(aQry, aCliente);
AddLista(aCliente);
Next;
end;
end;
aQry.Close;
end;
finally
aQry.DisposeOf;
end;
end;
function TClienteDao.PodeExcluir: Boolean;
var
aRetorno : Boolean;
aQry : TFDQuery;
begin
aRetorno := True;
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Select ');
SQL.Add(' count(id_cliente) as qt_clientes');
SQL.Add('from ' + aDDL.getTableNamePedido);
SQL.Add('where id_cliente = :id_cliente');
SQL.EndUpdate;
ParamByName('id_cliente').AsString := GUIDToString(aModel.ID);
OpenOrExecute;
aRetorno := (FieldByName('qt_clientes').AsInteger = 0);
aQry.Close;
end;
finally
aQry.DisposeOf;
Result := aRetorno;
end;
end;
procedure TClienteDao.SetValues(const aDataSet: TFDQuery;
const aObject: TCliente);
begin
with aDataSet, aObject do
begin
ID := StringToGUID(FieldByName('id_cliente').AsString);
Codigo := FieldByName('cd_cliente').AsCurrency;
Tipo := IfThen(AnsiUpperCase(FieldByName('tp_cliente').AsString) = 'F', tcPessoaFisica, tcPessoaJuridica);
Nome := FieldByName('nm_cliente').AsString;
CpfCnpj := FieldByName('nr_cpf_cnpj').AsString;
Contato := FieldByName('ds_contato').AsString;
Telefone := FieldByName('nr_telefone').AsString;
Celular := FieldByName('nr_celular').AsString;
Email := FieldByName('ds_email').AsString;
Endereco := FieldByName('ds_endereco').AsString;
Observacao := FieldByName('ds_observacao').AsString;
Ativo := (AnsiUpperCase(FieldByName('sn_ativo').AsString) = 'S');
Sincronizado := (AnsiUpperCase(FieldByName('sn_sincronizado').AsString) = 'S');
if (Trim(FieldByName('cd_referencia').AsString) <> EmptyStr) then
Referencia := StringToGUID(FieldByName('cd_referencia').AsString)
else
Referencia := GUID_NULL;
DataUltimaCompra := FieldByName('dt_ultima_compra').AsDateTime;
ValorUltimaCompra := FieldByName('vl_ultima_compra').AsCurrency;
end;
end;
procedure TClienteDao.Sincronizado;
var
aQry : TFDQuery;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Update ' + aDDL.getTableNameCliente + ' Set');
SQL.Add(' sn_ativo = :sn_ativo ');
SQL.Add(' , sn_sincronizado = :sn_sincronizado ');
SQL.Add('where id_cliente = :id_cliente ');
SQL.EndUpdate;
ParamByName('id_cliente').AsString := GUIDToString(aModel.ID);
ParamByName('sn_ativo').AsString := IfThen(aModel.Ativo, FLAG_SIM, FLAG_NAO);
ParamByName('sn_sincronizado').AsString := IfThen(aModel.Sincronizado, FLAG_SIM, FLAG_NAO);
ExecSQL;
end;
finally
aQry.DisposeOf;
end;
end;
procedure TClienteDao.Update;
var
aQry : TFDQuery;
aFone : String;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
aFone := aModel.Telefone.Trim();
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Update ' + aDDL.getTableNameCliente + ' Set');
SQL.Add(' cd_cliente = :cd_cliente ');
SQL.Add(' , nm_cliente = :nm_cliente ');
SQL.Add(' , tp_cliente = :tp_cliente ');
SQL.Add(' , nr_cpf_cnpj = :nr_cpf_cnpj ');
SQL.Add(' , ds_contato = :ds_contato ');
if (Length(aFone) > 14) then // (91) 3295-3390
SQL.Add(' , nr_celular = :nr_celular ')
else
SQL.Add(' , nr_telefone = :nr_telefone ');
SQL.Add(' , ds_email = :ds_email ');
SQL.Add(' , ds_endereco = :ds_endereco ');
SQL.Add(' , ds_observacao = :ds_observacao ');
SQL.Add(' , sn_ativo = :sn_ativo ');
SQL.Add(' , sn_sincronizado = :sn_sincronizado ');
if (aModel.Referencia <> GUID_NULL) then
SQL.Add(' , cd_referencia = :cd_referencia ');
SQL.Add('where id_cliente = :id_cliente ');
SQL.EndUpdate;
ParamByName('id_cliente').AsString := GUIDToString(aModel.ID);
ParamByName('cd_cliente').AsCurrency := aModel.Codigo;
ParamByName('nm_cliente').AsString := aModel.Nome;
ParamByName('tp_cliente').AsString := GetTipoClienteStr(aModel.Tipo);
ParamByName('nr_cpf_cnpj').AsString := aModel.CpfCnpj;
ParamByName('ds_contato').AsString := aModel.Contato;
if (Length(aFone) > 14) then // (91) 3295-3390
ParamByName('nr_celular').AsString := aFone
else
ParamByName('nr_telefone').AsString := aFone;
ParamByName('ds_email').AsString := aModel.Email;
ParamByName('ds_endereco').AsString := aModel.Endereco;
ParamByName('ds_observacao').AsString := aModel.Observacao;
ParamByName('sn_ativo').AsString := IfThen(aModel.Ativo, FLAG_SIM, FLAG_NAO);
ParamByName('sn_sincronizado').AsString := IfThen(aModel.Sincronizado, FLAG_SIM, FLAG_NAO);
if (aModel.Referencia <> GUID_NULL) then
ParamByName('cd_referencia').AsString := GUIDToString(aModel.Referencia);
ExecSQL;
aOperacao := TTipoOperacaoDao.toEditado;
end;
finally
aQry.DisposeOf;
end;
end;
end.
|
unit AsyncFileCopy.Impl;
interface
uses
System.SysUtils, System.DateUtils, AsyncIO, AsyncIO.OpResults, System.Math,
AsyncIO.Filesystem;
type
IOProgressHandler = reference to procedure(const TotalBytesRead, TotalBytesWritten: UInt64;
const ReadBPS, WriteBPS: double);
AsyncFileCopier = interface
{$REGION Property accessors}
function GetService: IOService;
{$ENDREGION}
procedure Execute(const InputFilename, OutputFilename: string);
property Service: IOService read GetService;
end;
function NewAsyncFileCopier(const Service: IOService; const ProgressHandler: IOProgressHandler; const BufferSize: integer = 4*1024): AsyncFileCopier;
implementation
uses
AsyncIO.Coroutine;
type
AsyncFileCopierImpl = class(TInterfacedObject, AsyncFileCopier)
private
FService: IOService;
FProgressHandler: IOProgressHandler;
FBuffer: TBytes;
FTotalBytesRead: UInt64;
FTotalBytesWritten: UInt64;
FReadTimeMSec: Int64;
FWriteTimeMSec: Int64;
FProgressTimestamp: TDateTime;
procedure ProgressUpdate;
public
constructor Create(const Service: IOService; const ProgressHandler: IOProgressHandler; const BufferSize: integer);
function GetService: IOService;
procedure Execute(const InputFilename, OutputFilename: string);
property Service: IOService read FService;
end;
function NewAsyncFileCopier(const Service: IOService; const ProgressHandler: IOProgressHandler; const BufferSize: integer): AsyncFileCopier;
begin
result := AsyncFileCopierImpl.Create(Service, ProgressHandler, BufferSize);
end;
{ AsyncFileCopierImpl }
constructor AsyncFileCopierImpl.Create(const Service: IOService; const ProgressHandler: IOProgressHandler; const BufferSize: integer);
begin
inherited Create;
FService := Service;
FProgressHandler := ProgressHandler;
SetLength(FBuffer, BufferSize);
end;
procedure AsyncFileCopierImpl.Execute(const InputFilename, OutputFilename: string);
var
inputStream: AsyncFileStream;
outputStream: AsyncFileStream;
serviceContext: IOServiceCoroutineContext;
yield: YieldContext;
readRes: IOResult;
writeRes: IOResult;
doneReading: boolean;
readTimestamp: TDateTime;
writeTimestamp: TDateTime;
begin
inputStream := NewAsyncFileStream(Service, InputFilename, fcOpenExisting, faRead, fsRead);
outputStream := NewAsyncFileStream(Service, OutputFilename, fcCreateAlways, faWrite, fsNone);
serviceContext := NewIOServiceCoroutineContext(Service);
yield := NewYieldContext(serviceContext);
doneReading := False;
while (True) do
begin
// queue the async read
// this will return once the read has completed
readTimestamp := Now;
readRes := AsyncRead(inputStream, FBuffer, TransferAll(), yield);
if (not readRes.Success) and (readRes <> SystemResults.EndOfFile) then
begin
readRes.RaiseException('Reading file');
end;
// check for EOF
if (readRes = SystemResults.EndOfFile) then
doneReading := True;
FTotalBytesRead := FTotalBytesRead + readRes.BytesTransferred;
FReadTimeMSec := FReadTimeMSec + MilliSecondsBetween(Now, readTimestamp);
ProgressUpdate;
if (readRes.BytesTransferred = 0) then
begin
// stopping to be improved
Service.Stop;
exit;
end;
// we've read some data, now queue write
// again this will return once the write has completed
writeTimestamp := Now;
writeRes := AsyncWrite(outputStream, FBuffer, TransferExactly(readRes.BytesTransferred), yield);
if (not writeRes.Success) then
begin
writeRes.RaiseException('Writing file');
end;
if (doneReading) then
FProgressTimestamp := 0;
FTotalBytesWritten := FTotalBytesWritten + writeRes.BytesTransferred;
FWriteTimeMSec := FWriteTimeMSec + MilliSecondsBetween(Now, writeTimestamp);
ProgressUpdate;
if (doneReading) then
begin
// stopping to be improved
Service.Stop;
exit;
end
// writing done and we got more to read, so rinse repeat
end;
end;
function AsyncFileCopierImpl.GetService: IOService;
begin
result := FService;
end;
procedure AsyncFileCopierImpl.ProgressUpdate;
var
readBPS, writeBPS: double;
begin
if (not Assigned(FProgressHandler)) then
exit;
if (MilliSecondsBetween(Now, FProgressTimestamp) < 500) then
exit;
readBPS := FTotalBytesRead / (1e3 * Max(1, FReadTimeMSec));
writeBPS := FTotalBytesWritten / (1e3 * Max(1, FWriteTimeMSec));
FProgressHandler(FTotalBytesRead, FTotalBytesWritten, readBPS, writeBPS);
FProgressTimestamp := Now;
end;
end.
|
unit ClienteFornecedor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, uADStanIntf,
uADStanOption, uADStanParam, uADStanError, uADDatSManager, uADPhysIntf,
uADDAptIntf, uADStanAsync, uADDAptManager, Data.DB, uADCompDataSet,
uADCompClient, Vcl.Grids, Vcl.DBGrids;
type
TfrmCliFor = class(TForm)
editNomeRazao: TLabeledEdit;
editCpfCnpj: TLabeledEdit;
editEndereco: TLabeledEdit;
editTelefone: TLabeledEdit;
editCep: TLabeledEdit;
editDataNasc: TLabeledEdit;
editProfissao: TLabeledEdit;
comboStatus: TComboBox;
radioTipoPessoa: TRadioGroup;
comboEstadoCivil: TComboBox;
Label1: TLabel;
Label2: TLabel;
btnSalvar: TButton;
btnAtualizar: TButton;
btnExcluir: TButton;
btnCancelar: TButton;
dbGridCliFor: TDBGrid;
btnListar: TButton;
ADQuery1: TADQuery;
DataSource1: TDataSource;
editID: TLabeledEdit;
comboTipoCliFor: TComboBox;
Label3: TLabel;
comboGenero: TComboBox;
Label4: TLabel;
procedure FormShow(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure btnListarClick(Sender: TObject);
procedure btnAtualizarClick(Sender: TObject);
procedure dbGridCliForCellClick(Column: TColumn);
procedure FormCreate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
//procedure dbGridCliForCellClick(Column: TColumn);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmCliFor: TfrmCliFor;
implementation
{$R *.dfm}
//atualiza cliente e fornecedores
procedure TfrmCliFor.btnAtualizarClick(Sender: TObject);
begin
if editID.Text <> '' then begin //verifica id e descrição se estão vazios
ADQuery1.Close;
ADQuery1.SQL.Clear;
ADQuery1.SQL.Add('SELECT ID FROM TBCLIFOR WHERE ID = :ID');
ADQuery1.ParamByName('ID').AsString := editID.Text;
ADQuery1.Open;
if not ADQuery1.IsEmpty then begin
try
ADQuery1.Close;
ADQuery1.SQL.Clear;
ADQuery1.SQL.Add('UPDATE TBCLIFOR SET NOME = :NOME, CPF_CNPJ = :CPF_CNPJ, ENDERECO = :ENDERECO, TELEFONE = :TELEFONE, CEP = :CEP, SEXO = :SEXO,');
ADQuery1.SQL.Add(' DATA_NASC = :DATA_NASC, PROFISSAO = :PROFISSAO, ESTADO_CIVIL = :ESTADO_CIVIL, STATUS = :STATUS, TIPO_PESSOA = :TIPO_PESSOA, TIPO_CLI_FOR = :TIPO_CLI_FOR WHERE ID = :ID');
ADQuery1.ParamByName('NOME').AsString := editNomeRazao.Text;
ADQuery1.ParamByName('CPF_CNPJ').AsString := editCpfCnpj.Text;
ADQuery1.ParamByName('ENDERECO').AsString := editEndereco.Text;
ADQuery1.ParamByName('TELEFONE').AsString := editTelefone.Text;
ADQuery1.ParamByName('CEP').AsString := editCep.Text;
ADQuery1.ParamByName('SEXO').AsString := comboGenero.Text;
ADQuery1.ParamByName('DATA_NASC').AsString := editDataNasc.Text;
ADQuery1.ParamByName('PROFISSAO').AsString := editProfissao.Text;
ADQuery1.ParamByName('ESTADO_CIVIL').AsString := comboEstadoCivil.Text;
ADQuery1.ParamByName('STATUS').AsInteger := StrToIntDef(comboStatus.Text, 0);
ADQuery1.ParamByName('TIPO_PESSOA').AsInteger := StrToIntDef(comboStatus.Text, 0);
ADQuery1.ParamByName('TIPO_CLI_FOR').AsInteger := StrToIntDef(comboStatus.Text, 0);
ADQuery1.ParamByName('STATUS').AsInteger := StrToIntDef(comboStatus.Text, 0);
ADQuery1.ParamByName('ID').AsString := editID.Text;
ADQuery1.ExecSQL;
finally
btnListarClick(Sender);
ShowMessage('Atualizado com sucesso!');
end;
end;
end;
end;
//lista usarios na dbgrid
procedure TfrmCliFor.btnListarClick(Sender: TObject);
begin
ADQuery1.Close;
ADQuery1.SQL.Clear;
ADQuery1.SQL.Add('SELECT * FROM TBCLIFOR');
ADQuery1.Open;
end;
//cadastro de clientes
procedure TfrmCliFor.btnSalvarClick(Sender: TObject);
begin
if editID.Text <> '' then begin
ShowMessage('O campo ID deve estar em branco para realizar um novo cadastro!');
exit;
end;
if editNomeRazao.Text <> '' then begin
ADQuery1.Close;
ADQuery1.SQL.Clear;
ADQuery1.SQL.Add('INSERT INTO TBCLIFOR (NOME, CPF_CNPJ, ENDERECO, TELEFONE, CEP, SEXO, DATA_NASC, PROFISSAO, ESTADO_CIVIL, STATUS, TIPO_PESSOA, TIPO_CLI_FOR, ID_USUARIO)');
ADQuery1.SQL.Add(' VALUES (:NOME, :CPF_CNPJ, :ENDERECO, :TELEFONE, :CEP, :SEXO, :DATA_NASC, :PROFISSAO, :ESTADO_CIVIL, :STATUS, :TIPO_PESSOA, :TIPO_CLI_FOR, :ID_USUARIO)');
ADQuery1.ParamByName('NOME').AsString := editNomeRazao.Text;
ADQuery1.ParamByName('CPF_CNPJ').AsString := editCpfCnpj.Text;
ADQuery1.ParamByName('ENDERECO').AsString := editEndereco.Text;
ADQuery1.ParamByName('TELEFONE').AsString := editTelefone.Text;
ADQuery1.ParamByName('CEP').AsString := editCep.Text;
ADQuery1.ParamByName('SEXO').AsString := comboGenero.Text;
ADQuery1.ParamByName('DATA_NASC').AsString := editDataNasc.Text;
ADQuery1.ParamByName('PROFISSAO').AsString := editProfissao.Text;
ADQuery1.ParamByName('ESTADO_CIVIL').AsString := comboEstadoCivil.Text;
ADQuery1.ParamByName('STATUS').AsInteger := StrToIntDef(comboStatus.Text, 0);
ADQuery1.ParamByName('TIPO_PESSOA').AsInteger := StrToIntDef(comboStatus.Text, 0);
ADQuery1.ParamByName('TIPO_CLI_FOR').AsInteger := StrToIntDef(comboTipoCliFor.Text, 0);
ADQuery1.ParamByName('STATUS').AsInteger := StrToIntDef(comboStatus.Text, 0);
ADQuery1.ParamByName('ID_USUARIO').AsInteger := 1;
ADQuery1.ExecSQL;
btnListarClick(Sender);
end;
end;
procedure TfrmCliFor.dbGridCliForCellClick(Column: TColumn);
begin
end;
{
procedure TfrmCliFor.dbGridCliForCellClick(Column: TColumn);
begin
editID.Text := dbGridCliFor.DataSource.DataSet.FieldByName('ID').AsString;
editNomeRazao.Text := dbGridCliFor.DataSource.DataSet.FieldByName('NOME').AsString;
editCpfCnpj.Text := dbGridCliFor.DataSource.DataSet.FieldByName('CPF_CNPJ').AsString;
editEndereco.Text := dbGridCliFor.DataSource.DataSet.FieldByName('ENDERECO').AsString;
editTelefone.Text := dbGridCliFor.DataSource.DataSet.FieldByName('TELEFONE').AsString;
editCep.Text := dbGridCliFor.DataSource.DataSet.FieldByName('CEP').AsString;
comboGenero.Text := dbGridCliFor.DataSource.DataSet.FieldByName('SEXO').AsString;
editDataNasc.Text := dbGridCliFor.DataSource.DataSet.FieldByName('DATA_NASC').AsString;
editProfissao.Text := dbGridCliFor.DataSource.DataSet.FieldByName('PROFISSAO').AsString;
comboEstadoCivil.Text := dbGridCliFor.DataSource.DataSet.FieldByName('ESTADO_CIVIL').AsString;
comboStatus.Text := dbGridCliFor.DataSource.DataSet.FieldByName('STATUS').AsString;
radioTipoPessoa.Text := dbGridCliFor.DataSource.DataSet.FieldByName('TIPO_PESSOA').AsString;
comboTipoCliFor.Text := dbGridCliFor.DataSource.DataSet.FieldByName('TIPO_PESSOA').AsString;
end;
}
//carrega os dados ao mostrar o formulário
procedure TfrmCliFor.FormShow(Sender: TObject);
begin
ADQuery1.Close;
ADQuery1.SQL.Clear;
ADQuery1.SQL.Add('SELECT * FROM TBCLIFOR');
ADQuery1.Open;
end;
procedure TfrmCliFor.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ADQuery1.Close;
ADQuery1.SQL.Clear;
Action := caFree;
self := nil;
end;
procedure TfrmCliFor.FormCreate(Sender: TObject);
begin
KeyPreview:=true;
end;
procedure TfrmCliFor.FormKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then begin
SelectNext(ActiveControl as TWinControl,True,True);
key:=#0;
end;
end;
end.
|
unit UnitTests;
interface
uses
SysUtils,
Classes,
eiTypes,
eiConstants,
eiProtocol,
eiHelpers,
TestFramework,
TestExtensions,
StopWatch,
Windows;
type
TPacketFactoryTest = class(TTestCase)
private
FPacketSize: int;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestGetReadPacket;
procedure TestGetWritePacket;
end;
TStopWatchTest = class(TTestCase)
private
FStopWatch: IStopWatch;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestRun;
end;
implementation
{ TPacketFactoryTest }
procedure TPacketFactoryTest.SetUp;
begin
inherited;
FPacketSize := SizeOf(EasyIpPacket);
end;
procedure TPacketFactoryTest.TearDown;
begin
inherited;
end;
procedure TPacketFactoryTest.TestGetReadPacket;
var
readPacket: EasyIpPacket;
begin
readPacket := TPacketFactory.GetReadPacket(0, dtFlag, EASYIP_DATASIZE - 1);
end;
procedure TPacketFactoryTest.TestGetWritePacket;
var
writePacket: EasyIpPacket;
begin
writePacket := TPacketFactory.GetWritePacket(0, dtFlag, EASYIP_DATASIZE - 1);
end;
{ TStopWatchTest }
procedure TStopWatchTest.SetUp;
begin
inherited;
FStopWatch := TStopWatch.Create;
end;
procedure TStopWatchTest.TearDown;
begin
inherited;
FStopWatch := nil;
end;
procedure TStopWatchTest.TestRun;
const
startSleepTime = 1;
multiplier = 2;
stopSleepTime = 500;
var
delta: int;
sleepValue: int;
begin
sleepValue := startSleepTime;
while (sleepValue < stopSleepTime) do
begin
FStopWatch.Start;
Sleep(sleepValue);
FStopWatch.Stop;
delta := FStopWatch.ElapsedMilliseconds - sleepValue;
OutputDebugString(PChar(FStopWatch.Elapsed));
Check(Abs(delta) < 15);
// OutputDebugString(PChar('delta ' + IntToStr(delta)));
sleepValue := sleepValue * multiplier;
end;
end;
initialization
// TestFramework.RegisterTest(TPacketFactoryTest.Suite);
// TestFramework.RegisterTest(TRepeatedTest.Create(TStopWatchTest.Suite, 2));
end.
|
unit TextEditor.Print.Margins;
interface
uses
System.Classes, System.SysUtils, Vcl.Graphics, TextEditor.Print.PrinterInfo, TextEditor.Types, TextEditor.Utils;
type
TTextEditorPrintMargins = class(TPersistent)
strict private
FBottom: Double;
FFooter: Double;
FHeader: Double;
FInternalMargin: Double;
FLeft: Double;
FLeftTextIndent: Double;
FMargin: Double;
FMirrorMargins: Boolean;
FPixelBottom: Integer;
FPixelFooter: Integer;
FPixelHeader: Integer;
FPixelInternalMargin: Integer;
FPixelLeft: Integer;
FPixelLeftTextIndent: Integer;
FPixelMargin: Integer;
FPixelRight: Integer;
FPixelRightTextIndent: Integer;
FPixelTop: Integer;
FRight: Double;
FRightTextIndent: Double;
FTop: Double;
FUnitSystem: TTextEditorUnitSystem;
function ConvertFrom(AValue: Double): Double;
function ConvertTo(AValue: Double): Double;
function GetBottom: Double;
function GetFooter: Double;
function GetHeader: Double;
function GetInternalMargin: Double;
function GetLeft: Double;
function GetLeftTextIndent: Double;
function GetMargin: Double;
function GetRight: Double;
function GetRightTextIndent: Double;
function GetTop: Double;
procedure SetBottom(const AValue: Double);
procedure SetFooter(const AValue: Double);
procedure SetHeader(const AValue: Double);
procedure SetInternalMargin(const AValue: Double);
procedure SetLeft(const AValue: Double);
procedure SetLeftTextIndent(const AValue: Double);
procedure SetMargin(const AValue: Double);
procedure SetRight(const AValue: Double);
procedure SetRightTextIndent(const AValue: Double);
procedure SetTop(const AValue: Double);
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
procedure InitPage(const ACanvas: TCanvas; const APageNumber: Integer; const APrinterInfo: TTextEditorPrinterInfo;
const ALineNumbers, ALineNumbersInMargin: Boolean; const AMaxLineNumber: Integer);
procedure LoadFromStream(const AStream: TStream);
procedure SaveToStream(const AStream: TStream);
property PixelBottom: Integer read FPixelBottom write FPixelBottom;
property PixelFooter: Integer read FPixelFooter write FPixelFooter;
property PixelHeader: Integer read FPixelHeader write FPixelHeader;
property PixelInternalMargin: Integer read FPixelInternalMargin write FPixelInternalMargin;
property PixelLeft: Integer read FPixelLeft write FPixelLeft;
property PixelLeftTextIndent: Integer read FPixelLeftTextIndent write FPixelLeftTextIndent;
property PixelMargin: Integer read FPixelMargin write FPixelMargin;
property PixelRight: Integer read FPixelRight write FPixelRight;
property PixelRightTextIndent: Integer read FPixelRightTextIndent write FPixelRightTextIndent;
property PixelTop: Integer read FPixelTop write FPixelTop;
published
property Bottom: Double read GetBottom write SetBottom;
property Footer: Double read GetFooter write SetFooter;
property Header: Double read GetHeader write SetHeader;
property InternalMargin: Double read GetInternalMargin write SetInternalMargin;
property Left: Double read GetLeft write SetLeft;
property LeftTextIndent: Double read GetLeftTextIndent write SetLeftTextIndent;
property Margin: Double read GetMargin write SetMargin;
property MirrorMargins: Boolean read FMirrorMargins write FMirrorMargins;
property Right: Double read GetRight write SetRight;
property RightTextIndent: Double read GetRightTextIndent write SetRightTextIndent;
property Top: Double read GetTop write SetTop;
property UnitSystem: TTextEditorUnitSystem read FUnitSystem write FUnitSystem default usMM;
end;
implementation
const
mmPerInch = 25.4;
mmPerCm = 10;
constructor TTextEditorPrintMargins.Create;
begin
inherited;
FUnitSystem := usMM;
FLeft := 20;
FRight := 15;
FTop := 18;
FBottom := 18;
FHeader := 15;
FFooter := 15;
FLeftTextIndent := 2;
FRightTextIndent := 2;
FInternalMargin := 0.5;
FMargin := 0;
FMirrorMargins := False;
end;
function TTextEditorPrintMargins.ConvertTo(AValue: Double): Double;
begin
case FUnitSystem of
usCm:
Result := AValue * mmPerCm;
usInch:
Result := AValue * mmPerInch;
muThousandthsOfInches:
Result := mmPerInch * AValue / 1000;
else
Result := AValue;
end;
end;
function TTextEditorPrintMargins.ConvertFrom(AValue: Double): Double;
begin
case FUnitSystem of
usCm:
Result := AValue / mmPerCm;
usInch:
Result := AValue / mmPerInch;
muThousandthsOfInches:
Result := 1000 * AValue / mmPerInch;
else
Result := AValue;
end;
end;
function TTextEditorPrintMargins.GetBottom: Double;
begin
Result := ConvertFrom(FBottom);
end;
function TTextEditorPrintMargins.GetFooter: Double;
begin
Result := ConvertFrom(FFooter);
end;
function TTextEditorPrintMargins.GetMargin: Double;
begin
Result := ConvertFrom(FMargin);
end;
function TTextEditorPrintMargins.GetHeader: Double;
begin
Result := ConvertFrom(FHeader);
end;
function TTextEditorPrintMargins.GetLeft: Double;
begin
Result := ConvertFrom(FLeft);
end;
function TTextEditorPrintMargins.GetRight: Double;
begin
Result := ConvertFrom(FRight);
end;
function TTextEditorPrintMargins.GetTop: Double;
begin
Result := ConvertFrom(FTop);
end;
function TTextEditorPrintMargins.GetLeftTextIndent: Double;
begin
Result := ConvertFrom(FLeftTextIndent);
end;
function TTextEditorPrintMargins.GetRightTextIndent: Double;
begin
Result := ConvertFrom(FRightTextIndent);
end;
function TTextEditorPrintMargins.GetInternalMargin: Double;
begin
Result := ConvertFrom(FInternalMargin);
end;
procedure TTextEditorPrintMargins.SetBottom(const AValue: Double);
begin
FBottom := ConvertTo(AValue);
end;
procedure TTextEditorPrintMargins.SetFooter(const AValue: Double);
begin
FFooter := ConvertTo(AValue);
end;
procedure TTextEditorPrintMargins.SetMargin(const AValue: Double);
begin
FMargin := ConvertTo(AValue);
end;
procedure TTextEditorPrintMargins.SetHeader(const AValue: Double);
begin
FHeader := ConvertTo(AValue);
end;
procedure TTextEditorPrintMargins.SetLeft(const AValue: Double);
begin
FLeft := ConvertTo(AValue);
end;
procedure TTextEditorPrintMargins.SetRight(const AValue: Double);
begin
FRight := ConvertTo(AValue);
end;
procedure TTextEditorPrintMargins.SetTop(const AValue: Double);
begin
FTop := ConvertTo(AValue);
end;
procedure TTextEditorPrintMargins.SetLeftTextIndent(const AValue: Double);
begin
FLeftTextIndent := ConvertTo(AValue);
end;
procedure TTextEditorPrintMargins.SetRightTextIndent(const AValue: Double);
begin
FRightTextIndent := ConvertTo(AValue);
end;
procedure TTextEditorPrintMargins.SetInternalMargin(const AValue: Double);
begin
FInternalMargin := ConvertTo(AValue);
end;
procedure TTextEditorPrintMargins.InitPage(const ACanvas: TCanvas; const APageNumber: Integer; const APrinterInfo: TTextEditorPrinterInfo;
const ALineNumbers, ALineNumbersInMargin: Boolean; const AMaxLineNumber: Integer);
begin
if FMirrorMargins and ((APageNumber mod 2) = 0) then
begin
PixelLeft := APrinterInfo.PixFromLeft(FRight);
PixelRight := APrinterInfo.PrintableWidth - APrinterInfo.PixFromRight(FLeft + FMargin);
end
else
begin
PixelLeft := APrinterInfo.PixFromLeft(FLeft + FMargin);
PixelRight := APrinterInfo.PrintableWidth - APrinterInfo.PixFromRight(FRight);
end;
if ALineNumbers and (not ALineNumbersInMargin) then
PixelLeft := PixelLeft + TextWidth(ACanvas, IntToStr(AMaxLineNumber) + ': ');
PixelTop := APrinterInfo.PixFromTop(FTop);
PixelBottom := APrinterInfo.PrintableHeight - APrinterInfo.PixFromBottom(FBottom);
PixelHeader := APrinterInfo.PixFromTop(FHeader);
PixelFooter := APrinterInfo.PrintableHeight - APrinterInfo.PixFromBottom(FFooter);
PixelInternalMargin := Round(APrinterInfo.YPixPermm * FInternalMargin);
PixelMargin := Round(APrinterInfo.XPixPermm * FMargin);
PixelRightTextIndent := PixelRight - Round(APrinterInfo.XPixPermm * FRightTextIndent);
PixelLeftTextIndent := PixelLeft + Round(APrinterInfo.XPixPermm * FLeftTextIndent);
end;
procedure TTextEditorPrintMargins.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TTextEditorPrintMargins) then
with ASource as TTextEditorPrintMargins do
begin
Self.FLeft := FLeft;
Self.FRight := FRight;
Self.FTop := FTop;
Self.FBottom := FBottom;
Self.FHeader := FHeader;
Self.FFooter := FFooter;
Self.FLeftTextIndent := FLeftTextIndent;
Self.FRightTextIndent := FRightTextIndent;
Self.FInternalMargin := FInternalMargin;
Self.FMargin := FMargin;
Self.FMirrorMargins := FMirrorMargins;
Self.FUnitSystem := FUnitSystem;
end
else
inherited Assign(ASource);
end;
procedure TTextEditorPrintMargins.LoadFromStream(const AStream: TStream);
begin
with AStream do
begin
Read(FUnitSystem, SizeOf(FUnitSystem));
Read(FLeft, SizeOf(FLeft));
Read(FRight, SizeOf(FRight));
Read(FTop, SizeOf(FTop));
Read(FBottom, SizeOf(FBottom));
Read(FHeader, SizeOf(FHeader));
Read(FFooter, SizeOf(FFooter));
Read(FLeftTextIndent, SizeOf(FLeftTextIndent));
Read(FRightTextIndent, SizeOf(FRightTextIndent));
Read(FInternalMargin, SizeOf(FInternalMargin));
Read(FMargin, SizeOf(FMargin));
Read(FMirrorMargins, SizeOf(FMirrorMargins));
end;
end;
procedure TTextEditorPrintMargins.SaveToStream(const AStream: TStream);
begin
with AStream do
begin
Write(FUnitSystem, SizeOf(FUnitSystem));
Write(FLeft, SizeOf(FLeft));
Write(FRight, SizeOf(FRight));
Write(FTop, SizeOf(FTop));
Write(FBottom, SizeOf(FBottom));
Write(FHeader, SizeOf(FHeader));
Write(FFooter, SizeOf(FFooter));
Write(FLeftTextIndent, SizeOf(FLeftTextIndent));
Write(FRightTextIndent, SizeOf(FRightTextIndent));
Write(FInternalMargin, SizeOf(FInternalMargin));
Write(FMargin, SizeOf(FMargin));
Write(FMirrorMargins, SizeOf(FMirrorMargins));
end;
end;
end.
|
unit UxlRichEdit;
interface
uses Windows, Messages, RichEdit, UxlEdit, UxlClasses, UxlList, UxlWinControl, CommDlg;
type
TTextStruct = record
pText: Pwidechar;
nSize: longint;
StreamIn: boolean;
end;
PTextStruct = ^TTextStruct;
TKeyEvent = function (key: DWORD): boolean of object;
IRichEditDecorator = interface
procedure BeforePaint ();
procedure Paint ();
procedure OnNotify (code, lparam: dword);
procedure EditorRecreated ();
end;
TxlRichEdit = class (TxlEditControl)
private
FProtected: boolean;
FProtectedCount: cardinal;
FUndoLimit: integer;
FAutoIndent: boolean;
FAutoEmptyLine: boolean;
FLeftMargin: cardinal;
FRightMargin: cardinal;
FSmoothScroll: boolean;
FOneClickOpenLink: boolean;
FDecorators: TxlInterfaceList;
FOnContextMenu: TDemandEvent;
FOnKeyDown: TKeyEvent;
FOnKeyPress: TKeyEvent;
FOnLink: TStringEvent;
procedure f_SetUndoLimit (value: integer);
procedure f_SetProtected (value: boolean);
procedure SetLeftMargin (value: cardinal);
procedure SetRightMargin (value: cardinal);
procedure SetScrollPos (value: TPoint);
function GetScrollPos (): TPoint;
procedure SetFirstVisibleLine (value: dword);
function GetFirstVisibleLine (): dword;
protected
function DoCreateControl (HParent: HWND): HWND; override;
procedure OnCreateControl (); override;
procedure ReCreate (); override;
function ProcessMessage (AMessage, wParam, lParam: DWORD): DWORD; override;
function f_GetSelText (): widestring; override;
function GetText (): widestring; override;
procedure SetText (const s_text: widestring); override;
procedure OnFontChange (Sender: TObject); override;
procedure SetColor (i_color: TColor); override;
public
constructor create (WndParent: TxlWinContainer; h_handle: HWND = 0); override;
destructor destroy (); override;
function ProcessNOtify (code: integer; lParam: dword): dword; override;
procedure Redo (); override;
function CanRedo (): boolean; override;
procedure GetSel (var i_start, i_length: integer); override;
procedure SetSel (i_start, i_length: integer); override;
function TextCount (b_withcrlf: boolean = true): cardinal; override;
function GetTextBlock (i_start, i_length: cardinal): widestring;
procedure GetVisibleTextRange (var i_start, i_end: cardinal);
procedure GetCharXY (index: integer; var i_x, i_y: integer);
function GetCharIndex (i_x, i_y: integer): integer;
function TextRect (): TRect;
function LineHeight (): integer;
procedure AddDecorator (value: IRichEditDecorator);
procedure RemoveDecorator (value: IRichEditDecorator);
function CanIndent (): boolean;
procedure Indent (b_indent: boolean = true; s_prefix: widestring = '');
property LeftMargin: cardinal read FLeftMargin write SetLeftMargin;
property RightMargin: cardinal read FRightMargin write SetRightMargin;
property TabStops: integer read FTabStops write f_SetTabStops;
property LineNumber: integer read f_GetLineNumber;
property LineText: widestring read f_GetSelLineText write f_SetSelLineText;
property Lines[index: integer]: widestring read f_GetLine; default;
property UndoLimit: integer read FUndoLimit write f_SetUndoLimit;
property AutoIndent: boolean read FAutoIndent write FAutoIndent;
property AutoEmptyLine: boolean read FAutoEmptyLine write FAutoEmptyLine;
property Protected: boolean read FProtected write f_SetProtected;
property ScrollPos: TPoint read GetScrollPos write SetScrollPos;
property FirstVisibleLine: dword read GetFirstVisibleLine write SetFirstVisibleLine;
property SmoothScroll: boolean read FSmoothScroll write FSmoothScroll;
property OneClickOpenLink: boolean read FOneClickOpenLink write FOneClickOpenLink;
property OnContextMenu: TDemandEvent read FOnContextMenu write FOnContextMenu;
property OnKeyDown: TKeyEvent read FOnKeyDown write FOnKeyDown;
property OnKeyPress: TKeyEvent read FOnKeyPress write FOnKeyPress;
property OnLink: TStringEvent read FOnLink write FOnLink;
end;
function EditStreamCallBack (dwCookie: DWORD; pbBuff: PBYTE; cb: longint; var pcb: longint): dword; stdcall;
implementation
uses SysUtils, UxlFunctions, UxlStrUtils, UxlCommDlgs, UxlMath, UxlWinDef, UxlDateTimeUtils;
constructor TxlRichEdit.create (WndParent: TxlWinContainer; h_handle: HWND = 0);
begin
inherited Create (WndParent, h_handle);
FDecorators := TxlInterfaceList.Create;
end;
destructor TxlRichEdit.destroy ();
begin
FDecorators.free;
inherited;
end;
function TxlRichEdit.DoCreateControl (HParent: HWND): HWND;
var i_style: DWord;
begin
i_Style := ES_LEFT or ES_MULTILINE or ES_AUTOVSCROLL or ES_WANTRETURN or WS_VSCROLL or ES_NOHIDESEL;
if not FWordWrap then i_style := i_style or ES_AUTOHSCROLL or WS_HSCROLL;
result := CreateWin32Control (HParent, 'RichEdit20W', i_style, WS_EX_CLIENTEDGE);
end;
procedure TxlRichEdit.OnCreateControl ();
begin
inherited OnCreateControl;
Perform (EM_SETTEXTMODE, TM_PLAINTEXT, 0);
Perform (EM_AUTOURLDETECT, 1, 0);
Perform (EM_SETEVENTMASK, 0, ENM_SELCHANGE or ENM_Change or ENM_LINK or ENM_SCROLL or ENM_PROTECTED); // or ENM_DROPFILES );
Perform (EM_EXLIMITTEXT, 0, dword(-1));
SetWndProc (@WindowProc);
Redraw;
end;
procedure TxlRichEdit.ReCreate ();
var s_text: widestring;
i: integer;
begin
s_text := Text; // 针对由wordwrap导致的recreate, 此时控件中可能已有文字,执行settextmode可能失败
Text := '';
inherited ReCreate ();
LeftMargin := FLeftMargin;
RightMargin := FRightMargin;
for i := FDecorators.Low to FDecorators.High do
IRichEditDecorator(FDecorators[i]).EditorReCreated ();
Text := s_text;
end;
procedure TxlRichEdit.AddDecorator (value: IRichEditDecorator);
begin
FDecorators.Add(value);
end;
procedure TxlRichEdit.RemoveDecorator (value: IRichEditDecorator);
begin
FDecorators.Remove(value);
end;
procedure TxlRichEdit.Redo ();
begin
Perform (EM_REDO, 0, 0);
end;
function TxlRichEdit.CanRedo (): boolean;
begin
result := (Perform(EM_CANREDO, 0, 0) <> 0);
end;
procedure TxlRichEdit.f_SetUndoLimit (value: integer);
begin
FUndoLimit := value;
Perform (EM_SETUNDOLIMIT, value, 0);
end;
function TxlRichEdit.f_GetSelText (): widestring;
var i_start, i_length: integer;
begin
GetSel (i_start, i_length);
if i_length <= 0 then
result := ''
else
begin
SetLength (result, i_length);
Perform (EM_GETSELTEXT, 0, lparam(pwidechar(result)));
end;
end;
procedure TxlRichEdit.GetSel (var i_start, i_length: integer);
var cr: TCharRange;
begin
Perform (EM_EXGETSEL, 0, lparam(@cr));
i_start := cr.cpMin;
i_length := cr.cpMax - cr.cpMin;
end;
procedure TxlRichEdit.SetSel (i_start, i_length: integer);
var cr: TCharRange;
begin
cr.cpMin := i_start;
cr.cpMax := i_start + i_length;
Perform (EM_EXSETSEL, 0, lparam(@cr));
end;
function TxlRichEdit.TextCount (b_withcrlf: boolean = true): cardinal;
var o_lenex: TGETTEXTLENGTHEX;
begin
o_lenex.flags := GTL_PRECISE or GTL_NUMCHARS;
if b_withcrlf then o_lenex.flags := o_lenex.flags or GTL_USECRLF;
o_lenex.codepage := 1200; // unicode
result := Perform (EM_GETTEXTLENGTHEX, wparam(@o_lenex), 0);
end;
function TxlRichEdit.GetTextBlock (i_start, i_length: cardinal): widestring;
var o_range: TTextRangeW;
begin
SetLength (result, i_length + 1);
o_range.chrg.cpMin := i_start;
o_range.chrg.cpMax := i_start + i_length;
o_range.lpstrText := pwidechar(result);
Perform (EM_GETTEXTRANGE, 0, lparam(@o_range));
result := pwidechar(result);
end;
procedure TxlRichEdit.GetVisibleTextRange (var i_start, i_end: cardinal);
var o_textrect: TRect;
o_point: TPoint;
begin
o_textrect := TextRect;
o_point := RectToPoint (o_textRect);
i_start := Perform (EM_CHARFROMPOS, 0, dword(@o_point));
o_point.x := o_TextRect.right;
o_point.y := o_TextRect.Bottom;
i_end := Perform (EM_CHARFROMPOS, 0, dword(@o_point));
end;
procedure TxlRichEdit.SetLeftMargin (value: cardinal);
begin
FLeftMargin := value;
Perform (EM_SETMARGINS, EC_LEFTMARGIN, MakeLParam(value, 0));
end;
procedure TxlRichEdit.SetRightMargin (value: cardinal);
begin
FRightMargin := value;
Perform (EM_SETMARGINS, EC_RIGHTMARGIN, MakeLParam(0, value));
end;
procedure TxlRichEdit.SetScrollPos (value: TPoint);
begin
value.Y := ConfineRange (value.y, 0, LineCount * LineHeight - textrect.Bottom);
Perform (EM_SETSCROLLPOS, 0, lparam(@value));
end;
function TxlRichEdit.GetScrollPos (): TPoint;
begin
Perform (EM_GETSCROLLPOS, 0, lparam(@result));
end;
procedure TxlRichEdit.SetFirstVisibleLine (value: dword);
begin
SetSel (0, 0);
Perform ( EM_GETLINECOUNT, 0, 0 ); // 无此句,在载入文字后恢复滚动位置会出问题,可能是因为文字未载入完全系统就尝试滚动的缘故
Perform (EM_LINESCROLL, 0, value);
end;
function TxlRichEdit.GetFirstVisibleLine (): dword;
begin
result := Perform (EM_GETFIRSTVISIBLELINE, 0, 0);
end;
function TxlRichEdit.TextRect (): TRect;
begin
Perform (EM_GETRECT, 0, dword(@result));
end;
procedure TxlRichEdit.GetCharXY (index: integer; var i_x, i_y: integer);
var o_point: TPoint;
begin
Perform (EM_POSFROMCHAR, dword(@o_point), index);
i_x := o_point.X;
i_y := o_point.y;
end;
function TxlRichEdit.GetCharIndex(i_x, i_y: integer): integer;
var o_point: TPoint;
begin
o_point.x := i_x;
o_point.y := i_y;
result := Perform (EM_CHARFROMPOS, 0, dword(@o_point));
end;
function TxlRichEdit.LineHeight (): integer;
var i, j, k: integer;
begin
GetCharXY (0, k, i);
GetCharXY (f_GetLineCharIndex(1), k, j);
result := j - i;
if result <= 0 then
result := -1 * Font.Height;
end;
type PEnLink = ^TEnLink;
function TxlRichEdit.ProcessNotify (code: integer; lParam: dword): dword;
var p: PEnLink;
s: widestring;
i, n: integer;
enp: TENPROTECTED;
begin
result := 0;
case code of
EN_SelChange, EN_Change:
begin
f_OnChange;
for i := FDecorators.Low to FDecorators.High do
IRichEditDecorator(FDecorators[i]).OnNotify (code, lparam);
end;
EN_LINK:
begin
p := PEnLink(lParam);
if (p^.msg = WM_LBUTTONDBLCLK) or ((p^.msg = WM_LBUTTONDOWN) and (FOneClickOpenLink or KeyPressed(VK_CONTROL))) then
begin
s := GetTextBlock (p^.chrg.cpMin, p^.chrg.cpMax - p^.chrg.cpMin);
if assigned (FOnLink) then
FOnLink (s)
else
try
ExecuteLink (s);
except
end;
end;
end;
EN_PROTECTED:
begin
if not FProtected then exit;
enp := PENPROTECTED(lparam)^;
n := FProtectedCount;
if (enp.msg = WM_KEYDOWN) and (enp.wParam = VK_BACK) then
inc (n);
result := ifThen ( enp.chrg.cpMin < n, 1, 0);
end;
else
result := inherited ProcessNotify (code, lparam);
end;
end;
//---------------------
procedure TxlRichEdit.SetColor (i_color: TColor);
begin
inherited SetColor (i_color);
Perform (EM_SETBKGNDCOLOR, 0, i_color);
end;
procedure TxlRichEdit.OnFontChange (Sender: TObject);
var n: integer;
FCharFormat: TCharFormatW;
s_name: widestring;
begin
with FCharFormat do
begin
cbSize := sizeof (FCharFormat);
dwMask := CFM_BOLD or CFM_COLOR or CFM_ITALIC or CFM_SIZE or CFM_STRIKEOUT or CFm_UNDERLINE or CFM_FACE or CFM_OFFSET or CFM_PROTECTED;
dwEffects := 0;
if font.bold then
dwEffects := dwEffects or CFE_BOLD;
if font.italic then dwEffects := dwEffects or CFE_ITALIC;
if font.strikeout then dwEffects := dwEffects or CFE_STRIKEOUT;
if font.underline then dwEffects := dwEffects or CFE_UNDERLINE;
if FProtected then dwEffects := dwEffects or CFE_PROTECTED;
// bCharSet := DEFAULT_CHARSET; // 千万不能用!!!
yHeight := font.size * 20;
crTextColor := font.Color;
yOffset := 0;
// bPitchAndFamily := o_logfont.lfPitchAndFamily;
end;
s_name := Font.Name;
n := length(s_name)+1;
copymemory (@FCharFormat.szFaceName, pwidechar(s_name), n*2);
Perform (EM_SETCHARFORMAT, SCF_ALL, lparam(@FCharFormat));
end;
procedure TxlRichEdit.f_SetProtected (value: boolean);
begin
FProtected := value;
if value then
FProtectedCount := TextCount (false)
else
FProtectedCount := 0;
OnFontChange (self); // 不可省略!
end;
function TxlRichEdit.CanIndent (): boolean;
begin
result := IsSubStr (#13, SelText);
end;
procedure TxlRichEdit.Indent (b_indent: boolean = true; s_prefix: widestring = '');
var s: widestring;
i_start, i_len, i_start2, i_line, i_pos, n, i_prefixlen: integer;
b_numberprefix: boolean;
begin
s := SelText;
b_numberprefix := s_prefix = '';
GetSel (i_start, i_len);
i_line := Perform (EM_LINEFROMCHAR, i_start, 0);
i_start2 := Perform (EM_LINEINDEX, i_line, 0);
if i_start > i_start2 then
begin
inc (i_len, i_start - i_start2);
i_start := i_start2;
SetSel (i_start, i_len);
s := SelText;
end;
if i_start = i_start2 then
i_pos := 1
else
i_pos := FirstPos (#13, s) + 1;
n := 0;
while InRange (i_pos, 1, i_len) do
begin
inc (n);
if (n > 1) and (i_pos = 1) then break;
if b_numberprefix then
begin
s_prefix := IntToStr(n) + '. ';
end;
i_prefixlen := Length(s_prefix);
while (i_pos < i_len) and (Ord(s[i_pos]) <= 32) do
inc (i_pos);
if b_indent then
begin
Insert (s, i_pos, s_prefix);
inc (i_len, i_prefixlen);
end
else
begin
if MidStr(s, i_pos, i_prefixlen) = s_prefix then
begin
Delete (s, i_pos, i_prefixlen);
dec (i_len, i_prefixlen);
end
else if (i_pos > 1) and (i_prefixlen = 1) and (Ord(s_prefix[1]) <= 32) and (Ord(s[i_pos - 1]) <= 32) and (Ord(s[i_pos - 1]) <> 13) then // shift_tab 时连空格等一并回撤
begin
dec (i_pos);
Delete (s, i_pos, 1);
dec (i_len, 1);
end;
end;
i_pos := FirstPos (#13, s, i_pos) + 1;
end;
SelText := s;
SetSel (i_start, i_len);
end;
function TxlRichEdit.ProcessMessage (AMessage, wParam, lParam: DWORD): DWORD;
var i, n: integer;
s: widestring;
b, b_processed: boolean;
i_time: Int64;
begin
result := 0;
b_processed := false;
case AMessage of
WM_KEYDOWN:
begin
if assigned (FOnKeyDown) and FOnKeyDown (wParam) then
b_processed := true
else if wParam = VK_RETURN then
begin
if FAutoIndent then s := LineText;
result := inherited ProcessMessage (WM_KeyDown, WParam, LParam);
if FAutoEmptyLine then
inherited ProcessMessage (WM_KeyDown, WParam, LParam);
if s = '' then exit;
i := 1;
n := length(s);
while (i <= n) and ((s[i] = #9) or (s[i] = #32)) or (s[i] = ' ') do // 包含中文空格
begin
Perform (WM_CHAR, dword(s[i]), 0);
inc (i);
end;
b_processed := true;
end;
end;
WM_CHAR:
if (wparam = 9) and CanIndent then
begin
Indent (not KeyPressed(VK_SHIFT), #9);
b_processed := true;
end
else if assigned (FOnKeyPress) then
b_processed := FOnKeyPress (wParam);
WM_CONTEXTMENU:
if assigned (FOnContextMenu) then
begin
i_time := SystemTimeToInt64 (Now, ittMilliSecond);
result := inherited ProcessMessage (AMessage, WParam, LParam);
if SystemTimeToInt64 (Now, ittMilliSecond) - i_time <= 100 then // 并未弹出系统本身的默认菜单。针对scrollbar
FOnContextMenu (self);
b_processed := true;
end;
WM_MBUTTONDOWN:
if (wparam and MK_CONTROL) <> 0 then // ctrl+中键单击:撤销 zoom
begin
Post (EM_SETZOOM, 0, 0);
b_processed := true;
end;
WM_MOUSEWHEEL:
if not (KeyPressed(VK_CONTROL) or SmoothScroll) then
begin
b_processed := true;
b := GetWheelDelta (wParam) > 0;
for i := 0 to 2 do
Perform (WM_VSCROLL, IfThen (b, SB_LINEUP, SB_LINEDOWN), 0);
END;
WM_PAINT:
begin
for i := FDecorators.Low to FDecorators.High do
IRichEditDecorator(FDecorators[i]).BeforePaint;
result := inherited ProcessMessage (AMessage, WParam, LParam);
for i := FDecorators.Low to FDecorators.High do
IRichEditDecorator(FDecorators[i]).Paint;
b_processed := true;
// ValidateRect (Fhandle, nil);
end;
end;
if not b_processed then
result := inherited ProcessMessage (AMessage, WParam, LParam);
end;
//------------------
function TxlRichEdit.GetText (): widestring;
var es: EditStream;
ess: TTextStruct;
i_len: integer;
begin
i_len := TextLength;
setlength (result, i_len);
ess.pText := pwidechar(result);
ess.nSize := i_len * 2;
ess.StreamIn := false;
with es do
begin
dwCookie := dword(@ess);
dwError := 0;
pfnCallback := @EditStreamCallback;
end;
Perform (EM_STREAMOUT, SF_TEXT or SF_UNICODE, LParam(@es));
end;
procedure TxlRichEdit.SetText (const s_text: widestring);
var es: EditStream;
ess: TTextStruct;
b: boolean;
begin
b := Protected;
FProtected := false;
ess.pText := pwidechar(s_text);
ess.nSize := length(s_text) * 2;
ess.streamIn := true;
with es do
begin
dwCookie := dword(@ess);
dwError := 0;
pfnCallback := @EditStreamCallback;
end;
SetRedraw (false);
Perform (EM_SETTEXTMODE, TM_PLAINTEXT, 0);
Perform (EM_STREAMIN, SF_TEXT or SF_UNICODE, LParam(@es));
SetRedraw (true);
FProtected := b;
end;
function EditStreamCallBack (dwCookie: DWORD; pbBuff: PBYTE; cb: longint; var pcb: longint): dword; stdcall;
var pess: PTextStruct;
begin
pess := PTextStruct(dwCookie);
if cb > pess^.nSize then
pcb := pess^.nSize
else
pcb := (cb div 2) * 2;
if pcb > 0 then
begin
if pess^.StreamIn then
copymemory (pbBuff, pess^.pText, pcb)
else
copymemory (pess^.pText, pbbuff, pcb);
inc (pess^.pText, pcb div 2);
dec (pess^.nSize, pcb);
end;
result := 0;
end;
//------------------
var Riched20: HModule;
initialization
Riched20 := LoadLibraryW ('riched20.dll');
finalization
FreeLibrary (Riched20);
end.
// procedure SetSelColor (i_color: TColor); // 需要把PlainText风格去除才能生效。如需实现语法高亮,实现OnPaint事件,在事件代码中逐个SetSelColor即可。
//procedure TxlRichEdit.SetSelColor (i_color: TColor);
//var FCharFormat: TCharFormatW;
//begin
// with FCharFormat do
// begin
// cbSize := sizeof (FCharFormat);
// dwMask := CFM_COLOR;
// dwEffects := 0;
// crTextColor := i_color;
// end;
// Perform (EM_SETCHARFORMAT, SCF_SELECTION, dword(@FCharFormat));
//end;
|
unit ufrmMaintenancePassword;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, ActnList, uConn, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus,
ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxLabel, cxGridLevel, cxClasses, cxGridCustomView, System.Actions,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC;
type
TfrmMaintenancePassword = class(TfrmMasterBrowse)
procedure actAddExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
private
dataUser: TDataSet;
procedure OverridePrivileges;
procedure ParseHeaderGrid(jmlData: Integer);
procedure ParseDataGrid();
procedure PrepareEdit();
public
{ Public declarations }
end;
var
frmMaintenancePassword: TfrmMaintenancePassword;
implementation
uses ufrmDialogMaintenancePassword, uTSCommonDlg;
{$R *.dfm}
procedure TfrmMaintenancePassword.actAddExecute(Sender: TObject);
begin
inherited;
if not assigned(frmDialogMaintenancePassword) then
Application.CreateForm(TfrmDialogMaintenancePassword, frmDialogMaintenancePassword);
frmDialogMaintenancePassword.Caption := 'Add Cashier';
frmDialogMaintenancePassword.FormMode := fmAdd;
SetFormPropertyAndShowDialog(frmDialogMaintenancePassword);
if (frmDialogMaintenancePassword.IsProcessSuccessfull) then
begin
actRefreshExecute(Self);
CommonDlg.ShowConfirmSuccessfull(atAdd);
end;
frmDialogMaintenancePassword.Free;
end;
procedure TfrmMaintenancePassword.PrepareEdit();
begin
{frmDialogMaintenancePassword.edtUserName.Text := strgGrid.Cells[1,strgGrid.Row];
frmDialogMaintenancePassword.edtFullname.Text := strgGrid.Cells[2,strgGrid.Row];
If strgGrid.Cells[7,strgGrid.Row] = '11' then
frmDialogMaintenancePassword.cbbLevel.ItemIndex := 1
else
frmDialogMaintenancePassword.cbbLevel.ItemIndex := 0;
if strgGrid.Cells[4,strgGrid.Row] = 'ACTIVE' then
frmDialogMaintenancePassword.chkStatus.Checked := True
else
frmDialogMaintenancePassword.chkStatus.Checked := False;
frmDialogMaintenancePassword.edtPasswd.Text := strgGrid.Cells[5,strgGrid.Row];
frmDialogMaintenancePassword.User_ID := StrToInt(strgGrid.Cells[6,strgGrid.Row]);
}
end;
procedure TfrmMaintenancePassword.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmMaintenancePassword.FormCreate(Sender: TObject);
begin
inherited;
lblHeader.Caption := 'CASHIER AND PASSWORD MAINTENANCE';
ParseDataGrid;
end;
procedure TfrmMaintenancePassword.FormDestroy(Sender: TObject);
begin
inherited;
frmMaintenancePassword := nil;
end;
procedure TfrmMaintenancePassword.ParseDataGrid;
var intI: Integer;
begin
{if not Assigned(MaintenancePasswd) then MaintenancePasswd := TMaintenancePasswd.Create;
dataUser := MaintenancePasswd.GetListDataMaintenancePasswd(masternewunit.id);
ParseHeaderGrid(dataUser.RecordCount);
if dataUser.RecordCount > 0 then
begin
//initiate
intI := 1;
dataUser.First;
while not(dataUser.Eof) do
begin
with strgGrid do
begin
Cells[0,intI] := IntToStr(intI) + '.';
Cells[1,intI] := dataUser.FieldByName('USR_USERNAME').AsString;
Cells[2,intI] := dataUser.FieldByName('USR_FULLNAME').AsString;
Cells[3,intI] := dataUser.FieldByName('GRO_NAME').AsString;
if dataUser.FieldByName('USR_STATUS').AsInteger = 1 then
Cells[4,intI] := 'ACTIVE'
else Cells[4,intI] := 'NOT ACTIVE';
Cells[5,intI] := dataUser.FieldByName('USR_PASSWD').AsString;
Cells[6,intI] := dataUser.FieldByName('USR_ID').AsString;
Cells[7,intI] := dataUser.FieldByName('UG_GRO_ID').AsString;
AutoSize := true;
end; //end with strggrid
dataUser.Next;
Inc(intI);
end;// end while not eof
end; //end if recordcount
strgGrid.AutoSize := true;
strgGrid.FixedRows := 1;
}
end;
procedure TfrmMaintenancePassword.ParseHeaderGrid(jmlData: Integer);
begin
{ with strgGrid do
begin
Clear;
RowCount := jmlData + 1;
ColCount := 5;
Cells[0,0] := 'NO.';
Cells[1,0] := 'CASHIER ID';
Cells[2,0] := 'FULLNAME';
Cells[3,0] := 'CASHIER LEVEL';
Cells[4,0] := 'STATUS';
if jmlData < 1 then
begin
RowCount := 2;
Cells[0,1] := ' ';
Cells[1,1] := ' ';
Cells[2,1] := ' ';
Cells[3,1] := ' ';
Cells[4,1] := ' ';
Cells[5,1] := '0';
end;
FixedRows := 1;
AutoSize := true;
end;
}
end;
procedure TfrmMaintenancePassword.actEditExecute(Sender: TObject);
begin
inherited;
{if strgGrid.Cells[5,strgGrid.Row] = '0' then Exit;
if not assigned(frmDialogMaintenancePassword) then
Application.CreateForm(TfrmDialogMaintenancePassword, frmDialogMaintenancePassword);
frmDialogMaintenancePassword.Caption := 'Edit Cashier';
frmDialogMaintenancePassword.FormMode := fmEdit;
PrepareEdit();
SetFormPropertyAndShowDialog(frmDialogMaintenancePassword);
if (frmDialogMaintenancePassword.IsProcessSuccessfull) then
begin
actRefreshExecute(Self);
CommonDlg.ShowConfirmSuccessfull(atEdit);
end;
frmDialogMaintenancePassword.Free;
}
end;
procedure TfrmMaintenancePassword.actRefreshExecute(Sender: TObject);
begin
inherited;
ParseDataGrid();
end;
procedure TfrmMaintenancePassword.FormShow(Sender: TObject);
begin
inherited;
OverridePrivileges;
end;
procedure TfrmMaintenancePassword.OverridePrivileges;
begin
//method ini utk override property bottom panel
//karena versi ori aplikasi dikontrol dari user module di HO
actAdd.Enabled := True;
actEdit.Enabled := True;
actPrint.Enabled := True;
actRefresh.Enabled := True;
end;
end.
|
unit uCadastroDeParaCanal;
interface
uses
System.IOUtils,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, dxSkinsCore,
dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxCheckBox,
cxContainer, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxLabel, dxGDIPlusClasses, Vcl.ExtCtrls, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, dxSkinOffice2013White,
dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee,
dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast,
dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky,
dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray,
dxSkinOffice2013LightGray, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic,
dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters,
dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue;
type
TFr_CadastroDeParaCanal = class(TForm)
cxGridDeParaCanal: TcxGrid;
cxGridLevelDeParaCanal: TcxGridLevel;
cxTableViewDeParaCanal: TcxGridDBTableView;
DataSourceTSOP_DeParaCanal: TDataSource;
FDConnection: TFDConnection;
FDQueryTSOP_DeParaCanal: TFDQuery;
PanelSQLSplashScreen: TPanel;
ImageSQLSplashScreen: TImage;
cxLabelMensagem: TcxLabel;
FDQueryTSOP_DeParaCanalTSOP_DPACANCOD: TFDAutoIncField;
FDQueryTSOP_DeParaCanalTSOP_ORICOD: TIntegerField;
FDQueryTSOP_DeParaCanalTSOP_DPACANTXTANT: TStringField;
FDQueryTSOP_DeParaCanalTSOP_DPACANTXTDEP: TStringField;
FDQueryTSOP_DeParaCanalTSOP_USUCODCAD: TIntegerField;
FDQueryTSOP_DeParaCanalTSOP_DPACANDATCAD: TSQLTimeStampField;
FDQueryTSOP_DeParaCanalTSOP_USUCODALT: TIntegerField;
FDQueryTSOP_DeParaCanalTSOP_DPACANDATALT: TSQLTimeStampField;
cxTableViewDeParaCanalTSOP_DPACANCOD: TcxGridDBColumn;
cxTableViewDeParaCanalTSOP_DPACANTXTANT: TcxGridDBColumn;
cxTableViewDeParaCanalTSOP_DPACANTXTDEP: TcxGridDBColumn;
FDQueryTSOP_DeParaCanalTSOP_DPACANTIPTXT: TStringField;
cxTableViewDeParaCanalTSOP_DPACANTIPTXT: TcxGridDBColumn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
procedure FormCreate(Sender: TObject);
procedure FDQueryTSOP_DeParaCanalNewRecord(DataSet: TDataSet);
procedure FDQueryTSOP_DeParaCanalAfterEdit(DataSet: TDataSet);
private
procedure Mensagem( pMensagem: String );
{ Private declarations }
public
procedure AbrirDataset;
procedure LoadGridCustomization;
{ Public declarations }
end;
var
Fr_CadastroDeParaCanal: TFr_CadastroDeParaCanal;
implementation
{$R *.dfm}
uses uUtils, uBrady;
procedure TFr_CadastroDeParaCanal.AbrirDataset;
begin
if not FDConnection.Connected then
begin
Mensagem( 'Abrindo conex„o...' );
try
FDConnection.Params.LoadFromFile( MyDocumentsPath + '\DB.ini' );
FDConnection.Open;
Mensagem( 'Obtendo dados (De/Para Canal)...' );
FDQueryTSOP_DeParaCanal.Open;
finally
Mensagem( EmptyStr );
end;
end;
end;
procedure TFr_CadastroDeParaCanal.FDQueryTSOP_DeParaCanalAfterEdit(DataSet: TDataSet);
begin
FDQueryTSOP_DeParaCanalTSOP_ORICOD.AsInteger := 1;
FDQueryTSOP_DeParaCanalTSOP_USUCODALT.AsInteger := 1;
FDQueryTSOP_DeParaCanalTSOP_DPACANDATALT.AsDateTime := Now;
end;
procedure TFr_CadastroDeParaCanal.FDQueryTSOP_DeParaCanalNewRecord(DataSet: TDataSet);
begin
FDQueryTSOP_DeParaCanalTSOP_ORICOD.AsInteger := 1;
FDQueryTSOP_DeParaCanalTSOP_DPACANTIPTXT.AsString := 'S';
FDQueryTSOP_DeParaCanalTSOP_USUCODCAD.AsInteger := 1;
FDQueryTSOP_DeParaCanalTSOP_USUCODALT.AsInteger := 1;
FDQueryTSOP_DeParaCanalTSOP_DPACANDATCAD.AsDateTime := Now;
FDQueryTSOP_DeParaCanalTSOP_DPACANDATALT.AsDateTime := Now;
end;
procedure TFr_CadastroDeParaCanal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FDQueryTSOP_DeParaCanal.Close;
FDConnection.Close;
Fr_CadastroDeParaCanal := nil;
Action := caFree;
end;
procedure TFr_CadastroDeParaCanal.FormContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
begin
Fr_Brady.PopupGridTools( cxGridDeParaCanal.ActiveView );
end;
procedure TFr_CadastroDeParaCanal.FormCreate(Sender: TObject);
begin
LoadGridCustomization;
end;
procedure TFr_CadastroDeParaCanal.LoadGridCustomization;
begin
if System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + Name + '_' + cxTableViewDeParaCanal.Name + '.ini' ) then
cxTableViewDeParaCanal.RestoreFromIniFile( MyDocumentsPath + '\' + Name + '_' + cxTableViewDeParaCanal.Name + '.ini' );
end;
procedure TFr_CadastroDeParaCanal.Mensagem(pMensagem: String);
begin
cxLabelMensagem.Caption := pMensagem;
PanelSQLSplashScreen.Visible := not pMensagem.IsEmpty;
Update;
Application.ProcessMessages;
end;
end.
|
unit SQLProducerTest;
interface
uses
Classes, SysUtils, TestFramework,
DatabaseDefinition, SQLProducer;
type
TSQLProducerTest = class (TTestCase)
protected
function CreateDatabaseDefinition: TDatabaseDefinition;
published
procedure TestInsertStatement;
procedure TestUpdateStatement;
procedure TestExistsStatement;
procedure TestDeleteStatement;
procedure TestLastIdStatement;
end;
implementation
{ TSQLProducerTest }
{ Protected declarations }
type
TTestRec = packed record
Id: Integer;
Kind: Word;
Name: array[0..79] of Char;
end;
function TSQLProducerTest.CreateDatabaseDefinition: TDatabaseDefinition;
begin
Result := TDatabaseDefinition.Create;
Result.Tables.Add(TTable.Create);
Result.Tables[0].Name := 'Test';
Result.Tables[0].FileName := 'Test.rtm';
Result.Tables[0].Fields.Add(TField.Create);
Result.Tables[0].Fields[0].Name := 'Id';
Result.Tables[0].Fields[0].DataType := dtInteger;
Result.Tables[0].Fields[0].Size := 4;
Result.Tables[0].Fields[0].Offset := 0;
Result.Tables[0].Fields[0].IncludedInSQL := True;
Result.Tables[0].Fields[0].IsPrimaryKey := True;
Result.Tables[0].Fields.Add(TField.Create);
Result.Tables[0].Fields[1].Name := 'Kind';
Result.Tables[0].Fields[1].DataType := dtInteger;
Result.Tables[0].Fields[1].Size := 2;
Result.Tables[0].Fields[1].Offset := 4;
Result.Tables[0].Fields[1].IncludedInSQL := False;
Result.Tables[0].Fields[1].IsPrimaryKey := False;
Result.Tables[0].Fields.Add(TField.Create);
Result.Tables[0].Fields[2].Name := 'Name';
Result.Tables[0].Fields[2].DataType := dtChar;
Result.Tables[0].Fields[2].Size := 80;
Result.Tables[0].Fields[2].Offset := 6;
Result.Tables[0].Fields[2].IncludedInSQL := True;
Result.Tables[0].Fields[2].IsPrimaryKey := False;
end;
{ Published declarations }
procedure TSQLProducerTest.TestInsertStatement;
const
EXPECTED = 'INSERT INTO TEST (ID, NAME) VALUES (10, ''Hello, world!'');';
DATA: TTestRec = (Id: 10; Kind: 123; Name: 'Hello, world!');
begin
{$WARNINGS OFF}
with TSQLProducer.Create do
{$WARNINGS ON}
try
with CreateDatabaseDefinition do
try
CheckEquals(EXPECTED, Insert(Tables[0], @Data));
finally
Free;
end;
finally
Free;
end;
end;
procedure TSQLProducerTest.TestUpdateStatement;
const
EXPECTED = 'UPDATE TEST SET NAME = ''Hello, world!'' WHERE ID = 10';
DATA: TTestRec = (Id: 10; Kind: 123; Name: 'Hello, world!');
begin
{$WARNINGS OFF}
with TSQLProducer.Create do
{$WARNINGS ON}
try
with CreateDatabaseDefinition do
try
CheckEquals(EXPECTED, Update(Tables[0], @Data));
finally
Free;
end;
finally
Free;
end;
end;
procedure TSQLProducerTest.TestExistsStatement;
const
EXPECTED = 'SELECT COUNT(*) FROM TEST WHERE ID = 10;';
DATA: TTestRec = (Id: 10; Kind: 123; Name: 'Hello, world!');
begin
{$WARNINGS OFF}
with TSQLProducer.Create do
{$WARNINGS ON}
try
with CreateDatabaseDefinition do
try
CheckEquals(EXPECTED, Exists(Tables[0], @Data));
finally
Free;
end;
finally
Free;
end;
end;
procedure TSQLProducerTest.TestDeleteStatement;
const
EXPECTED = 'DELETE FROM TEST WHERE ID = 10;';
DATA: TTestRec = (Id: 10; Kind: 123; Name: 'Hello, world!');
begin
{$WARNINGS OFF}
with TSQLProducer.Create do
{$WARNINGS ON}
try
with CreateDatabaseDefinition do
try
CheckEquals(EXPECTED, Delete(Tables[0], @Data));
finally
Free;
end;
finally
Free;
end;
end;
procedure TSQLProducerTest.TestLastIdStatement;
const
EXPECTED = 'SELECT MAX(ID) FROM TEST;';
begin
{$WARNINGS OFF}
with TSQLProducer.Create do
{$WARNINGS ON}
try
with CreateDatabaseDefinition do
try
CheckEquals(EXPECTED, LastId(Tables[0]));
finally
Free;
end;
finally
Free;
end;
end;
initialization
RegisterTest(TSQLProducerTest.Suite);
end.
|
(*
MIT License
Copyright (c) 2016 Ean Smith
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*)
(*******************************************************************************
Purpose:
Sample project for delphi (Berlin 10.1) demonstrating a use case for the POS library
----------------------------------------------------
dd.mm.yy - initials - note
----------------------------------------------------
11.26.16 - ems - created
*******************************************************************************)
unit umain_sample_1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,WIZ.POS,
FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls;
type
/// <summary>
/// Just a testing class for the library making sure everything compiles ok
/// and the core features return as expected.
/// </summary>
TTestStuff = class(TCustomStuff)
strict private
//a buffer to hold some text
FTestBuffer : TStringList;
protected
/// <summary>
/// here we override the DoClassify to look at some buffer of strings.
/// As long as there is some text in the buffer,
/// </summary>
function DoClassify(out Error: String): Boolean; override;
public
procedure AddSomeTestText(Const ATest:String);
constructor Create; override;
destructor Destroy; override;
end;
Tmain_sample_1 = class(TForm)
Btn_Add: TButton;
Memo_Add: TMemo;
Btn_Classify: TButton;
Memo_Classify: TMemo;
procedure Btn_AddClick(Sender: TObject);
procedure Btn_ClassifyClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FTestStuff: TTestStuff;
{ Private declarations }
public
{ Public declarations }
end;
var
main_sample_1: Tmain_sample_1;
implementation
{$R *.fmx}
function TTestStuff.DoClassify(out Error: String): Boolean;
begin
Result:=False;
//as long as we have a string in our list, then we are good, otherwise not
if FTestBuffer.Count<1 then
Begin
Error:='the buffer has no text to classify with';
Exit;
end;
while FTestBuffer.Count>0 do
Begin
if not AddAttribute(FTestBuffer[0],Error) then
Exit;
FTestBuffer.Delete(0);
end;
Result:=True;
end;
procedure TTestStuff.AddSomeTestText(const ATest: String);
begin
//clears our attribute list (reset basically)
IsClassified:=False;
//add some string to our buffer
FTestBuffer.Add(ATest);
end;
constructor TTestStuff.Create;
begin
inherited Create;
FTestBuffer:=TStringList.Create;
end;
destructor TTestStuff.Destroy;
begin
FTestBuffer.Free;
inherited Destroy;
end;
procedure Tmain_sample_1.Btn_AddClick(Sender: TObject);
var
I: Integer;
begin
for I := 0 to Pred(Memo_Add.Lines.Count) do
FTestStuff.AddSomeTestText(Memo_Add.Lines[i]);
end;
procedure Tmain_sample_1.Btn_ClassifyClick(Sender: TObject);
var
LError: String;
begin
if not FTestStuff.Classify(LError) then
Memo_Classify.Text:=LError
else
Memo_Classify.Text:=BoolToStr(FTestStuff.IsClassified,True);
end;
procedure Tmain_sample_1.FormCreate(Sender: TObject);
begin
FTestStuff:=TTestStuff.Create;
end;
procedure Tmain_sample_1.FormDestroy(Sender: TObject);
begin
FTestStuff.Free;
end;
end.
|
unit AreaFix;
/////////////////////////////////////////////////////////////////////
//
// Hi-Files Version 2
// Copyright (c) 1997-2004 Dmitry Liman [2:461/79]
//
// http://hi-files.narod.ru
//
/////////////////////////////////////////////////////////////////////
interface
procedure RunAreaFix;
{ =================================================================== }
implementation
uses
Objects, SysUtils, MyLib, _CFG, _LOG, _Res, _FAreas, _Tic, MsgAPI, _MapFile;
{ --------------------------------------------------------- }
{ UnlinkAll }
{ --------------------------------------------------------- }
procedure UnlinkAll( Echo: PFileEcho; MsgBase: PMsgBase );
var
todo: PAddrList;
procedure Copy( A: PAddress ); far;
var
j: Integer;
begin
if not todo^.Search( A, j ) then
todo^.AtInsert( j, NewAddr(A^) );
end; { Copy }
procedure Unlink( A: PAddress ); far;
var
M: PNetmailMessage;
Link: PEcholink;
begin
Link := CFG^.Links^.Find( A^ );
M := MsgBase^.NewMessage;
try
with M^ do
begin
SetOrig( Link^.OurAka );
SetFrom( PROG_NAME );
SetDest( A^ );
SetTo ( 'Allfix' );
SetSubj( Link^.Password^ );
case Link^.Flavor of
fl_Hold : SetAttr( ATTR_LOCAL or ATTR_HOLD );
fl_Dir : SetAttr( ATTR_LOCAL or ATTR_DIR );
fl_Imm : SetAttr( ATTR_LOCAL or ATTR_IMM );
fl_Crash: SetAttr( ATTR_LOCAL or ATTR_CRASH );
end;
Append( '-' + Echo^.Name^ );
Append( TEARLINE );
Save;
end;
finally
Destroy( M );
end;
end; { Unlink }
begin
New( todo, Init(50, 50) );
with Echo^ do
begin
Uplinks^.ForEach( @Copy );
Uplinks^.FreeAll;
Downlinks^.ForEach( @Copy );
Downlinks^.FreeAll;
end;
todo^.ForEach( @Unlink );
Destroy( todo );
end; { UnlinkAll }
{ --------------------------------------------------------- }
{ HandleMessage }
{ --------------------------------------------------------- }
procedure HandleMessage( IM: PNetmailMessage; MsgBase: PMsgBase );
const
AWAITING_STATE = ' ...awaiting';
DOWN_STATE = ' ...down';
var
OM : PNetmailMessage;
Link: PEchoLink;
procedure SendHelp;
var
S: String;
Map: TMappedFile;
begin
if (CFG^.AllfixHelp <> '') and FileExists(CFG^.AllfixHelp) then
begin
Log^.Write( ll_Protocol, Format(LoadString(_SLogSendingHelp), [CFG^.AllfixHelp]) );
Map.Init( CFG^.AllfixHelp );
while Map.GetLine( S ) do
OM^.Append( S );
Map.Done;
end
else
begin
Log^.Write( ll_Warning, Format(LoadString(_SLogHelpNotAvail), [CFG^.AllfixHelp]));
OM^.Append( LoadString(_SReplyHelpNotAvail) );
end;
end; { SendHelp }
procedure SendList;
const
EMPTY = '-- ';
var
j: Integer;
n: Integer;
w: Integer;
S: String;
Echo: PFileEcho;
procedure CalcWidth( Echo: PFileEcho ); far;
begin
if Length(Echo^.Name^) > w then
w := Length(Echo^.Name^);
end; { CalcWidth }
begin
Log^.Write( ll_Protocol, LoadString(_SLogSendingEchoList) );
OpenFileBase;
w := 0;
FileBase^.EchoList^.ForEach( @CalcWidth );
n := 0;
for j := 0 to Pred( FileBase^.EchoList^.Count ) do
begin
Echo := FileBase^.EchoList^.At( j );
S := EMPTY;
if Echo^.Downlinks^.IndexOf( @Link^.Addr ) >= 0 then
S[1] := 'R';
if Echo^.Uplinks^.IndexOf( @Link^.Addr ) >= 0 then
S[2] := 'W';
if S <> EMPTY then Inc( n );
S := S + Pad(Echo^.Name^, w);
case Echo^.State of
es_Awaiting: S := S + AWAITING_STATE;
es_Down : S := S + DOWN_STATE;
end;
OM^.Append( S );
end;
OM^.Append( '' );
for j := 0 to 5 do
OM^.Append( LoadString(_SAfixReplyRW + j) );
OM^.Append( '' );
OM^.Append( Format(LoadString(_SReplyListFooter),
[FileBase^.EchoList^.Count, n] ));
if elo_Pause in Link^.Opt then
OM^.Append( LoadString(_SPauseWarning) );
end; { SendList }
procedure SendQuery;
const
EMPTY = '-- ';
var
j: Integer;
n: Integer;
w: Integer;
S: String;
Echo: PFileEcho;
procedure CalcWidth( Echo: PFileEcho ); far;
var
j: Integer;
begin
if Echo^.Downlinks^.Search( @Link^.Addr, j ) or Echo^.Uplinks^.Search( @Link^.Addr, j ) then
begin
if Length(Echo^.Name^) > w then
w := Length(Echo^.Name^);
end;
end; { CalcWidth }
begin
Log^.Write( ll_Protocol, LoadString(_SLogSendingEchoQuery) );
OpenFileBase;
w := 0;
FileBase^.EchoList^.ForEach( @CalcWidth );
n := 0;
for j := 0 to Pred( FileBase^.EchoList^.Count ) do
begin
Echo := FileBase^.EchoList^.At( j );
S := EMPTY;
if Echo^.Downlinks^.IndexOf( @Link^.Addr ) >= 0 then
S[1] := 'R';
if Echo^.Uplinks^.IndexOf( @Link^.Addr ) >= 0 then
S[2] := 'W';
if S <> EMPTY then
begin
Inc( n );
S := S + Pad(Echo^.Name^, w);
case Echo^.State of
es_Awaiting: S := S + AWAITING_STATE;
es_Down : S := S + DOWN_STATE;
end;
OM^.Append( S );
end;
end;
OM^.Append( '' );
for j := 0 to 5 do
OM^.Append( LoadString(_SAfixReplyRW + j) );
OM^.Append( '' );
OM^.Append( Format(LoadString(_SReplyQueryFooter), [n] ));
if elo_Pause in Link^.Opt then
OM^.Append( LoadString(_SPauseWarning) );
end; { SendQuery }
procedure SendAvail;
procedure Write( P: PString ); far;
begin
OM^.Append( P^ );
end; { Write }
procedure WriteList( AR: PAvailRec ); far;
begin
if not (ao_Inactive in AR^.Opt) and (AR^.List <> nil) then
begin
OM^.Append( '' );
OM^.Append( Format(LoadString(_SReplyAvailFrom), [AddrToStr(AR^.Addr)]) );
OM^.Append( '' );
AR^.List^.ForEach( @Write );
OM^.Append( '' );
end;
end; { WriteList }
begin
Log^.Write( ll_Protocol, LoadString(_SLogSendingAvail) );
CFG^.Avail^.LoadAll;
CFG^.Avail^.ForEach( @WriteList );
if elo_Pause in Link^.Opt then
OM^.Append( LoadString(_SPauseWarning) );
end; { SendAvail }
procedure SetNotifyMode( const S: String );
var
Mode: String;
begin
if JustSameText( S, 'On' ) then
begin
Include( Link^.Opt, elo_Notify );
Mode := LoadString( _SModeTurnedOn );
end
else if JustSameText( S, 'Off' ) then
begin
Exclude( Link^.Opt, elo_Notify );
Mode := LoadString( _SModeTurnedOff );
end
else
begin
Log^.Write( ll_Warning, Format(LoadString(_SLogInvalidNotifyCmd), [S] ));
OM^.Append( LoadString(_SReplyInvalidNotifyCmd) );
Exit;
end;
CFG^.Modified := True;
OM^.Append( Format(LoadString(_SNotifyChanged), [Mode] ));
end; { SetNotifyMode }
procedure ApplyPause;
var
S: String;
begin
Include( Link^.Opt, elo_Pause );
S := Format( LoadString(_SPauseChanged), [LoadString(_SModeTurnedOn)] );
OM^.Append( S );
Log^.Write( ll_Protocol, S );
CFG^.Modified := True;
end; { ApplyPause }
procedure ApplyResume;
var
S: String;
begin
Exclude( Link^.Opt, elo_Pause );
S := Format( LoadString(_SPauseChanged), [LoadString(_SModeTurnedOff)] );
OM^.Append( S );
Log^.Write( ll_Protocol, S );
CFG^.Modified := True;
end; { ApplyResume }
procedure MakeStat(const S: String);
var
p1, p2 : String;
Period : Integer;
begin
{
SplitPair(S, p1, p2);
try
Period := StrToInt(p1);
if (Period < 1) or (Period > 365) then
raise Exception.Create;
except
on E: Exception do
}
end; { MakeStat }
procedure DoCommand( const S: String );
var
Key, Par: String;
begin
SplitPair( S, Key, Par );
if JustSameText( Key, '%Help' ) then
SendHelp
else if JustSameText( Key, '%List' ) then
SendList
else if JustSameText( Key, '%Query' ) then
SendQuery
else if JustSameText( Key, '%Avail' ) then
SendAvail
else if JustSameText( Key, '%Notify' ) then
SetNotifyMode( Par )
else if JustSameText( Key, '%Pause' ) then
ApplyPause
else if JustSameText( Key, '%Resume' ) then
ApplyResume
else if JustSameText( Key, '%Stat' ) then
MakeStat( Par )
else
begin
Log^.Write( ll_Warning, Format(LoadString(_SLogInvalidAfixCmd), [Key] ));
OM^.Append( LoadString(_SReplyInvalidAfixCmd) );
end;
end; { DoCommand }
function LastLink( Echo: PFileEcho ) : Boolean;
begin
if Echo^.Downlinks^.Count = 0 then
Result := True
else if (Echo^.Downlinks^.Count = 1) and (Echo^.Uplinks^.Count = 1) then
Result := CompAddr( PAddress(Echo^.Downlinks^.At(0))^,
PAddress(Echo^.Uplinks^.At(0))^ ) = 0
else
Result := False;
end; { LastLink }
procedure Event_UplinksLost( Echo: PFileEcho );
begin
Log^.Write( ll_Warning, LoadString(_SLogUplinksLost) );
Notify( Echo^.Name^, LoadString(_SNotifyWarnSubj), LoadString(_SNotifyUplinksLost) );
UnlinkAll( Echo, MsgBase );
FileBase^.EchoList^.Free( Echo );
end; { Event_UplinksLost }
procedure Event_DownlinksLost( Echo: PFileEcho );
begin
Log^.Write( ll_Warning, LoadString(_SLogDownlinksLost) );
UnlinkAll( Echo, MsgBase );
FileBase^.Echolist^.Free( Echo );
end; { Event_DownlinksLost }
procedure SubChanged;
begin
FileBase^.Modified := True;
OM^.SetSubj( LoadString(_SSubChangedSubj) );
end; { SubChanged }
procedure LinkEcho( Echo: PFileEcho; Action: Char; DontWarn: Boolean );
var
j: Integer;
Wrote: Boolean;
begin
if Action = '+' then
begin
if Echo^.Downlinks^.Search( @Link^.Addr, j ) then
begin
if not DontWarn then
OM^.Append( Format(LoadString(_SReplyAlreadyDL), [Echo^.Name^] ));
end
else if Link^.Deny^.Match( Echo^.Name^ ) then
begin
Log^.Write( ll_Warning, Format(LoadString(_SAfixEchoDenied), [Echo^.Name^] ));
OM^.Append( LoadString(_SEchoDenied) );
end
else
begin
SubChanged;
Echo^.Downlinks^.AtInsert( j, NewAddr(Link^.Addr) );
Log^.Write( ll_Protocol, Format(LoadString(_SLogDLinked), [Echo^.Name^] ));
OM^.Append( Format(LoadString(_SReplyDLinked), [Echo^.Name^] ));
end;
end
else
begin
Wrote := False;
if Echo^.Downlinks^.Search( @Link^.Addr, j ) then
begin
Wrote := True;
SubChanged;
Echo^.Downlinks^.AtFree( j );
Log^.Write( ll_Protocol, Format(LoadString(_SLogDUnlinked), [Echo^.Name^] ));
OM^.Append( Format(LoadString(_SReplyUnlinked), [Echo^.Name^] ));
if (Echo^.Area = nil) and LastLink( Echo ) then
begin
Event_DownlinksLost( Echo );
Exit;
end;
end;
if Echo^.Uplinks^.Search( @Link^.Addr, j ) then
begin
SubChanged;
Echo^.Uplinks^.AtFree( j );
Log^.Write( ll_Protocol, Format(LoadStr(_SLogUUnlinked), [Echo^.Name^] ));
if not Wrote then
OM^.Append( Format(LoadString(_SReplyUnlinked), [Echo^.Name^] ));
if Echo^.Uplinks^.Count = 0 then
Event_UplinksLost( Echo );
end;
end;
end; { LinkEcho }
function ResolveForward( const EchoTag: String ) : PFileEcho;
var
Uplink: PEchoLink;
Echo : PFileEcho;
UM : PNetmailMessage;
begin
Result := nil;
Uplink := CFG^.Avail^.FindUplink( EchoTag );
if Uplink = nil then Exit;
New( Echo, Init(EchoTag) );
FileBase^.Echolist^.Insert( Echo );
FileBase^.Modified := True;
Result := Echo;
Echo^.Uplinks^.Insert( NewAddr(Uplink^.Addr) );
Log^.Write( ll_Service, Format(LoadString(_SLogWriteFwd),
[AddrToStr(Uplink^.Addr), Echotag] ));
UM := MsgBase^.NewMessage;
try
with UM^ do
begin
SetOrig( Uplink^.OurAka );
SetFrom( PROG_NAME );
SetDest( Uplink^.Addr );
SetTo ( 'Allfix' );
SetSubj( Uplink^.Password^ );
case Uplink^.Flavor of
fl_Hold : SetAttr( ATTR_LOCAL or ATTR_HOLD );
fl_Dir : SetAttr( ATTR_LOCAL or ATTR_DIR );
fl_Imm : SetAttr( ATTR_LOCAL or ATTR_IMM );
fl_Crash: SetAttr( ATTR_LOCAL or ATTR_CRASH );
end;
Append( '+' + Echotag );
Append( TEARLINE );
Save;
end;
finally
Destroy( UM );
end;
end; { ResolveForward }
procedure Subscribe( S: String );
var
j: Integer;
Action: Char;
Found : Boolean;
Echo : PFileEcho;
begin
OpenFileBase;
Action := S[1];
System.Delete( S, 1, 1 );
if HasWild( S ) then
begin
Found := False;
for j := 0 to Pred( FileBase^.EchoList^.Count ) do
begin
Echo := FileBase^.EchoList^.At( j );
if WildMatch( Echo^.Name^, S ) then
begin
LinkEcho( Echo, Action, True );
Found := True;
end;
end;
if not Found then
OM^.Append( LoadString(_SReplyWildNotFound) );
end
else
begin
Echo := FileBase^.GetEcho( S );
if Echo = nil then
begin
Echo := ResolveForward( S );
if Echo <> nil then
begin
OM^.Append( Format(LoadString(_SReplyReqForw),
[AddrToStr( PAddress(Echo^.Uplinks^.At(0))^ )] ));
end;
end;
if Echo <> nil then
LinkEcho( Echo, Action, False )
else
begin
Log^.Write( ll_Warning, Format(LoadString(_SLogNoSuchEcho), [S] ));
OM^.Append( Format(LoadString(_SReplyNoSuchEcho), [S]));
end;
end;
end; { Subscribe }
procedure EatLine( S: PString ); far;
begin
if (S^ = '') or (S^[1] = ^A) or (Pos('---', S^) = 1) or (Pos(' * Origin: ', S^) = 1) then Exit;
OM^.Append( '' );
OM^.Append( '> ' + S^ );
if S^[1] = '%' then
DoCommand( S^ )
else if S^[1] in ['+', '-'] then
Subscribe( S^ )
else
OM^.Append( 'Пpопускаем...' );
end; { EatLine }
function OurMessage: Boolean;
var
Robot: String;
begin
if IM^.Echomail or
(Link = nil) or
(CompAddr(IM^.GetDest, Link^.OurAka) <> 0) or
TestBit(IM^.GetAttr, ATTR_RECVD)
then
Result := False
else
begin
Robot := IM^.GetTo;
Result := CFG^.AfixRobots^.Match( Robot );
end;
end; { OurMessage }
begin
Link := CFG^.Links^.Find( IM^.GetOrig );
if not OurMessage then Exit;
OM := nil;
try
OM := MsgBase^.NewMessage;
with OM^ do
begin
SetOrig( Link^.OurAka );
SetFrom( PROG_NAME );
SetDest( IM^.GetOrig );
SetTo ( IM^.GetFrom );
SetSubj( Format(LoadString(_SYourAfixReqSubj), [IM^.GetTo] ));
if Cfg^.KillAfixReq then
SetAttr( ATTR_LOCAL or ATTR_KILLSENT )
else
SetAttr( ATTR_LOCAL );
SetReply( IM^.GetMsgID );
Append( 'Hi, ' + ExtractWord( 1, IM^.GetFrom, BLANK ) + '!' );
end;
Log^.Write( ll_Protocol, Format(LoadString(_SLogAfixReply), [IM^.GetFrom, AddrToStr(IM^.GetOrig)]));
case Link^.Flavor of
fl_Hold : OM^.SetAttr( OM^.GetAttr or ATTR_HOLD );
fl_Dir : OM^.SetAttr( OM^.GetAttr or ATTR_DIR );
fl_Imm : OM^.SetAttr( OM^.GetAttr or ATTR_IMM );
fl_Crash : OM^.SetAttr( OM^.GetAttr or ATTR_CRASH );
end;
if JustSameText( IM^.GetSubj, Link^.Password^ ) then
IM^.ForEach( @EatLine )
else
begin
Log^.Write( ll_Warning, Format(LoadString(_SLogWrongAfixPw), [IM^.GetSubj] ));
OM^.Append( LoadString(_SReplyWrongAfixPw));
end;
with OM^ do
begin
Append( '' );
Append( TEARLINE );
Save;
end;
finally
if CFG^.KillAfixReq then
IM^.Kill
else
begin
IM^.SetAttr( IM^.GetAttr or ATTR_RECVD );
IM^.Save;
end;
Destroy( OM );
end;
end; { HandleMessage }
{ --------------------------------------------------------- }
{ RunAreaFix }
{ --------------------------------------------------------- }
procedure RunAreaFix;
var
Message: PNetmailMessage;
MsgBase: PMsgBase;
begin
Log^.Write( ll_Service, LoadString(_SLogStartAfix) );
MsgBase := nil;
try
New( MsgBase, Init(CFG^.Netmail) );
MsgBase^.SetPID( SHORT_PID );
MsgBase^.SeekFirst;
while MsgBase^.SeekFound do
begin
Message := nil;
try
Message := MsgBase^.GetMessage;
HandleMessage( Message, MsgBase );
finally
Destroy( Message );
end;
MsgBase^.SeekNext;
end;
finally
Destroy( MsgBase );
end;
Log^.Write( ll_Service, LoadString(_SLogStopAfix) );
end; { RunAreaFix }
end.
|
unit tInfSql;
interface
Uses
tSQLCls,DBTables,Classes,Forms,DB,SysUtils;
const sqlSuccess=0;
sqlDBOpen=1;
Type TInformixSQL=class(TSQL)
public
constructor Create(dsn,uid,pwd:string);
{Virtual Functions}
function Connect(uid,pwd:string):integer; override;
function CurrentDate:String;override;
function CurrentDateTime:String;override;
function CurrentUser:String;override;
function TableKeyword(FieldName:string):string;override;
function DatePart(fn:string):string;override;
{**************serge}
function ConvertToDate2(fn:string):string;override;
function ConvertToDate(fn:string):string;override;
function ConvertToDateTime(fn:string):string;override;
function TimePart(fn:string):string;override;
function CharStr(fn:string):string;override;
function UpperCase(fn:string):string;override;
function SortLongString(fn:string):string;override;
function UserID(uid:string):longint;override;
function CreateUser(uid,pwd:string):longint;override;
function ChangePassword(uid,pwd:string):integer; override;
function DropUser(uid:string):integer;override;
function GrantRole(uid,group:string):integer;override;
function RevokeRole(uid,group:string):integer;override;
procedure MultiString(sl:TStrings; p:PChar);override;
function ConnectCount:longint; override;
function LockRecord(Table,Field,Value,Condition:string):integer; override;
function RunFunction(FunName,Params,Alias:string):TQuery; override;
function RunFunctionEx(FunName:TSQLString;Params:TStrings):TQuery; override;
function LTrim(Value:string):string; override;
function InsertSelect(TableName,Fields,SelTableName,Values,Cond:String):integer;override;
end;
implementation
constructor TInformixSQL.Create(dsn,uid,pwd:string);
begin
inherited Create(dsn,uid,pwd);
PrefixTable:='';
DualTable:='DUAL'
end;
function TInformixSQL.CurrentDate:String;
begin
CurrentDate:='TODAY'
end;
function TInformixSQL.CurrentDateTime:String;
begin
CurrentDateTime:='CURRENT'
end;
function TInformixSQL.CurrentUser:String;
{Возвращает текущего пользователя }
begin
CurrentUser:='USER'
end;
function TInformixSQL.TableKeyword(FieldName:string):string;
begin
TableKeyword:=Copy(FieldName,1,18)
end;
function TInformixSQL.DatePart(fn:string):string;
{Возвращает от типа DATE часть, содержащую дату}
begin
DatePart:='EXTEND('+fn+',''YEAR TO DAY'')';
end;
function TInformixSQL.ConvertToDate2(fn:string):string;
var r:string;
begin
if fn[1]='''' then r:=copy(fn,2,length(fn)-2) else r:=fn;
ConvertToDate2:='DATETIME('+r+') YEAR TO DAY';
end;
function TInformixSQL.ConvertToDate(fn:string):string;
begin
ConvertToDate:=fn
end;
function TInformixSQL.ConvertToDateTime(fn:string):string;
begin
ConvertToDateTime:=fn {'TO_DATE('+fn+',''YYYY-MM-DD HH24:MI:SS'')'};
end;
function TInformixSQL.TimePart(fn:string):string;
{Возвращает от типа DATE часть, содержащую время}
begin
TimePart:='EXTEND('+fn+',''HOUR TO SECOND'')';
end;
function TInformixSQL.CharStr(fn:string):string;
{Возвращает значение типа CHAR целого цисла : x=CHR(67)-> x='D'}
begin
CharStr:=MakeStr(' '){'CHR('+fn+')'}
end;
function TInformixSQL.UpperCase(fn:string):string;
begin
UpperCase:='UPPER('+fn+')'
end;
function TInformixSQL.SortLongString(fn:string):string;
begin
SortLongString:=fn;
end;
function TInformixSQL.UserID(uid:string):longint;
begin
UserID:=0{SelectInteger('"SYS".ALL_USERS','USER_ID','UPPER("USERNAME")'+'=UPPER('+
MakeStr(uid)+')');}
end;
function TInformixSQL.CreateUser(uid,pwd:string):longint;
begin
{ if ExecOneSQL('CREATE USER '+uid+' IDENTIFIED BY '+pwd)=0 then
CreateUser:=UserID(uid)
else}
CreateUser:=-1
end;
function TInformixSQL.DropUser(uid:string):integer;
begin
DropUser:=-1{ExecOneSQL('DROP USER '+uid)}
end;
function TInformixSQL.GrantRole(uid,group:string):integer;
begin
GrantRole:=ExecOneSQL('GRANT '+group+' TO '+uid)
end;
function TInformixSQL.RevokeRole(uid,group:string):integer;
begin
RevokeRole:=ExecOneSQL('REVOKE '+group+' FROM '+uid)
end;
procedure TInformixSQL.MultiString(sl:TStrings; p:PChar);
var i:integer;
begin
if p=NIL then
sl.Add('NULL')
else
if p[0]=#0 then
sl.Add('''''')
else
sl.Add(MakeStr(StrPas(p)));
{ SplitText(sl,p,'||');}
end;
function TInformixSQL.RunFunction(FunName,Params,Alias:string):TQuery;
var sl:TStringList;
begin
sl:=TStringList.Create;
sl.Add(Params);
RunFunction:=RunFunctionEx(FunName,sl);
sl.Free
end;
function TInformixSQL.RunFunctionEx(FunName:TSQLString;Params:TStrings):TQuery;
var sl:TStringList;
begin
sl:=TStringList.Create;
sl.Add('EXECUTE PROCEDURE '+FunName+'(');
sl.AddStrings(Params);
sl.Add(')');
RunFunctionEx:=CreateQuery(sl);
sl.Free;
end;
function TInformixSQL.ConnectCount:longint;
begin
ConnectCount:=0
end;
function TInformixSQL.LockRecord(Table,Field,Value,Condition:string):integer;
var q:TQuery;
res:integer;
sl:TStringList;
begin
if StartTransaction then
begin
if Condition<>'' then
Condition:=' AND '+Condition;
sl:=TStringList.Create;
Condition:=Keyword(Field)+'='+Value+Condition;
sl.Add('SELECT * FROM '+AddPrefix(Table));
sl.Add('WHERE '+Condition+' FOR UPDATE NOWAIT');
q:=CreateQuery(sl);
if Error=1 then
res:=2
else
if q.eof then
res:=1
else
res:=0;
q.Free;
sl.Free;
end
else
res:=3;
if (res=1) or (res=2) then
RollBack;
LockRecord:=res;
end;
function TInformixSQL.ChangePassword(uid,pwd:string):integer;
var s:string;
begin
ChangePassword:=-1;
{ s:='ALTER USER '+uid;
if pwd<>'' then
s:=s+' IDENTIFIED BY '+pwd;
ChangePassword:=sql.ExecOneSQL(s)}
end;
function TInformixSQL.Connect(uid,pwd:string):integer;
begin
Result:=inherited Connect(uid,pwd);
execonesql('set explain on');
end;
function TInformixSQL.LTrim(Value:string):string;
begin
LTrim:='TRIM('+Value+')'
end;
function TInformixSQL.InsertSelect(TableName,Fields,SelTableName,Values,Cond:String):integer;
var sl:TStringList;
function MakeAsgn(flds,values:String):string;
var
f,v:string;
r:string;
function GetWord(var s:string):string;
var
i:integer;
r:string;
begin
i:=pos(',',s);
if i=0 then i:=length(s);
if s[i]=',' then r:=copy(s,1,i-1) else r:=copy(s,1,i);
SYSTEM.delete(s,1,i);
GetWord:=r;
end;
begin
r:='';
while flds<>'' do
begin
f:=GetWord(flds);
v:=GetWord(values);
r:=r+v+' '+f;
if flds<>'' then r:=r+',';
end;
MakeAsgn:=r;
end;
begin
sl:=TStringList.Create;
sl.Add('SELECT ');
sl.Add(MakeAsgn(MakeKeywords(Fields),Values));
sl.Add('FROM '+AddPrefix(SelTableName));
AddCondition(sl,Cond);
sl.Add('INTO TEMP anzrows');
ExecSQL(sl);
sl.Clear;
sl.Add(INSERT_INTO+AddPrefix(TableName));
sl.Add('('+MakeKeywords(Fields)+') select * from anzrows');
InsertSelect:=ExecSQL(sl);
ExecOneSQL('DROP TABLE anzrows');
sl.Free
end;
end.
|
unit ucounter;
{$mode OBJFPC}{$H+}
interface
uses
Classes, SysUtils, ZDataset, ZConnection, Uperson;
type
{ T_TC_ClassificatorCounter }
T_TC_ClassificatorCounter = Class(TObject)
private
FCaption: string;
FConnection: TZConnection;
FCurrentValue: integer;
FLockDate: TDateTime;
FLocked: boolean;
FLockUser: string;
FMaximumValue: integer;
FNumLength: integer;
FPerson: T_TC_Person;
FPostfix: string;
FPrefix: string;
FPUID: string;
FView: TZReadOnlyQuery;
function New(const aPUID, aCaption, aPrefix, aPostfix:string; const iNumLength, iCurValue, iMaxValue:integer):boolean;
procedure SetCaption(AValue: string);
procedure SetConnection(AValue: TZConnection);
procedure SetCurrentValue(AValue: integer);
procedure SetLocked(AValue: boolean);
procedure SetMaximumValue(AValue: integer);
procedure SetNumLength(AValue: integer);
procedure SetPostfix(AValue: string);
procedure SetPrefix(AValue: string);
procedure SetPUID(AValue: string);
public
property Connection:TZConnection read FConnection write SetConnection;
property Caption:string read FCaption write SetCaption;
property Prefix:string read FPrefix write SetPrefix;
property Postfix:string read FPostfix write SetPostfix;
property NumLength:integer read FNumLength write SetNumLength;
property CurrentValue:integer read FCurrentValue write SetCurrentValue;
property MaximumValue:integer read FMaximumValue write SetMaximumValue;
property Locked:boolean read FLocked write SetLocked;
property View:TZReadOnlyQuery read FView;
property PUID:string read FPUID write SetPUID;
property LockUser:string read FLockUser;
property LockDate:TDateTime read FLockDate;
function GetCounter(const aPUID:string):boolean;
function Add(const aCaption, aPrefix, aPostfix:string; const iNumLength, iCurValue, iMaxValue:integer; aDefault:boolean=False):string;
function Edit:boolean;
function Delete(const aPUID:string):boolean;
constructor Create; overload;
destructor Destroy; override;
end;
{ T_TC_ClassificatorCounterLink }
T_TC_ClassificatorCounterLink = Class (TObject)
private
FConnection: TZConnection;
FCounter: T_TC_ClassificatorCounter;
FPerson: T_TC_Person;
procedure SetConnection(AValue: TZConnection);
procedure SetCounter(AValue: T_TC_ClassificatorCounter);
procedure SetPerson(AValue: T_TC_Person);
function GetClassPUIDFromID(const aClass_ID:string):string;
public
property Person:T_TC_Person read FPerson write SetPerson;
property Counter:T_TC_ClassificatorCounter read FCounter write SetCounter;
property Connection: TZConnection read FConnection write SetConnection;
function GetLinkFormat(const aClassPuid:string):string;
function GetCode(const aClassPuid:string; const aFormatPuid:string=''):string;
function SetLink(const aClassPuid:string; const aFormatPuid:string=''):boolean;
function DeleteLink(const aClassPuid:string):boolean;
constructor Create; overload;
constructor Create(aCounter: T_TC_ClassificatorCounter); overload;
destructor Destroy; override;
end;
implementation
uses comunit;
{ T_TC_ClassificatorCounterLink }
procedure T_TC_ClassificatorCounterLink.SetCounter(
AValue: T_TC_ClassificatorCounter);
begin
if FCounter=AValue then Exit;
FCounter:=AValue;
end;
procedure T_TC_ClassificatorCounterLink.SetConnection(AValue: TZConnection);
begin
if FConnection=AValue then Exit;
FConnection:=AValue;
end;
procedure T_TC_ClassificatorCounterLink.SetPerson(AValue: T_TC_Person);
begin
if FPerson=AValue then Exit;
FPerson:=AValue;
end;
function T_TC_ClassificatorCounterLink.GetClassPUIDFromID(
const aClass_ID: string): string;
begin
end;
function T_TC_ClassificatorCounterLink.GetLinkFormat(const aClassPuid: string
): string;
var
Quer1:TZReadOnlyQuery;
begin
Result:='';
if FConnection <> nil then
begin
Quer1:=TZReadOnlyQuery.Create(nil);
Quer1.Connection:=FConnection;
Quer1.SQL.Text:='SELECT FORMAT_PUID FROM INFODBA.TCV_CLASSIF_FORMREF'
+ ' WHERE (CLASS_PUID='+QuotedStr(aClassPuid)+') AND (ROWNUM=1)';
Quer1.Open;
if Quer1.IsEmpty then
begin
Quer1.Close;
Quer1.SQL.Text:='SELECT t_04.FORMAT_PUID FROM (SELECT t_01.puid,t_01.pseq,'
+ ' t_01.pval_0, t_05.pname, t_05.puid as ppuid'
+ ' FROM INFODBA.PPARENT t_01 LEFT JOIN INFODBA.PSMLB0 t_05 ON t_05.pcid=t_01.pval_0'
+ ' WHERE t_01.puid='+QuotedStr(aClassPuid)+' order by pseq asc) t_03'
+ ' LEFT JOIN INFODBA.TCV_CLASSIF_FORMREF t_04 ON t_03.ppuid=T_04.CLASS_PUID'
+ ' WHERE (t_04.FORMAT_PUID IS NOT NULL) AND (ROWNUM=1) ORDER BY PSEQ';
Quer1.Open;
if Quer1.IsEmpty then Result:=csDefaultFormatUID
else Result:=Quer1.Fields[0].AsString;
end
else
Result:=Quer1.Fields[0].AsString;
Quer1.Close;
FreeAndNil(Quer1);
end;
// Result:='';
end;
function T_TC_ClassificatorCounterLink.GetCode(const aClassPuid: string;
const aFormatPuid:string=''): string;
var
s:string;
Quer1:TZQuery;
iCurVal, iMaxVal:integer;
begin
Result:='';
s := aFormatPuid;
if s='' then s:=GetLinkFormat(aClassPuid);
if Counter.GetCounter(s) then
begin
Quer1:=TZQuery.Create(nil);
Quer1.Connection:=Counter.Connection;
(* Quer1.SQL.Text:='SELECT NUM_CURVAL, NUM_MAXVAL'
+' FROM INFODBA.TCV_CLASSIF_FORMAT WHERE PUID='+QuotedStr(s);
// +') AND (LOCK_USER IS NOT NULL)';
Quer1.Open;
if Quer1.RecordCount>0 then
begin
iCurVal:=Quer1.Fields[0].AsInteger;
iMaxVal:=Quer1.Fields[1].AsInteger;
Quer1.Close; *)
if Counter.CurrentValue<=Counter.MaximumValue then
begin
Quer1.SQL.Text:='UPDATE INFODBA.TCV_CLASSIF_FORMAT SET'
+' NUM_CURVAL=' + IntToStr(Counter.CurrentValue+1)
+' WHERE PUID='+ QuotedStr(s);
Quer1.ExecSQL;
Result:=Counter.Prefix
+ Padl(inttostr(Counter.CurrentValue),Counter.NumLength,'0')+Counter.Postfix;
end;
(* end; *)
FreeAndNil(Quer1);
end;
end;
function T_TC_ClassificatorCounterLink.SetLink(const aClassPuid: string;
const aFormatPuid:string=''): boolean;
var
s:string;
Quer1:TZQuery;
begin
Result:=True;
if aFormatPuid='' then
s:=Counter.PUID
else
s:=aFormatPuid;
Quer1:=TZQuery.Create(nil);
Quer1.Connection:=Counter.Connection;
DeleteLink(aClassPuid);
try
Quer1.SQL.Text:='INSERT INTO INFODBA.TCV_CLASSIF_FORMREF (FORMAT_PUID,'
+ ' CLASS_PUID) VALUES ('+QuotedStr(s)+', '+QuotedStr(aClassPuid)+')';
Quer1.ExecSQL;
except
Result:=False;
end;
FreeAndNil(Quer1);
end;
function T_TC_ClassificatorCounterLink.DeleteLink(const aClassPuid: string): boolean;
var
s:string;
Quer1:TZQuery;
begin
Result:=True;
{if aFormatPuid='' then
s:=Counter.PUID
else
s:=aFormatPuid;}
Quer1:=TZQuery.Create(nil);
Quer1.Connection:=Counter.Connection;
Quer1.SQL.Add('DELETE FROM INFODBA.TCV_CLASSIF_FORMREF WHERE CLASS_PUID='
+ QuotedStr(aClassPuid));
//(FORMAT_PUID=' +QuotedStr(s)+') AND (CLASS_PUID='+QuotedStr(aClassPuid)+')');
try
Quer1.ExecSQL;
except
Result:=False;
end;
FreeAndNil(Quer1);
end;
constructor T_TC_ClassificatorCounterLink.Create;
begin
inherited Create;
end;
constructor T_TC_ClassificatorCounterLink.Create(
aCounter: T_TC_ClassificatorCounter);
begin
Inherited Create;
FCounter:=aCounter;
end;
destructor T_TC_ClassificatorCounterLink.Destroy;
begin
inherited Destroy;
end;
{ T_TC_ClassificatorCounter }
procedure T_TC_ClassificatorCounter.SetConnection(AValue: TZConnection);
begin
if FConnection=AValue then Exit;
FConnection:=AValue;
FView.Connection:=FConnection;
FView.SQL.Text:='SELECT * FROM INFODBA.TCV_CLASSIF_FORMAT ORDER BY PREFIX, POSTFIX';
FView.Open;
end;
function T_TC_ClassificatorCounter.New(const aPUID, aCaption, aPrefix,
aPostfix: string; const iNumLength, iCurValue, iMaxValue: integer): boolean;
var
quer1:TZQuery;
begin
Result:=True;
quer1:=TZQuery.Create(nil);
quer1.Connection:=FConnection;
quer1.SQL.Text:='INSERT INTO INFODBA.TCV_CLASSIF_FORMAT (PUID, NUM_CURVAL,'
+' NUM_MAXVAL, NUM_LENGTH, PREFIX, POSTFIX, PCAPTION) VALUES ('
+QuotedStr(aPUID)+', '+IntToStr(iCurValue)+', '+IntToStr(iMaxValue)+', '
+IntToStr(iNumLength)+', '+QuotedStr(aPrefix)+', '+QuotedStr(aPostfix)+', '
+QuotedStr(aCaption)+')';
try
quer1.ExecSQL;
except
Result:=False;
end;
FreeAndNil(quer1);
end;
procedure T_TC_ClassificatorCounter.SetCaption(AValue: string);
begin
if FCaption=AValue then Exit;
FCaption:=AValue;
end;
procedure T_TC_ClassificatorCounter.SetCurrentValue(AValue: integer);
begin
if FCurrentValue=AValue then Exit;
FCurrentValue:=AValue;
end;
procedure T_TC_ClassificatorCounter.SetLocked(AValue: boolean);
var
quer1:TZQuery;
begin
if FLocked=AValue then Exit;
quer1:=TZQuery.Create(nil);
quer1.Connection:=FConnection;
if AValue then
begin
quer1.SQL.Text:='';
end
else
begin
end;
FreeAndNil(quer1);
FLocked:=AValue;
end;
procedure T_TC_ClassificatorCounter.SetMaximumValue(AValue: integer);
begin
if FMaximumValue=AValue then Exit;
FMaximumValue:=AValue;
end;
procedure T_TC_ClassificatorCounter.SetNumLength(AValue: integer);
begin
if FNumLength=AValue then Exit;
FNumLength:=AValue;
end;
procedure T_TC_ClassificatorCounter.SetPostfix(AValue: string);
begin
if FPostfix=AValue then Exit;
FPostfix:=AValue;
end;
procedure T_TC_ClassificatorCounter.SetPrefix(AValue: string);
begin
if FPrefix=AValue then Exit;
FPrefix:=AValue;
end;
procedure T_TC_ClassificatorCounter.SetPUID(AValue: string);
begin
if FPUID=AValue then Exit;
FPUID:=AValue;
end;
function T_TC_ClassificatorCounter.GetCounter(const aPUID: string): boolean;
var
Quer1:TZReadOnlyQuery;
procedure LoadFromQuer1;
begin
FCaption:=Quer1.FieldByName('PCAPTION').AsString;
FPUID:=Quer1.FieldByName('PUID').AsString;
FPostfix:=Quer1.FieldByName('POSTFIX').AsString;
FPrefix:=Quer1.FieldByName('PREFIX').AsString;
FNumLength:=Quer1.FieldByName('NUM_LENGTH').AsInteger;
FCurrentValue:=Quer1.FieldByName('NUM_CURVAL').AsInteger;
FMaximumValue:=Quer1.FieldByName('NUM_MAXVAL').AsInteger;
FLockUser:=Quer1.FieldByName('LOCK_USER').AsString;
FLockDate:=Quer1.FieldByName('LOCK_DATE').AsDateTime;
Result:=True;
end;
begin
Result:=False;
Quer1:=TZReadOnlyQuery.Create(nil);
Quer1.Connection:=FConnection;
Quer1.SQL.Text:='SELECT * FROM INFODBA.TCV_CLASSIF_FORMAT WHERE (PUID='
+QuotedStr(aPUID)+') AND (ROWNUM=1)';
Quer1.Open;
if Quer1.RecordCount>0 then
begin
LoadFromQuer1;
Result:=True;
end
else
begin
Quer1.Close;
Quer1.SQL.Text:='SELECT * FROM INFODBA.TCV_CLASSIF_FORMAT WHERE (PUID='
+ QuotedStr(csDefaultFormatUID)+') AND (ROWNUM=1)';
Quer1.Open;
if Quer1.RecordCount>0 then
begin
LoadFromQuer1;
Result:=True;
end;
end;
end;
function T_TC_ClassificatorCounter.Add(const aCaption, aPrefix,
aPostfix: string; const iNumLength, iCurValue,
iMaxValue: integer; aDefault:boolean=False): string;
begin
if aDefault then Result := csDefaultFormatUID
else Result := GetUID;
if New(Result,aCaption,aPrefix,aPostfix,iNumLength,iCurValue,iMaxValue) then
begin
FPUID:=Result;
FCurrentValue:=iCurValue;
FMaximumValue:=iMaxValue;
FNumLength:=iNumLength;
FPrefix:=aPrefix;
FPostfix:=aPostfix;
FCaption:=aCaption;
end
else
Result:='';
end;
function T_TC_ClassificatorCounter.Edit: boolean;
begin
Delete(FPUID);
Result:=
New(FPUID,FCaption,FPrefix,FPostfix,FNumLength,FCurrentValue,FMaximumValue);
end;
function T_TC_ClassificatorCounter.Delete(const aPUID: string): boolean;
var
Quer1:TZQuery;
begin
Result:= True;
Quer1:=TZQuery.Create(nil);
Quer1.Connection:=FConnection;
Quer1.SQL.Text:='DELETE FROM INFODBA.TCV_CLASSIF_FORMAT WHERE PUID='+QuotedStr(aPUID);
try
Quer1.ExecSQL;
except
Result:=False;
end;
FreeAndNil(Quer1);
end;
constructor T_TC_ClassificatorCounter.Create;
begin
inherited;
FView:=TZReadOnlyQuery.Create(nil);
end;
destructor T_TC_ClassificatorCounter.Destroy;
begin
FView.Close;
FreeAndNil(FView);
inherited Destroy;
end;
end.
|
unit mailer_lib;
{$mode objfpc}{$H+}
{$include ../../define.inc}
interface
uses
{$IFDEF SYNAPSE}
{$IFDEF XMAILER}
xmailer,
{$ENDIF}
{$ENDIF}
Classes, SysUtils;
const
_MAIL_NOSUPPORT = 'Mailer-Support not exist.';
type
{ TMailer }
TMailer = class
private
FErrorMessage: string;
FMailServer: string;
FMailPassword: string;
FMailUserName: string;
FPort: string;
FTo, FCc, FBcc: TStringList;
FEmailFormat: string;
FLogs: string;
FSSL, FTLS: boolean;
function getEmailFormat: string;
function getMailServer: string;
function getSmtpPort: string;
function getSSL: boolean;
function getTLS: boolean;
procedure setEmailFormat(AValue: string);
procedure setMailPassword(AValue: string);
procedure setMailServer(AValue: string);
procedure setMailUserName(AValue: string);
procedure setSmptPort(AValue: string);
procedure setSSL(AValue: boolean);
procedure setTLS(AValue: boolean);
{$IFDEF XMAILER}
procedure xmailer_OnProgress(const AProgress, AMax: integer; const AStatus: string);
{$ENDIF XMAILER}
public
Subject, Sender: string;
Message: TStringList;
constructor Create(Setting: string = 'default');
destructor Destroy; override;
property emailFormat: string read getEmailFormat write setEmailFormat;
property MailServer: string read getMailServer write setMailServer;
property Port: string read getSmtpPort write setSmptPort;
property UserName: string read FMailUserName write setMailUserName;
property Password: string read FMailPassword write setMailPassword;
property SSL: boolean read getSSL write setSSL;
property TLS: boolean read getTLS write setTLS;
property ErrorMessage: string read FErrorMessage;
property Logs: string read FLogs;
procedure AddTo(Email: string; Name: string = '');
procedure AddCc(Email: string; Name: string = '');
procedure AddBcc(Email: string; Name: string = '');
procedure Clear;
procedure Prepare;
function Send: boolean;
end;
implementation
uses fastplaz_handler, common, config_lib;
{ TMailer }
procedure TMailer.AddTo(Email: string; Name: string);
begin
if Name = '' then
FTo.Add(Email)
else
FTo.Add(Name + '<' + Email + '>');
end;
procedure TMailer.AddCc(Email: string; Name: string);
begin
if Name = '' then
FCc.Add(Email)
else
FCc.Add(Name + '<' + Email + '>');
end;
procedure TMailer.AddBcc(Email: string; Name: string);
begin
if Name = '' then
FBcc.Add(Email)
else
FBcc.Add(Name + '<' + Email + '>');
end;
procedure TMailer.Clear;
begin
FTo.Clear;
FBcc.Clear;
FCc.Clear;
FLogs := _MAIL_NOSUPPORT;
Subject := '';
Message.Clear;
{$IFDEF XMAILER}
FLogs := '';
{$ENDIF}
end;
procedure TMailer.Prepare;
begin
Clear;
end;
function TMailer.Send: boolean;
{$IFDEF XMAILER}
var
Mail: TSendMail;
{$ENDIF XMAILER}
begin
Result := False;
{$IFDEF XMAILER}
try
try
Mail := TSendMail.Create;
Mail.OnProgress := @xmailer_OnProgress;
Mail.Smtp.Host := FMailServer;
Mail.Smtp.Port := FPort;
Mail.Smtp.UserName := FMailUserName;
Mail.Smtp.Password := FMailPassword;
Mail.Smtp.SSL := FSSL;
Mail.Smtp.TLS := FTLS;
Mail.Sender := Sender;
Mail.Receivers.Text := FTo.Text;
Mail.Subject := Subject;
Mail.Message.Text := Message.Text;
if FEmailFormat = 'html' then
Mail.ContentType := ctTextHTML
else
Mail.ContentType := ctTextPlain;
Mail.Send;
FLogs := FLogs + 'OK';
Result := True;
except
on e: Exception do
begin
FErrorMessage := e.Message;
FLogs := e.Message + #13;
end;
end;
finally
Mail.Free;
end;
{$ENDIF XMAILER}
end;
function TMailer.getMailServer: string;
begin
Result := FMailServer;
end;
function TMailer.getEmailFormat: string;
begin
Result := FEmailFormat;
end;
function TMailer.getSmtpPort: string;
begin
Result := FPort;
end;
function TMailer.getSSL: boolean;
begin
Result := FSSL;
end;
function TMailer.getTLS: boolean;
begin
Result := FTLS;
end;
procedure TMailer.setEmailFormat(AValue: string);
begin
FEmailFormat := AValue;
end;
procedure TMailer.setMailPassword(AValue: string);
begin
if FMailPassword = AValue then
Exit;
FMailPassword := AValue;
end;
procedure TMailer.setMailServer(AValue: string);
begin
if FMailServer = AValue then
Exit;
FMailServer := AValue;
end;
procedure TMailer.setMailUserName(AValue: string);
begin
if FMailUserName = AValue then
Exit;
FMailUserName := AValue;
end;
procedure TMailer.setSmptPort(AValue: string);
begin
if FPort = AValue then
Exit;
FPort := AValue;
end;
procedure TMailer.setSSL(AValue: boolean);
begin
FSSL := AValue;
end;
procedure TMailer.setTLS(AValue: boolean);
begin
FTLS := AValue;
end;
{$IFDEF XMAILER}
procedure TMailer.xmailer_OnProgress(const AProgress, AMax: integer; const AStatus: string);
begin
FLogs := FLogs + FormatDateTime('YYYY-mm-dd hh:nn:ss', now) + ' | ' + AStatus + #13;
end;
{$ENDIF XMAILER}
constructor TMailer.Create(Setting: string);
begin
FTo := TStringList.Create;
FCc := TStringList.Create;
FBcc := TStringList.Create;
message := TStringList.Create;
FSSL := False;
FTLS := False;
FEmailFormat := 'html';
FLogs := '';
// read from config.json
MailServer := Config[format(_MAIL_MAILSERVER, [Setting])];
UserName := Config[format(_MAIL_USERNAME, [Setting])];
Password := Config[format(_MAIL_PASSWORD, [Setting])];
Port := Config[format(_MAIL_SMTPPORT, [Setting])];
SSL := Config.GetValue(format(_MAIL_SSL, [Setting]), True);
TLS := Config.GetValue(format(_MAIL_TLS, [Setting]), True);
end;
destructor TMailer.Destroy;
begin
inherited Destroy;
FreeAndNil(message);
FreeAndNil(FTo);
FreeAndNil(FCc);
FreeAndNil(FBcc);
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP Fenix
Description: Service relacionado à tabela [PRODUTO_SUBGRUPO]
The MIT License
Copyright: Copyright (C) 2020 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (alberteije@gmail.com)
@version 1.0.0
*******************************************************************************}
unit ProdutoSubgrupoService;
interface
uses
ProdutoSubgrupo, ProdutoGrupo,
System.SysUtils, System.Generics.Collections, ServiceBase, MVCFramework.DataSet.Utils;
type
TProdutoSubgrupoService = class(TServiceBase)
private
class procedure AnexarObjetosVinculados(AListaProdutoSubgrupo: TObjectList<TProdutoSubgrupo>); overload;
class procedure AnexarObjetosVinculados(AProdutoSubgrupo: TProdutoSubgrupo); overload;
public
class function ConsultarLista: TObjectList<TProdutoSubgrupo>;
class function ConsultarListaFiltroValor(ACampo: string; AValor: string): TObjectList<TProdutoSubgrupo>;
class function ConsultarObjeto(AId: Integer): TProdutoSubgrupo;
class procedure Inserir(AProdutoSubgrupo: TProdutoSubgrupo);
class function Alterar(AProdutoSubgrupo: TProdutoSubgrupo): Integer;
class function Excluir(AProdutoSubgrupo: TProdutoSubgrupo): Integer;
end;
var
sql: string;
implementation
{ TProdutoSubgrupoService }
class procedure TProdutoSubgrupoService.AnexarObjetosVinculados(AProdutoSubgrupo: TProdutoSubgrupo);
begin
// ProdutoGrupo
sql := 'SELECT * FROM PRODUTO_GRUPO WHERE ID = ' + AProdutoSubgrupo.IdProdutoGrupo.ToString;
AProdutoSubgrupo.ProdutoGrupo := GetQuery(sql).AsObject<TProdutoGrupo>;
end;
class procedure TProdutoSubgrupoService.AnexarObjetosVinculados(AListaProdutoSubgrupo: TObjectList<TProdutoSubgrupo>);
var
ProdutoSubgrupo: TProdutoSubgrupo;
begin
for ProdutoSubgrupo in AListaProdutoSubgrupo do
begin
AnexarObjetosVinculados(ProdutoSubgrupo);
end;
end;
class function TProdutoSubgrupoService.ConsultarLista: TObjectList<TProdutoSubgrupo>;
begin
sql := 'SELECT * FROM PRODUTO_SUBGRUPO ORDER BY ID';
try
Result := GetQuery(sql).AsObjectList<TProdutoSubgrupo>;
AnexarObjetosVinculados(Result);
finally
Query.Close;
Query.Free;
end;
end;
class function TProdutoSubgrupoService.ConsultarListaFiltroValor(ACampo, AValor: string): TObjectList<TProdutoSubgrupo>;
begin
sql := 'SELECT * FROM PRODUTO_SUBGRUPO where ' + ACampo + ' like "%' + AValor + '%"';
try
Result := GetQuery(sql).AsObjectList<TProdutoSubgrupo>;
AnexarObjetosVinculados(Result);
finally
Query.Close;
Query.Free;
end;
end;
class function TProdutoSubgrupoService.ConsultarObjeto(AId: Integer): TProdutoSubgrupo;
begin
sql := 'SELECT * FROM PRODUTO_SUBGRUPO WHERE ID = ' + IntToStr(AId);
try
GetQuery(sql);
if not Query.Eof then
begin
Result := Query.AsObject<TProdutoSubgrupo>;
AnexarObjetosVinculados(Result);
end
else
Result := nil;
finally
Query.Close;
Query.Free;
end;
end;
class procedure TProdutoSubgrupoService.Inserir(AProdutoSubgrupo: TProdutoSubgrupo);
begin
AProdutoSubgrupo.ValidarInsercao;
AProdutoSubgrupo.Id := InserirBase(AProdutoSubgrupo, 'PRODUTO_SUBGRUPO');
end;
class function TProdutoSubgrupoService.Alterar(AProdutoSubgrupo: TProdutoSubgrupo): Integer;
begin
AProdutoSubgrupo.ValidarAlteracao;
Result := AlterarBase(AProdutoSubgrupo, 'PRODUTO_SUBGRUPO');
end;
class function TProdutoSubgrupoService.Excluir(AProdutoSubgrupo: TProdutoSubgrupo): Integer;
begin
AProdutoSubgrupo.ValidarExclusao;
Result := ExcluirBase(AProdutoSubgrupo.Id, 'PRODUTO_SUBGRUPO');
end;
end.
|
// functions.pas: include file, included into unit1.pas
// swap 2 cards in the hand
procedure TForm1.swapCard(src, dst: integer);
var
temp: integer;
begin
South.hand[dst].deal := false;
South.hand[src].deal := false;
temp := South.hand[src].suit;
South.hand[src].suit := South.hand[dst].suit;
South.hand[dst].suit := temp;
temp := South.hand[src].rank;
South.hand[src].rank := South.hand[dst].rank;
South.hand[dst].rank := temp;
end;
// Fisher-Yates shuffle of the deck of cards
procedure TForm1.fyshuffle(var cards: array of TCard);
var
m, i: integer;
temp: TCard;
begin
Randomize();
for m := High(cards)-1 downto Low(cards) do begin
i := Random(m);
temp := cards[m];
cards[m] := cards[i];
cards[i] := temp;
end;
end;
// compare on ranks - keeps the ranks together
function onRank(var hand: array of TCard; i, p: Integer): integer;
var
ri, rp: integer;
begin
// put the ace on top
ri := hand[i].rank-1;
rp := hand[p].rank-1;
if ri = 0 then ri := 13;
if rp = 0 then rp := 13;
hand[i].deal := false;
if (ri > rp) then
Result := 1
else if (ri = rp) then
Result := hand[i].suit - hand[p].suit
else
Result := -1;
end;
// compare on suits - keeps the suits together
function onSuit(var hand: array of TCard; i, p: Integer): integer;
var
t1, t2, ri, rp: integer;
begin
// put the ace on top
ri := hand[i].rank-1;
rp := hand[p].rank-1;
if ri = 0 then ri := 13;
if rp = 0 then rp := 13;
hand[i].deal := false;
t1 := hand[i].suit*13+ri;
t2 := hand[p].suit*13+rp;
Result := t1 - t2;
end;
// sort the hand of cards
procedure TForm1.QuickSort(L, R: Integer; var hand: array of TCard; Compare: TCompare);
var
I, J, Pivot: Integer;
begin
repeat
I := L;
J := R;
Pivot := (L + R) shr 1;
repeat
while Compare(hand, I, Pivot) < 0 do Inc(I);
while Compare(hand, J, Pivot) > 0 do Dec(J);
if I <= J then begin
swapCard(I, J);
if Pivot = I then
Pivot := J
else if Pivot = J then
Pivot := I;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then QuickSort(L, J, hand, Compare);
L := I;
until I >= R;
end;
// draws the complete hand on the virtual canvas
procedure TForm1.drawHand(player: TPlayer);
var
i: integer;
begin
if player.location=1 then
for i := 1 to length(player.hand)-1 do begin
drawCard(player.hand[i], length(player.hand))
end
else
drawBack(player);
end;
// draw the back of the cards
procedure TForm1.drawBack(player: TPlayer);
var
card, hcard, vcard, box: TBGRABitmap;
ctx: TBGRACanvas2D;
newsize, xpos, ypos, cw, ch, hcw, hch, i: integer;
bm: TBitmap;
radius, step, angle, schaal: single;
aantal, ruimte, skip: integer;
begin
aantal := 13;
radius := DegToRad( SEGMENT/13*aantal ); // the radius of the cards in the hand
step := radius / aantal;
angle := radius / 2 - radius + step / 2; // the angle at which to show the card
schaal := scale*0.7;
ruimte := round(shift*0.5);
skip := floor((13-length(player.hand))/2);
newsize := ceil(diagonal*schaal); // the diagonal size of the card (to leave room for rotation)
cw := round(CARDWIDTH*schaal); // scaled card width and height
ch := round(CARDHEIGHT*schaal);
hcw := round(-HALFCARDWIDTH*schaal); // scaled half card width and height (negative)
hch := round(-HALFCARDHEIGHT*schaal);
// generate the scaled card
bm := TBitmap.Create;
cardlist.GetBitmap(53, bm);
card := TBGRABitmap.Create(bm, true);
card.ResampleFilter := rfLinear; //rfBox; //rfBestQuality;
vcard := card.Resample(cw, ch) as TBGRABitmap;
hcard := vcard.RotateCW as TBGRABitmap;
xpos := player.position.x;
ypos := player.position.y;
player.layer.FillTransparent;
// draw the card in a rotated box
box := TBGRABitmap.Create(newsize, newsize, BGRAPixelTransparent);
ctx := box.Canvas2D;
ctx.antialiasing := false;
ctx.translate(round(newsize / 2), round(newsize / 2)); // center of the box
ctx.rotate(angle+skip*step);
case player.location of
2: begin // West
ypos -= round((length(player.hand)*ruimte)/2)+cw;
for i := Low(player.hand) to High(player.hand)-1 do begin
ctx.drawImage(hcard, hch, hcw);
player.layer.Canvas2d.drawImage(box, xpos, ypos);
ctx.rotate(step);
box.FillTransparent;
ypos += ruimte;
end;
end;
3: begin // North
xpos += round(length(player.hand)/2)+hcw;
for i := Low(player.hand) to High(player.hand)-1 do begin
ctx.drawImage(vcard, hcw, hch);
player.layer.Canvas2d.drawImage(box, xpos, ypos);
ctx.rotate(step);
box.FillTransparent;
xpos -= ruimte;
end;
end;
4: begin // East
ypos += round((length(player.hand)*ruimte)/2)-cw-round(cw/2);
for i := Low(player.hand) to High(player.hand)-1 do begin
ctx.drawImage(hcard, hch, hcw);
player.layer.Canvas2d.drawImage(box, xpos, ypos);
ctx.rotate(step);
box.FillTransparent;
ypos -= ruimte;
end;
end;
end;
box.Free;
bm.Free;
card.Free;
vcard.Free;
hcard.Free;
end;
// draws a card on the virtual canvas and sets the mask,
// cards and masks are seperate layers
procedure TForm1.drawCard(mycard: TCard; size: integer);
var
card, newcard, box: TBGRABitmap;
ctx: TBGRACanvas2D;
newsize, xpos, ypos, cw, ch, hcw, hch, radius: integer;
pixel: TBGRAPixel;
bm: TBitmap;
begin
newsize := ceil(diagonal*scale); // the diagonal size of the card (to leave room for rotation)
cw := round(CARDWIDTH*scale); // scaled card width and height
ch := round(CARDHEIGHT*scale);
hcw := round(-HALFCARDWIDTH*scale); // scaled half card width and height (negative)
hch := round(-HALFCARDHEIGHT*scale);
radius := round(10*scale); // the radius of the rounded card corners (for drawing the mask)
// calculate the position where to copy the card into the layer
xpos := South.position.x-round(newsize+size/2) + mycard.x*space;
ypos := South.position.y-round(newsize/2) + mycard.y;
if mycard.deal then begin // modify the position for cards that are shifted out of the deck
xpos += round(shift * sin(mycard.angle));
ypos -= round(shift * cos(mycard.angle));
end;
// generate the scaled card
bm := TBitmap.Create;
cardlist.GetBitmap((mycard.suit-1)*13 + mycard.rank, bm);
card := TBGRABitmap.Create(bm, true);
card.ResampleFilter := rfLinear; //rfBox; //rfBestQuality;
newcard := card.Resample(cw, ch) as TBGRABitmap;
// draw the card in a rotated box
box := TBGRABitmap.Create(newsize, newsize, BGRAPixelTransparent);
ctx := box.Canvas2D;
ctx.antialiasing := false;
ctx.translate(round(newsize / 2), round(newsize / 2)); // center of the box
ctx.rotate(mycard.angle);
ctx.drawImage(newcard, hcw, hch);
// draw the box with card in a virtual layer
mycard.layer.FillTransparent;
mycard.layer.Canvas2d.drawImage(box, xpos, ypos);
// draw the mask of the card
pixel.red := mycard.id shl 4;
pixel.blue:= mycard.suit shl 4; // not used (only for mask coloring)
pixel.green:=mycard.rank shl 4; // not used (only for mask coloring)
pixel.alpha := 255;
ctx.fillStyle(pixel);
ctx.roundRect(hcw, hch, cw, ch, radius);
ctx.fill;
mycard.mask.FillTransparent;
mycard.mask.Canvas2d.drawImage(box, xpos, ypos);
bm.Free;
card.Free;
newcard.Free;
box.Free;
end;
// put the deal on the table
procedure TForm1.putDeal();
var
card, newcard, box: TBGRABitmap;
ctx: TBGRACanvas2D;
newsize, xpos, ypos, cw, ch, hcw, hch, i: integer;
bm: TBitmap;
mycard: TCard;
begin
newsize := ceil(diagonal*scale); // the diagonal size of the card (to leave room for rotation)
cw := round(CARDWIDTH*scale); // scaled card width and height
ch := round(CARDHEIGHT*scale);
hcw := round(-HALFCARDWIDTH*scale); // scaled half card width and height (negative)
hch := round(-HALFCARDHEIGHT*scale);
xpos := round(Width/2)-cw;
ypos := round(Height/2)-ch;
for i := Low(South.hand) to High(South.hand)-1 do begin
mycard := South.hand[i+1];
if (mycard.deal) then
xpos -= shift;
end;
deal.FillTransparent;
for i := Low(South.hand) to High(South.hand)-1 do begin
mycard := South.hand[i+1];
if (mycard.deal) then begin
// generate the scaled card
bm := TBitmap.Create;
cardlist.GetBitmap((mycard.suit-1)*13 + mycard.rank, bm);
card := TBGRABitmap.Create(bm, true);
card.ResampleFilter := rfLinear;
newcard := card.Resample(cw, ch) as TBGRABitmap;
// draw the card in a rotated box
box := TBGRABitmap.Create(newsize, newsize, BGRAPixelTransparent);
ctx := box.Canvas2D;
ctx.antialiasing := false;
ctx.translate(round(newsize / 2), round(newsize / 2)); // center of the box
ctx.rotate(degtorad(random(40)-20));
ctx.drawImage(newcard, hcw, hch);
deal.Canvas2d.drawImage(box, xpos, ypos);
xpos += 2*shift;
card.Free;
newcard.Free;
box.Free;
bm.Free;
end;
end;
end;
// clears the masks and draws the green background on the form
// the texture is painted on a virtual canvas that is later copied to the form
procedure TForm1.setBackground();
var
X, Y: integer;
texture: TBGRABitmap;
bm: TBitmap;
begin
bm := TBitmap.Create;
cardlist.GetBitmap(0, bm);
texture := TBGRABitmap.Create(bm, False);
bm.Free;
for X := 0 to (Screen.Width div texture.Width) do begin
for Y := 0 to (Screen.Height div texture.Height) do begin
background.Canvas2d.drawImage(texture, X * texture.Width, Y * texture.Height);
end;
end;
FreeAndNil(texture);
end;
|
unit Aurelius.Drivers.AnyDac;
{$I Aurelius.inc}
interface
uses
Classes, DB, Variants, Generics.Collections, FMX.Dialogs, System.SysUtils, FireDAC.Stan.Error,
FireDAC.Comp.Client, FireDAC.Stan.Intf, FireDAC.Stan.Param,
Aurelius.Drivers.Base,
Aurelius.Drivers.Interfaces;
type
TAnyDacResultSetAdapter = class(TDriverResultSetAdapter<TFDQuery>)
end;
TAnyDacStatementAdapter = class(TInterfacedObject, IDBStatement, IDBDatasetStatement)
private
FFDQuery: TFDQuery;
function GetDataset: TDataset;
public
constructor Create(AADQuery: TFDQuery);
destructor Destroy; override;
procedure SetSQLCommand(SQLCommand: string);
procedure SetParams(Params: TEnumerable<TDBParam>);
procedure Execute;
function ExecuteQuery: IDBResultSet;
end;
TAnyDacConnectionAdapter = class(TDriverConnectionAdapter<TFDConnection>, IDBConnection)
public
procedure Connect;
procedure Disconnect;
function IsConnected: Boolean;
function CreateStatement: IDBStatement;
function BeginTransaction: IDBTransaction;
function RetrieveSqlDialect: string; override;
end;
TAnyDacTransactionAdapter = class(TInterfacedObject, IDBTransaction)
private
FADConnection: TFDConnection;
public
constructor Create(ADConnection: TFDConnection);
procedure Commit;
procedure Rollback;
end;
implementation
{ TAnyDacStatemenTFDapter }
uses
Aurelius.Drivers.Exceptions;
constructor TAnyDacStatemenTAdapter.Create(AADQuery: TFDQuery);
begin
FFDQuery := AADQuery;
end;
destructor TAnyDacStatemenTAdapter.Destroy;
begin
FFDQuery.Free;
inherited;
end;
procedure TAnyDacStatemenTAdapter.Execute;
begin
FFDQuery.ExecSQL;
end;
function TAnyDacStatemenTAdapter.ExecuteQuery: IDBResultSet;
var
ResultSet: TFDQuery;
I: Integer;
begin
ResultSet := TFDQuery.Create(nil);
try
ResultSet.Connection := FFDQuery.Connection;
ResultSet.SQL := FFDQuery.SQL;
for I := 0 to FFDQuery.Params.Count - 1 do
begin
ResultSet.Params[I].DataType := FFDQuery.Params[I].DataType;
ResultSet.Params[I].Value := FFDQuery.Params[I].Value;
end;
try
ResultSet.Open;
except on E: EFDException do
if E.FDCode = 308 then
try
ResultSet.Execute();
except on E: Exception do
raise;
end;
end;
except
ResultSet.Free;
raise;
end;
Result := TAnyDacResultSetAdapter.Create(ResultSet);
end;
function TAnyDacStatemenTAdapter.GetDataset: TDataset;
begin
Result := FFDQuery;
end;
procedure TAnyDacStatemenTAdapter.SetParams(Params: TEnumerable<TDBParam>);
var
P: TDBParam;
Parameter: TFDParam;
begin
for P in Params do
begin
Parameter := FFDQuery.ParamByName(P.ParamName);
Parameter.DataType := P.ParamType;
Parameter.Value := P.ParamValue;
end;
end;
procedure TAnyDacStatemenTAdapter.SetSQLCommand(SQLCommand: string);
begin
FFDQuery.SQL.Text := SQLCommand;
end;
{ TAnyDacConnectionAdapter }
procedure TAnyDacConnectionAdapter.Disconnect;
begin
if Connection <> nil then
Connection.Connected := False;
end;
function TAnyDacConnectionAdapter.RetrieveSqlDialect: string;
begin
if Connection = nil then
Exit('');
case Connection.RDBMSKind of
2:
result := 'MSSQL';
4:
result := 'MySQL';
8:
result := 'Firebird';
1:
result := 'Oracle';
10:
result := 'SQLite';
11:
result := 'PostgreSQL';
5:
result := 'DB2';
7:
result := 'ADVANTAGE';
else
// mkUnknown: ;
// mkOracle: ;
// mkMSAccess: ;
// mkDB2: ;
// mkASA: ;
// mkADS: ;
// mkSQLite: ;
// mkPostgreSQL: ;
// mkNexus: ;
// mkOther: ;
result := 'NOT_SUPPORTED';
end;
end;
function TAnyDacConnectionAdapter.IsConnected: Boolean;
begin
if Connection <> nil then
Result := Connection.Connected
else
Result := false;
end;
function TAnyDacConnectionAdapter.CreateStatement: IDBStatement;
var
Statement: TFDQuery;
begin
if Connection = nil then
Exit(nil);
Statement := TFDQuery.Create(nil);
try
Statement.Connection := Connection;
except
Statement.Free;
raise;
end;
Result := TAnyDacStatemenTAdapter.Create(Statement);
end;
procedure TAnyDacConnectionAdapter.Connect;
begin
if Connection <> nil then
Connection.Connected := True;
end;
function TAnyDacConnectionAdapter.BeginTransaction: IDBTransaction;
begin
if Connection = nil then
Exit(nil);
Connection.Connected := true;
if not Connection.InTransaction then
begin
Connection.StartTransaction;
Result := TAnyDacTransactionAdapter.Create(Connection);
end else
Result := TAnyDacTransactionAdapter.Create(nil);
end;
{ TAnyDacTransactionAdapter }
procedure TAnyDacTransactionAdapter.Commit;
begin
if (FADConnection = nil) then
Exit;
FADConnection.Commit;
end;
constructor TAnyDacTransactionAdapter.Create(ADConnection: TFDConnection);
begin
FADConnection := ADConnection;
end;
procedure TAnyDacTransactionAdapter.Rollback;
begin
if (FADConnection = nil) then
Exit;
FADConnection.Rollback;
end;
end.
|
program square100_for;
var
i: integer;
begin
for i := 1 to 100 do
writeln(i * i, ' ')
end.
|
(*
I want to thank all those you provided information on my request for
sunrise and sunset calculations. While the component and packages
looked quite nice, I felt it was a bit overboard. I did find some Java
code at the USGS site that I was able to convert. This is pretty
accurate to within about 30 seconds for latitude below 70 degrees and 10
minutes for latitudes above 70;
Here is the unit for those that would like to add this to their arsenal.
Jeff Steinkamp
*)
unit solar;
interface
uses
math,sysutils,dateutils;
type
TSun = record
srise : TDatetime;
sset : TDatetime;
snoon : TDatetime;
end;
function calcJD(ayear,amonth,aday : integer) : extended;
function SolarStuff(adate : TdateTime; alat,alon : extended) : TSun;
function calcJDfromJulianCent(t : extended): Extended;
function calcTimeJulianCent(jd : extended) : extended;
function calcSunSetUTC(jd,latitude,longitude : extended) :extended;
function calcSolarNoonUTC(t,longitude : Extended) : Extended;
function calcSunRiseUTC(jd,latitude,longitude : extended) :extended;
function calcHourAngleSunrise(lat,solarDec : extended) : extended;
function calcHourAngleSunset(lat,solarDec : extended) : extended;
function calcEquationOfTime(t:extended) : Extended;
function calcObliquityCorrection(t:extended) : extended;
function calcMeanObliquityOfEcliptic(t: Extended) : extended;
function calcGeoMeanLongSun(t:extended) : extended;
function calcEccentricityEarthOrbit(t : extended) : extended;
function calcJulianDaytoCent(jd : integer) : extended;
function CalcSunDeclination(t:extended): Extended;
function calcSunAapparentLong(t:extended) : extended;
function calcSunEqOfCenter(t:extended) : extended;
function calcGeoMeanAnomalySun(t : extended) : extended;
function calcSunTrueLong(t:extended) : extended;
//==============================================================================
implementation
//==============================================================================
function calcEquationOfTime(t:extended) : Extended;
//***************************************************************
// Purpose: calculate the difference between the true solar time
// and mean solar time
//
// Arguments: t: number of Julian centuries since J2000.0
//
// Return: Equation of time in minutes of time
//****************************************************************
var
epsilon,l0,e,m,y,Etime: extended;
sin2l0,sinm,cos2l0,sin4l0,sin2m : extended;
begin
epsilon := calcObliquityCorrection(t);
l0 := calcGeoMeanLongSun(t);
e := calcEccentricityEarthOrbit(t);
m := calcGeoMeanAnomalySun(t);
y := tan(degtorad(epsilon)/2.0);
y := y*y;
sin2l0 := sin(2.0 *degtorad(l0));
sinm := sin(degtorad(m));
cos2l0 := cos(2 * degtorad(l0));
sin4l0 := sin(4 * degtorad(l0));
sin2m := sin(2 * degtorad(m));
Etime := y * sin2l0 - 2.0 * e * sinm
+ 4.0 * e * y * sinm * -0.5 * y*y * sin4l0 - 1.25 * e * e * sin2m;
result := radtodeg(Etime) *4.0; // in minutes of time
end;
//------------------------------------------------------------------------------
function calcObliquityCorrection(t:extended) : extended;
//***************************************************************
// Purpose: calculate the correcrted obliquity of the ecliptic
//
// Arguments: t: number of Julian centuries since J2000.0
//
// Return: corrected obliquity in degrees
//****************************************************************
var
e0,omega : extended;
begin
e0 := calcMeanObliquityOfEcliptic(t);
omega := 125.04 - 1934.136 * t;
result := e0 + 0.00256 * cos(degtorad(omega)); //in degres
end;
//------------------------------------------------------------------------------
function calcMeanObliquityOfEcliptic(t: Extended) : extended;
//***************************************************************
// Purpose: calculate the mean obliquity of the ecliptic
//
// Arguments: t: number of Julian centuries since J2000.0
//
// Return: mean obliquity in degrees
//****************************************************************
var
sec : extended;
begin
sec := 21.448 - t*(46.82150 + t*(0.00059-t*(0.001813)));
result := 23.0 + (26.0 - sec/60.0)/60.0; //in degrees
end;
//------------------------------------------------------------------------------
function calcGeoMeanLongSun(t:extended) : extended;
//***************************************************************
// Purpose: calculate the Geometric Mean Longitude of the Sun
//
// Arguments: t: number of Julian centuries since J2000.0
//
// Return: Geometric Mean Longitude of the sun in degrees
//****************************************************************
var
l : extended;
begin
l := 280.46646 + t *(36000.76983 + 0.0003032 *t);
if l > 360.0 then l := l - 360;
if l < 0 then l := l + 360;
result := l; //in degrees;
end;
//------------------------------------------------------------------------------
function calcEccentricityEarthOrbit(t : extended) : extended;
//***************************************************************
// Purpose: calculate the eccentricity of earth's orbit
//
// Arguments: t: number of Julian centuries since J2000.0
//
// Return: unitless eccentricity
//****************************************************************
begin
result := 0.016708634 - t*(0.000042037 + 0.0000002367*t); // unitless
end;
//------------------------------------------------------------------------------
function calcGeoMeanAnomalySun(t : extended) : extended;
//***************************************************************
// Purpose: calculate the Geometric Mean Anomoly of the Sun
//
// Arguments: t: number of Julian centuries since J2000.0
//
// Return: Geometric Mean Anomoly of the sun in degrees
//****************************************************************
begin
result := 357.52911 + t*(35999.05029 - 0.0001537*t); // in degrees
end;
//------------------------------------------------------------------------------
function calcJulianDaytoCent(jd : integer) : extended;
//***************************************************************
// Purpose: convert the Julian dat to centuries since J2000.0
//
// Arguments: jd: Julian day of the year;
//
// Return: number of Julian centuries since J2000.0
//****************************************************************
begin
result := (jd-2451545.0/36525.0);
end;
//------------------------------------------------------------------------------
function CalcSunDeclination(t:extended): Extended;
//***************************************************************
// Purpose: calculate the declination of the sun
//
// Arguments: t: number of Julian centuries since J2000.0
//
// Return: suns's declination in degrees
//****************************************************************
var
e,lambda,sint,theta : extended;
begin
e := calcObliquityCorrection(t);
lambda := calcSunAapparentLong(t);
sint := sin(degtorad(e)) * sin(degtorad(lambda));
theta := radtodeg(arcsin(sint));
result := theta; //in degrees
end;
//------------------------------------------------------------------------------
function calcSunAapparentLong(t:extended) : extended;
//***************************************************************
// Purpose: calculate the apparent longitude of the sun
//
// Arguments: t: number of Julian centuries since J2000.0
//
// Return: suns's apparent longitude in degrees
//****************************************************************
var
alpha,omega,lambda : extended;
begin
alpha := calcSunTrueLong(t);
omega := 125.05 - 1934.136 * t;
lambda := alpha - 0.00569 - 0.00478 * sin(degtorad(omega));
result := lambda; // in degrees
end;
//------------------------------------------------------------------------------
function calcSunTrueLong(t:extended) : extended;
//***************************************************************
// Purpose: calculate the true longitude of the sun
//
// Arguments: t: number of Julian centuries since J2000.0
//
// Return: suns's true longitude in degrees
//****************************************************************
var
l0,c0 : extended;
begin
l0 := calcGeoMeanLongSun(t);
c0 := calcSunEqOfCenter(t);
result := l0 + c0; //in degrees
end;
//------------------------------------------------------------------------------
function calcSunEqOfCenter(t:extended) : extended;
//***************************************************************
// Purpose: calculate the equation of the center of the sun
//
// Arguments: t: number of Julian centuries since J2000.0
//
// Return: suns's equation of the center in degrees
//****************************************************************
var
m,mrad,sinm,sin2m,sin3m : extended;
begin
m := calcGeoMeanAnomalySun(t);
mrad := degtorad(m);
sinm := sin(mrad);
sin2m := sin(2*mrad);
sin3m := sin(3*mrad);
result := sinm*(1.914602 - t*(0.004817 + 0.000014*t))
+ sin2m*(0.019993 - 0.000101*t) + sin3m*0.000289; // in degrees
end;
//------------------------------------------------------------------------------
function calcHourAngleSunrise(lat,solarDec : extended) : extended;
//***************************************************************
// Purpose: calculate the hour angle of the sun at sunrise for the
// latitude
//
// Arguments: lat : latitude in degrees
// solarDec : declination angle of sun in degreees
//
// Return: hour angle of sunrise in radians
//****************************************************************
var
latrad,sdrad,haarg,ha : extended;
begin
latrad := degtorad(lat);
sdrad := degtorad(solardec);
haarg :=
(cos(degtorad(90.833))/cos(latrad)*cos(sdrad)-tan(latrad)*tan(sdrad));
ha :=
(arccos(cos(degtorad(90.833))/cos(latrad)*cos(sdrad)-tan(latrad)*tan(sdrad)));
result := ha;
end;
//------------------------------------------------------------------------------
function calcHourAngleSunset(lat,solarDec : extended) : extended;
//***************************************************************
// Purpose: calculate the hour angle of the sun at sunset for the
// latitude
//
// Arguments: lat : latitude in degrees
// solarDec : declination angle of sun in degreees
//
// Return: hour angle of sunset in radians
//****************************************************************
var
latrad,sdrad,haarg,ha : extended;
begin
latrad := degtorad(lat);
sdrad := degtorad(solardec);
haarg :=
(cos(degtorad(90.833))/cos(latrad)*cos(sdrad)-tan(latrad)*tan(sdrad));
ha :=
(arccos(cos(degtorad(90.833))/cos(latrad)*cos(sdrad)-tan(latrad)*tan(sdrad)));
result := -ha;
end;
//------------------------------------------------------------------------------
function calcSunRiseUTC(jd,latitude,longitude : extended) :extended;
//***************************************************************
// Purpose: calculate the UTC time of the sun at sunrise for the
// latitude
//
// Arguments: lat : latitude in degrees
// solarDec : declination angle of sun in degreees
//
// Return: time in minutes from zero
//****************************************************************
var
t,noonmin,tnoon,eqtime,solardec,hourangle : extended;
delta,timediff,timeutc,newt : extended;
begin
t := calcTimeJulianCent(JD);
//find the time of solar noon at the location, and use
//that declination. This is better than start of the julian day
noonmin := calcSolarNoonUTC(t,Longitude);
tnoon := calcTimeJulianCent(jd+noonmin/1440);
//** First pass to approximate sunrise using solar noon
eqtime := calcEquationofTime(tnoon);
solardec := calcSunDeclination(tnoon);
hourAngle := calcHourAngleSunrise(latitude,solarDec);
delta := longitude - radtodeg(hourangle);
timediff := 4 * delta; //in minutes of time
timeUTC := 720 + timeDiff - eqtime; // in minutes
//** Second pass including the fractional jday in gamma calc
newt := calctimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440);
eqtime := calcEquationOfTime(newt);
solarDec := calcSunDeclination(newt);
hourangle := calcHourAngleSunrise(latitude,solarDec);
delta := longitude - radtodeg(hourangle);
timediff := 4 * delta;
timeUTC := 720 + timeDiff - eqtime; //in minutes
result := timeUTC;
end;
//------------------------------------------------------------------------------
function calcSolarNoonUTC(t,longitude:extended) : Extended;
//***************************************************************
// Purpose: calculate the UTC time of solar noon for a given
// day and at the givin location on earth
//
// Arguments: t : number of Julian centuries since J2000.0
// longitude : longitude of boserver in degrees
//
// Return: time in minutes from zero
//****************************************************************
var
newt,eqtime,noonUTC : extended;
begin
newt := calcTimeJulianCent(calcJDFromJulianCent(t) + 0.5 +
longitude/360);
eqtime := calcEquationOfTime(newt);
NoonUTC := 720 + (longitude *4) - eqtime; //minutes
result := NoonUTC;
end;
//------------------------------------------------------------------------------
function calcSunSetUTC(jd,latitude,longitude : extended) :extended;
//***************************************************************
// Purpose: calculate the UTC time of the sun at sunset for the latitude
//
// Arguments: lat : latitude in degrees
// solarDec : declination angle of sun in degreees
//
// Return: time in minutes from zero
//****************************************************************
var
t,noonmin,tnoon,eqtime,solardec : extended;
hourangle,delta,timediff,timeutc,newt : extended;
begin
t := calcTimeJulianCent(JD);
//find the time of solar noon at the location, and use
//that declination. This is better than start of the julian day
noonmin := calcSolarNoonUTC(t,Longitude);
tnoon := calcTimeJulianCent(jd+noonmin/1440);
//** First pass to approximate sunrise using solar noon
eqtime := calcEquationofTime(tnoon);
solardec := calcSunDeclination(tnoon);
hourAngle := calcHourAngleSunset(latitude,solarDec);
delta := longitude - radtodeg(hourangle);
timediff := 4 * delta; //in minutes of time
timeUTC := 720 + timeDiff - eqtime; // in minutes
//** Second pass including the fractional jday in gamma calc
newt := calctimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440);
eqtime := calcEquationOfTime(newt);
solarDec := calcSunDeclination(newt);
hourangle := calcHourAngleSunset(latitude,solarDec);
delta := longitude - radtodeg(hourangle);
timediff := 4 * delta;
timeUTC := 720 + timeDiff - eqtime; //in minutes
result := timeUTC;
end;
//------------------------------------------------------------------------------
function calcTimeJulianCent(jd : extended) : extended;
//***************************************************************
// Purpose: Convert JulianDay to Centruies since J2000.0
//
// Arguments: jd : the julian day to convert
//
// Return: the T value corresponding to the julian day
//****************************************************************
begin
result := (jd - 2451545.0)/36525.0;
end;
//------------------------------------------------------------------------------
function calcJDfromJulianCent(t : extended): Extended;
//***************************************************************
// Purpose: Convert Centruies since J2000.0 to Julian Day
//
// Arguments: t : number of Julian centruies since J2000;
//
// Return: the Julian Day corresponding to the T value
//****************************************************************
begin
result := t * 36525.0 + 2451545.0;
end;
//------------------------------------------------------------------------------
function SolarStuff(adate : TDateTime; alat,alon : extended) : TSun;
//***************************************************************
// Purpose: calculate the sunrise, sunset and solar noon for a given
// date and location on the face of the earth
//
// Arguments: adate : the date in TDatetime format
// alat : latitude of location in degrees
// alon : longitude of location in degrees
//
// Return: Solar Sturcture containg sunrise, sunset and
// high noon in TdateTime format;
//****************************************************************
var
sunrise,sunset,noon,jd : extended;
sun : TSun;
begin
jd := calcJD(yearof(adate),monthof(adate),dayof(adate));
noon := calcSolarNoonUTC(calcTimeJulianCent(JD),alon);
sunrise := calcSunRiseUTC(jd,alat,alon);
sunset := calcSunSetUTC(jd,alat,alon);
sun.srise := adate + (sunrise/1440);
sun.sset := adate + (sunset/1440);
sun.snoon := adate + (noon/1440);
result := sun;
end;
//------------------------------------------------------------------------------
function calcJD(ayear,amonth,aday : integer) : extended;
//***************************************************************
// Purpose: Convert calandar day to Julian
//
// Arguments: ayear : 4 digit year
// amonth : 2 digit month
// aday : 2 digit dat
//
// Return: the Julian Day
//****************************************************************
var
a,b : integer;
begin
if amonth <= 2 then begin
ayear := ayear -1;
amonth := amonth + 12;
end;
a := trunc(ayear/100);
b := 2-a+trunc (a/4);
result := trunc(365.25 * (ayear + 4716)) + trunc(30.6001 *(amonth +1))
+ aday + b -1524.5;
end;
//==============================================================================
end.
|
unit FMain;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
System.Math.Vectors,
FMX.Types,
FMX.Controls,
FMX.Forms3D,
FMX.Types3D,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.Controls.Presentation,
FMX.StdCtrls,
FMX.Controls3D,
FMX.Layers3D,
FMX.Objects3D,
FMX.Ani,
Materials;
type
TFormMain = class(TForm3D)
Layer3D: TLayer3D;
LabelBackend: TLabel;
Plane1: TPlane;
FloatAnimationRotationY1: TFloatAnimation;
Plane2: TPlane;
FloatAnimationRotationY2: TFloatAnimation;
LabelFeather: TLabel;
TrackBarFeather: TTrackBar;
procedure Form3DCreate(Sender: TObject);
procedure Form3DRender(Sender: TObject; Context: TContext3D);
procedure TrackBarFeatherChange(Sender: TObject);
private
{ Private declarations }
FMaterialSource: TFeatheredEdgeMaterialSource;
class function LoadImage(const AResource: String): TBitmap; static;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.fmx}
{$R '..\Textures\Textures.res'}
procedure TFormMain.Form3DCreate(Sender: TObject);
begin
LabelBackend.Text := Context.ClassName;
FMaterialSource := TFeatheredEdgeMaterialSource.Create(Self);
var Image := LoadImage('LENA');
try
FMaterialSource.Image := Image;
finally
Image.Free;
end;
Plane1.MaterialSource := FMaterialSource;
Plane2.MaterialSource := FMaterialSource;
end;
procedure TFormMain.Form3DRender(Sender: TObject; Context: TContext3D);
begin
{$IF Defined(MACOS) and not Defined(IOS)}
{ Workaround for https://quality.embarcadero.com/browse/RSP-32121 }
if (GlobalUseMetal) then
Context.FillRect(Point3D(-Width, -Height, 100), Point3D(Width, Height, 100), 1, Color);
{$ENDIF}
end;
class function TFormMain.LoadImage(const AResource: String): TBitmap;
begin
Result := TBitmap.Create;
var Stream := TResourceStream.Create(HInstance, AResource, RT_RCDATA);
try
Result.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TFormMain.TrackBarFeatherChange(Sender: TObject);
begin
FMaterialSource.Feather := TrackBarFeather.Value;
end;
end.
|
unit RLMetaCLX;
interface
uses
{$IFDEF LINUX}
xlib, QConsts,
{$ELSE}
Windows, SysUtils,
{$endif}
Types, QGraphics, Qt, Classes, Math, QStdCtrls,
RLMetaFile, RLUtils, RLConsts;
type
TPointArray=array of TPoint;
function ToMetaRect(const aSource:TRect):TRLMetaRect;
function ToMetaColor(aSource:TColor):TRLMetaColor;
function ToMetaPenMode(aSource:TPenMode):TRLMetaPenMode;
function ToMetaPenStyle(aSource:TPenStyle):TRLMetaPenStyle;
procedure ToMetaPen(aSource:TPen; aDest:TRLMetaPen);
function ToMetaBrushStyle(aSource:TBrushStyle):TRLMetaBrushStyle;
procedure ToMetaBrush(aSource:TBrush; aDest:TRLMetaBrush);
function ToMetaPoint(const aSource:TPoint):TRLMetaPoint;
function ToMetaPointArray(const aSource:array of TPoint):TRLMetaPointArray;
function ToMetaFontCharset(aSource:TFontCharset):TRLMetaFontCharset;
function ToMetaFontPitch(aSource:TFontPitch):TRLMetaFontPitch;
function ToMetaFontStyles(aSource:TFontStyles):TRLMetaFontStyles;
procedure ToMetaFont(aSource:TFont; aDest:TRLMetaFont);
function ToMetaGraphic(aSource:TGraphic):string;
function ToMetaTextAlignment(aSource:TAlignment):TRLMetaTextAlignment;
function ToMetaTextLayout(aSource:TTextLayout):TRLMetaTextLayout;
function FromMetaRect(const aSource:TRLMetaRect):TRect;
function FromMetaPoint(const aSource:TRLMetaPoint):TPoint;
function FromMetaColor(const aSource:TRLMetaColor):TColor;
function FromMetaPenMode(aSource:TRLMetaPenMode):TPenMode;
function FromMetaPenStyle(aSource:TRLMetaPenStyle):TPenStyle;
procedure FromMetaPen(aSource:TRLMetaPen; aDest:TPen);
function FromMetaBrushStyle(aSource:TRLMetaBrushStyle):TBrushStyle;
procedure FromMetaBrush(aSource:TRLMetaBrush; aDest:TBrush);
function FromMetaFontStyles(aSource:TRLMetaFontStyles):TFontStyles;
function FromMetaFontCharset(aSource:TRLMetaFontCharset):TFontCharset;
function FromMetaFontPitch(aSource:TRLMetaFontPitch):TFontPitch;
procedure FromMetaFont(aSource:TRLMetaFont; aDest:TFont; aFactor:double=1);
function FromMetaGraphic(const aSource:string):TGraphic;
function FromMetaPointArray(const aSource:TRLMetaPointArray):TPointArray;
function FromMetaTextAlignment(aSource:TRLMetaTextAlignment):TAlignment;
function FromMetaTextLayout(aSource:TRLMetaTextLayout):TTextLayout;
//
procedure PenInflate(aPen:TPen; aFactor:double);
procedure CanvasStart(aCanvas:TCanvas);
procedure CanvasStop(aCanvas:TCanvas);
function CanvasGetClipRect(aCanvas:TCanvas):TRect;
procedure CanvasSetClipRect(aCanvas:TCanvas; const aRect:TRect);
procedure CanvasResetClipRect(aCanvas:TCanvas);
function CanvasGetRectData(aCanvas:TCanvas; const aRect:TRect):string;
procedure CanvasSetRectData(aCanvas:TCanvas; const aRect:TRect; const aData:string; aParity:boolean);
procedure CanvasStretchDraw(aCanvas:TCanvas; const aRect:TRect; const aData:string; aParity:boolean);
procedure CanvasTextRectEx(aCanvas:TCanvas; const aRect:TRect; aX,aY:integer; const aText:string; aAlignment:TRLMetaTextAlignment; aLayout:TRLMetaTextLayout; aTextFlags:TRLMetaTextFlags);
function CanvasGetPixels(aCanvas:TCanvas; X,Y:integer):TColor;
procedure CanvasLineToEx(aCanvas:TCanvas; X,Y:integer);
procedure FontGetMetrics(const aFontName:string; aFontStyles:TFontStyles; var aFontRec:TRLMetaFontMetrics);
function CanvasGetDescent(aCanvas:TCanvas):integer;
implementation
{ CONVERSION }
function ToMetaRect(const aSource:TRect):TRLMetaRect;
begin
result.Left :=aSource.Left;
result.Top :=aSource.Top;
result.Right :=aSource.Right;
result.Bottom:=aSource.Bottom;
end;
function ToMetaColor(aSource:TColor):TRLMetaColor;
var
rgb:cardinal;
begin
rgb:=ColorToRGB(aSource);
result.Red :=byte(rgb);
result.Green:=byte(rgb shr 8);
result.Blue :=byte(rgb shr 16);
end;
function ToMetaPenMode(aSource:TPenMode):TRLMetaPenMode;
begin
case aSource of
pmBlack : result:=MetaPenModeBlack;
pmWhite : result:=MetaPenModeWhite;
pmNop : result:=MetaPenModeNop;
pmNot : result:=MetaPenModeNot;
pmCopy : result:=MetaPenModeCopy;
pmNotCopy : result:=MetaPenModeNotCopy;
pmMergePenNot: result:=MetaPenModeMergePenNot;
pmMaskPenNot : result:=MetaPenModeMaskPenNot;
pmMergeNotPen: result:=MetaPenModeMergeNotPen;
pmMaskNotPen : result:=MetaPenModeMaskNotPen;
pmMerge : result:=MetaPenModeMerge;
pmNotMerge : result:=MetaPenModeNotMerge;
pmMask : result:=MetaPenModeMask;
pmNotMask : result:=MetaPenModeNotMask;
pmXor : result:=MetaPenModeXor;
pmNotXor : result:=MetaPenModeNotXor;
else
result:=MetaPenModeCopy;
end;
end;
function ToMetaPenStyle(aSource:TPenStyle):TRLMetaPenStyle;
begin
case aSource of
psSolid : result:=MetaPenStyleSolid;
psDash : result:=MetaPenStyleDash;
psDot : result:=MetaPenStyleDot;
psDashDot : result:=MetaPenStyleDashDot;
psDashDotDot : result:=MetaPenStyleDashDotDot;
psClear : result:=MetaPenStyleClear;
//psInsideFrame: result:=MetaPenStyleInsideFrame;
else
result:=MetaPenStyleSolid;
end;
end;
procedure ToMetaPen(aSource:TPen; aDest:TRLMetaPen);
begin
aDest.Color:=ToMetaColor(aSource.Color);
aDest.Mode :=ToMetaPenMode(aSource.Mode);
aDest.Style:=ToMetaPenStyle(aSource.Style);
aDest.Width:=aSource.Width;
end;
function ToMetaBrushStyle(aSource:TBrushStyle):TRLMetaBrushStyle;
begin
case aSource of
bsSolid : result:=MetaBrushStyleSolid;
bsClear : result:=MetaBrushStyleClear;
bsHorizontal: result:=MetaBrushStyleHorizontal;
bsVertical : result:=MetaBrushStyleVertical;
bsFDiagonal : result:=MetaBrushStyleFDiagonal;
bsBDiagonal : result:=MetaBrushStyleBDiagonal;
bsCross : result:=MetaBrushStyleCross;
bsDiagCross : result:=MetaBrushStyleDiagCross;
else
result:=MetaBrushStyleSolid;
end;
end;
procedure ToMetaBrush(aSource:TBrush; aDest:TRLMetaBrush);
begin
aDest.Color:=ToMetaColor(aSource.Color);
aDest.Style:=ToMetaBrushStyle(aSource.Style);
end;
function ToMetaPoint(const aSource:TPoint):TRLMetaPoint;
begin
result.X:=aSource.X;
result.Y:=aSource.Y;
end;
function ToMetaPointArray(const aSource:array of TPoint):TRLMetaPointArray;
var
i:integer;
begin
SetLength(result,High(aSource)+1);
for i:=0 to High(aSource) do
result[i]:=ToMetaPoint(aSource[i]);
end;
function ToMetaFontCharset(aSource:TFontCharset):TRLMetaFontCharset;
begin
result:=TRLMetaFontCharset(aSource);
end;
function ToMetaFontPitch(aSource:TFontPitch):TRLMetaFontPitch;
begin
case aSource of
fpDefault : result:=MetaFontPitchDefault;
fpVariable: result:=MetaFontPitchVariable;
fpFixed : result:=MetaFontPitchFixed;
else
result:=MetaFontPitchDefault;
end;
end;
function ToMetaFontStyles(aSource:TFontStyles):TRLMetaFontStyles;
begin
result:=0;
if fsBold in aSource then
result:=result or MetaFontStyleBold;
if fsItalic in aSource then
result:=result or MetaFontStyleItalic;
if fsUnderline in aSource then
result:=result or MetaFontStyleUnderline;
if fsStrikeOut in aSource then
result:=result or MetaFontStyleStrikeOut;
end;
procedure ToMetaFont(aSource:TFont; aDest:TRLMetaFont);
begin
aDest.PixelsPerInch:=aSource.PixelsPerInch;
aDest.Charset :=ToMetaFontCharset(aSource.Charset);
aDest.Color :=ToMetaColor(aSource.Color);
aDest.Height :=aSource.Height;
aDest.Name :=aSource.Name;
aDest.Pitch :=ToMetaFontPitch(aSource.Pitch);
aDest.Size :=aSource.Size;
aDest.Style :=ToMetaFontStyles(aSource.Style);
end;
function ToMetaGraphic(aSource:TGraphic):string;
var
s:TStringStream;
m:TBitmap;
g:TGraphic;
begin
m:=nil;
s:=TStringStream.Create('');
try
g:=aSource;
// identifica os tipos nativos
if g=nil then
s.WriteString('NIL')
else if g is TBitmap then
s.WriteString('BMP')
else if g is TIcon then
s.WriteString('ICO')
else
begin
// qualquer outro formato é transformado em bmp para ficar compatível com um carregador de qualquer plataforma
m:=TBitmap.Create;
m.Width :=aSource.Width;
m.Height:=aSource.Height;
g:=m;
m.Canvas.Draw(0,0,aSource);
s.WriteString('BMP');
end;
if Assigned(g) then
g.SaveToStream(s);
result:=s.DataString;
finally
if Assigned(m) then
m.free;
s.free;
end;
end;
function ToMetaTextAlignment(aSource:TAlignment):TRLMetaTextAlignment;
begin
case aSource of
taLeftJustify : result:=MetaTextAlignmentLeft;
taRightJustify: result:=MetaTextAlignmentRight;
taCenter : result:=MetaTextAlignmentCenter;
else
if aSource=succ(taCenter) then
result:=MetaTextAlignmentJustify
else
result:=MetaTextAlignmentLeft;
end;
end;
function ToMetaTextLayout(aSource:TTextLayout):TRLMetaTextLayout;
begin
case aSource of
tlTop : result:=MetaTextLayoutTop;
tlBottom: result:=MetaTextLayoutBottom;
tlCenter: result:=MetaTextLayoutCenter;
else
if aSource=succ(tlCenter) then
result:=MetaTextLayoutJustify
else
result:=MetaTextLayoutTop;
end;
end;
function FromMetaRect(const aSource:TRLMetaRect):TRect;
begin
result.Left :=aSource.Left;
result.Top :=aSource.Top;
result.Right :=aSource.Right;
result.Bottom:=aSource.Bottom;
end;
function FromMetaPoint(const aSource:TRLMetaPoint):TPoint;
begin
result.X:=aSource.X;
result.Y:=aSource.Y;
end;
function FromMetaColor(const aSource:TRLMetaColor):TColor;
begin
result:=RGB(aSource.Red,aSource.Green,aSource.Blue);
end;
function FromMetaPenMode(aSource:TRLMetaPenMode):TPenMode;
begin
case aSource of
MetaPenModeBlack : result:=pmBlack;
MetaPenModeWhite : result:=pmWhite;
MetaPenModeNop : result:=pmNop;
MetaPenModeNot : result:=pmNot;
MetaPenModeCopy : result:=pmCopy;
MetaPenModeNotCopy : result:=pmNotCopy;
MetaPenModeMergePenNot: result:=pmMergePenNot;
MetaPenModeMaskPenNot : result:=pmMaskPenNot;
MetaPenModeMergeNotPen: result:=pmMergeNotPen;
MetaPenModeMaskNotPen : result:=pmMaskNotPen;
MetaPenModeMerge : result:=pmMerge;
MetaPenModeNotMerge : result:=pmNotMerge;
MetaPenModeMask : result:=pmMask;
MetaPenModeNotMask : result:=pmNotMask;
MetaPenModeXor : result:=pmXor;
MetaPenModeNotXor : result:=pmNotXor;
else
result:=pmCopy;
end;
end;
function FromMetaPenStyle(aSource:TRLMetaPenStyle):TPenStyle;
begin
case aSource of
MetaPenStyleSolid : result:=psSolid;
MetaPenStyleDash : result:=psDash;
MetaPenStyleDot : result:=psDot;
MetaPenStyleDashDot : result:=psDashDot;
MetaPenStyleDashDotDot : result:=psDashDotDot;
MetaPenStyleClear : result:=psClear;
//MetaPenStyleInsideFrame: result:=psInsideFrame;
else
result:=psSolid;
end;
end;
procedure FromMetaPen(aSource:TRLMetaPen; aDest:TPen);
begin
aDest.Color:=FromMetaColor(aSource.Color);
aDest.Mode :=FromMetaPenMode(aSource.Mode);
aDest.Style:=FromMetaPenStyle(aSource.Style);
aDest.Width:=aSource.Width;
end;
function FromMetaBrushStyle(aSource:TRLMetaBrushStyle):TBrushStyle;
begin
case aSource of
MetaBrushStyleSolid : result:=bsSolid;
MetaBrushStyleClear : result:=bsClear;
MetaBrushStyleHorizontal: result:=bsHorizontal;
MetaBrushStyleVertical : result:=bsVertical;
MetaBrushStyleFDiagonal : result:=bsFDiagonal;
MetaBrushStyleBDiagonal : result:=bsBDiagonal;
MetaBrushStyleCross : result:=bsCross;
MetaBrushStyleDiagCross : result:=bsDiagCross;
else
result:=bsSolid;
end;
end;
procedure FromMetaBrush(aSource:TRLMetaBrush; aDest:TBrush);
begin
aDest.Color:=FromMetaColor(aSource.Color);
aDest.Style:=FromMetaBrushStyle(aSource.Style);
end;
function FromMetaFontStyles(aSource:TRLMetaFontStyles):TFontStyles;
begin
result:=[];
if (MetaFontStyleBold and aSource)=MetaFontStyleBold then
Include(result,fsBold);
if (MetaFontStyleItalic and aSource)=MetaFontStyleItalic then
Include(result,fsItalic);
if (MetaFontStyleUnderline and aSource)=MetaFontStyleUnderline then
Include(result,fsUnderline);
if (MetaFontStyleStrikeOut and aSource)=MetaFontStyleStrikeOut then
Include(result,fsStrikeOut);
end;
function FromMetaFontCharset(aSource:TRLMetaFontCharset):TFontCharset;
begin
result:=TFontCharset(aSource);
end;
function FromMetaFontPitch(aSource:TRLMetaFontPitch):TFontPitch;
begin
case aSource of
MetaFontPitchDefault : result:=fpDefault;
MetaFontPitchVariable: result:=fpVariable;
MetaFontPitchFixed : result:=fpFixed;
else
result:=fpDefault;
end;
end;
procedure FromMetaFont(aSource:TRLMetaFont; aDest:TFont; aFactor:double=1);
var
a,b:integer;
begin
a:=aSource.PixelsPerInch;
if a=0 then
a:=ScreenPPI;
b:=aDest.PixelsPerInch;
if b=0 then
b:=ScreenPPI;
//
//aDest.PixelsPerInch:=aSource.PixelsPerInch;
aDest.Charset :=FromMetaFontCharset(aSource.Charset);
aDest.Color :=FromMetaColor(aSource.Color);
//aDest.Height :=aSource.Height;
aDest.Name :=aSource.Name;
aDest.Pitch :=FromMetaFontPitch(aSource.Pitch);
aDest.Size :=Round(aSource.Size*aFactor*a/b);
aDest.Style :=FromMetaFontStyles(aSource.Style);
end;
function FromMetaGraphic(const aSource:string):TGraphic;
var
s:TStringStream;
t:string;
begin
if aSource='' then
result:=nil
else
begin
s:=TStringStream.Create(aSource);
try
s.Seek(0,soFromBeginning);
t:=s.ReadString(3);
if t='NIL' then
result:=nil
else if t='BMP' then
result:=TBitmap.Create
else if t='ICO' then
result:=TIcon.Create
else
result:=nil;
if Assigned(result) then
result.LoadFromStream(s);
finally
s.free;
end;
end;
end;
function FromMetaPointArray(const aSource:TRLMetaPointArray):TPointArray;
var
i:integer;
begin
SetLength(result,High(aSource)+1);
for i:=0 to High(aSource) do
result[i]:=FromMetaPoint(aSource[i]);
end;
function FromMetaTextAlignment(aSource:TRLMetaTextAlignment):TAlignment;
begin
case aSource of
MetaTextAlignmentLeft : result:=taLeftJustify;
MetaTextAlignmentRight : result:=taRightJustify;
MetaTextAlignmentCenter : result:=taCenter;
MetaTextAlignmentJustify: result:=succ(taCenter);
else
result:=taLeftJustify;
end;
end;
function FromMetaTextLayout(aSource:TRLMetaTextLayout):TTextLayout;
begin
case aSource of
MetaTextLayoutTop : result:=tlTop;
MetaTextLayoutBottom : result:=tlBottom;
MetaTextLayoutCenter : result:=tlCenter;
MetaTextLayoutJustify: result:=succ(tlCenter);
else
result:=tlTop;
end;
end;
{ MISC }
procedure PenInflate(aPen:TPen; aFactor:double);
begin
if aPen.Width>1 then
aPen.Width:=Max(1,Trunc(aPen.Width*aFactor));
end;
procedure CanvasStart(aCanvas:TCanvas);
begin
aCanvas.Start;
end;
procedure CanvasStop(aCanvas:TCanvas);
begin
aCanvas.Stop;
end;
function CanvasGetClipRect(aCanvas:TCanvas):TRect;
begin
result:=aCanvas.ClipRect;
end;
procedure CanvasSetClipRect(aCanvas:TCanvas; const aRect:TRect);
var
isnull:boolean;
begin
isnull:=((aRect.Right-aRect.Left)=0) or ((aRect.Bottom-aRect.Top)=0);
if isnull then
aCanvas.ResetClipRegion
else
aCanvas.SetClipRect(aRect);
end;
procedure CanvasResetClipRect(aCanvas:TCanvas);
begin
aCanvas.ResetClipRegion;
end;
function CanvasGetRectData(aCanvas:TCanvas; const aRect:TRect):string;
var
graphic:TBitmap;
begin
graphic:=TBitmap.Create;
with graphic do
try
Width :=aRect.Right-aRect.Left;
Height :=aRect.Bottom-aRect.Top;
PixelFormat:=pf32bit;
Canvas.CopyRect(Rect(0,0,Width,Height),aCanvas,aRect);
result:=ToMetaGraphic(graphic);
finally
graphic.free;
end;
end;
procedure CanvasSetRectData(aCanvas:TCanvas; const aRect:TRect; const aData:string; aParity:boolean);
var
graphic:TGraphic;
auxrect:TRect;
aux :integer;
begin
graphic:=FromMetaGraphic(aData);
if graphic<>nil then
try
auxrect:=aRect;
if aParity then
begin
aux :=(auxrect.Right-auxrect.Left) div graphic.Width;
auxrect.Right:=auxrect.Left+aux*graphic.Width+1;
end;
aCanvas.StretchDraw(auxrect,graphic);
finally
graphic.free;
end;
end;
procedure CanvasStretchDraw(aCanvas:TCanvas; const aRect:TRect; const aData:string; aParity:boolean);
begin
CanvasSetRectData(aCanvas,aRect,aData,aParity);
end;
procedure CanvasTextRectEx(aCanvas:TCanvas; const aRect:TRect; aX,aY:integer; const aText:string; aAlignment:TRLMetaTextAlignment; aLayout:TRLMetaTextLayout; aTextFlags:TRLMetaTextFlags);
var
delta,left,top,txtw,txth,wid,i:integer;
buff:string;
begin
buff :=aText;
delta:=aCanvas.TextWidth(' ') div 2;
txtw :=aCanvas.TextWidth(buff+' ');
txth :=aCanvas.TextHeight(buff+' ');
case aAlignment of
MetaTextAlignmentCenter: left:=(aRect.Left+aRect.Right-txtw) div 2;
MetaTextAlignmentRight : left:=aRect.Right-txtw+delta;
else
left:=aX+delta;
end;
case aLayout of
MetaTextLayoutCenter: top:=(aRect.Top+aRect.Bottom-txth) div 2;
MetaTextLayoutBottom: top:=aRect.Bottom-txth;
else
top:=aY;
end;
if aAlignment=MetaTextAlignmentJustify then
begin
wid:=aRect.Right-left;
i :=Length(buff);
while (aCanvas.TextWidth(buff+#32)<=wid) and IterateJustification(buff,i) do;
end;
if (aTextFlags and MetaTextFlagAutoSize)=MetaTextFlagAutoSize then
aCanvas.TextOut(left,top,buff)
else
aCanvas.TextRect(aRect,left,top,buff);
end;
function CanvasGetPixels(aCanvas:TCanvas; X,Y:integer):TColor;
begin
with TBitmap.Create do
try
Width :=1;
Height :=1;
PixelFormat:=pf32bit;
Canvas.CopyRect(Rect(0,0,1,1),aCanvas,Rect(X,Y,X+1,Y+1));
with TRGBArray(ScanLine[Y]^)[X] do
result:=RGB(rgbRed,rgbGreen,rgbBlue);
finally
free;
end;
end;
procedure CanvasLineToEx(aCanvas:TCanvas; X,Y:integer);
type
TPattern=record
Count :byte;
Lengths:array[0..5] of byte;
end;
const
Patterns:array[TPenStyle] of TPattern=((Count:0;Lengths:(0,0,0,0,0,0)), // psSolid
(Count:2;Lengths:(3,1,0,0,0,0)), // psDash
(Count:2;Lengths:(1,1,0,0,0,0)), // psDot
(Count:4;Lengths:(2,1,1,1,0,0)), // psDashDot
(Count:6;Lengths:(3,1,1,1,1,1)), // psDashDotDot
(Count:0;Lengths:(0,0,0,0,0,0)) // psClear
{$ifndef CLX}
,(Count:0;Lengths:(0,0,0,0,0,0))
{$endif}
); // psInsideFrame
var
x0,y0 :integer;
xb,yb :integer;
i,p,dist:integer;
theta :double;
sn,cs :double;
patt :^TPattern;
forecl :TColor;
backcl :TColor;
width0 :integer;
style0 :TPenStyle;
factor :integer;
cli :integer;
begin
if (Patterns[aCanvas.Pen.Style].Count=0) or (aCanvas.Pen.Width<=1) then
aCanvas.LineTo(X,Y)
else
begin
style0:=aCanvas.Pen.Style;
width0:=aCanvas.Pen.Width;
x0 :=aCanvas.PenPos.X;
y0 :=aCanvas.PenPos.Y;
theta :=ArcTan((Y-y0)/(X-x0));
sn :=Sin(theta);
cs :=Cos(theta);
dist :=Round(Sqrt(Sqr(X-x0)+Sqr(Y-y0)));
patt :=@Patterns[aCanvas.Pen.Style];
p :=0;
i :=0;
forecl:=aCanvas.Pen.Color;
backcl:=aCanvas.Brush.Color;
factor:=4*aCanvas.Pen.Width;
aCanvas.Pen.Style:=psSolid;
if aCanvas.Brush.Style<>bsClear then
begin
aCanvas.Pen.Color:=backcl;
aCanvas.LineTo(X,Y);
end;
aCanvas.Pen.Color:=forecl;
aCanvas.MoveTo(x0,y0);
cli:=0;
while i<dist do
begin
Inc(i,patt^.Lengths[p]*factor);
if not (i<dist) then
i:=dist;
xb:=x0+Round(i*cs);
yb:=y0+Round(i*sn);
if cli=0 then
aCanvas.LineTo(xb,yb)
else
aCanvas.MoveTo(xb,yb);
cli:=1-cli;
p :=Succ(p) mod patt^.Count;
end;
aCanvas.Pen.Style:=style0;
aCanvas.Pen.Width:=width0;
end;
end;
procedure FontGetMetrics(const aFontName:string; aFontStyles:TFontStyles; var aFontRec:TRLMetaFontMetrics);
var
i:integer;
begin
with TBitmap.Create do
try
Width :=1;
Height:=1;
Canvas.Font.Name :=aFontName;
Canvas.Font.Style:=aFontStyles;
Canvas.Font.Size :=750;
//
aFontRec.TrueType :=true;
aFontRec.BaseFont :=aFontName;
aFontRec.FirstChar:=32;
aFontRec.LastChar :=255;
for i:=aFontRec.FirstChar to aFontRec.LastChar do
aFontRec.Widths[i]:=Canvas.TextWidth(Chr(i));
//
aFontRec.FontDescriptor.Name :=aFontName;
aFontRec.FontDescriptor.Styles :='';
if fsBold in aFontStyles then
aFontRec.FontDescriptor.Styles:=aFontRec.FontDescriptor.Styles+'Bold';
if fsItalic in aFontStyles then
aFontRec.FontDescriptor.Styles:=aFontRec.FontDescriptor.Styles+'Italic';
if fsUnderline in aFontStyles then
aFontRec.FontDescriptor.Styles:=aFontRec.FontDescriptor.Styles+'Underline';
if fsStrikeOut in aFontStyles then
aFontRec.FontDescriptor.Styles:=aFontRec.FontDescriptor.Styles+'StrikeOut';
aFontRec.FontDescriptor.Flags :=32;
aFontRec.FontDescriptor.FontBBox :=Rect(-498,1023,1120,-307);
aFontRec.FontDescriptor.MissingWidth:=0;
aFontRec.FontDescriptor.StemV :=0;
aFontRec.FontDescriptor.StemH :=0;
aFontRec.FontDescriptor.ItalicAngle :=0;
aFontRec.FontDescriptor.CapHeight :=0;
aFontRec.FontDescriptor.XHeight :=0;
aFontRec.FontDescriptor.Ascent :=0;
aFontRec.FontDescriptor.Descent :=0;
aFontRec.FontDescriptor.Leading :=0;
aFontRec.FontDescriptor.MaxWidth :=0;
aFontRec.FontDescriptor.AvgWidth :=0;
finally
free;
end;
end;
function CanvasGetDescent(aCanvas:TCanvas):integer;
var
aux:TBitmap;
x,y:integer;
begin
aux:=TBitmap.Create;
try
aux.Width :=1;
aux.Height :=1;
aux.PixelFormat:=pf32bit;
aux.Canvas.Font.Assign(aCanvas.Font);
aux.Canvas.Font.Style :=aux.Canvas.Font.Style-[fsUnderline];
aux.Canvas.Font.Color :=clWhite;
aux.Canvas.Brush.Style:=bsSolid;
aux.Canvas.Brush.Color:=clBlack;
aux.Width :=aux.Canvas.TextWidth('L');
aux.Height:=aux.Canvas.TextHeight('L');
aux.Canvas.TextOut(0,0,'L');
//
y:=aux.Height-1;
while y>=0 do
begin
x:=0;
while x<aux.Width do
begin
with TRGBArray(aux.ScanLine[y]^)[x] do
if RGB(rgbRed,rgbGreen,rgbBlue)<>0 then
Break;
Inc(x);
end;
if x<aux.Width then
Break;
Dec(y);
end;
//
Result:=aux.Height-1-y;
finally
aux.Free;
end;
end;
end.
|
unit prefs;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Spin, IniFiles, ExtCtrls;
type
TPrefs = record
UsePerformanceCounter: boolean;
TMSSequence: String;
Mode,Design,nSubj,Seed,Subj,Session,StimSec,ShamSec,
HitHotKey,MissHotKey,TMSHotKey,TMSratems,TMSinterlockms//TMSphasems,TMSOnMS,TMSOffMS
: integer;
end;
type
TSettingsForm = class(TForm)
Label1: TLabel;
StimSecEdit: TSpinEdit;
Label2: TLabel;
ShamSecEdit: TSpinEdit;
Label3: TLabel;
SeedEdit: TSpinEdit;
nSubjEdit: TSpinEdit;
Label4: TLabel;
DesignDrop: TComboBox;
Label5: TLabel;
OKbtn: TButton;
CancelBtn: TButton;
ModeEdit: TSpinEdit;
Label6: TLabel;
TMSPanel: TPanel;
Label7: TLabel;
TMSratemsEdit: TSpinEdit;
TMSinterlockmsEdit: TSpinEdit;
Label8: TLabel;
Label9: TLabel;
UsePerformanceCounterCheck: TCheckBox;
TMSSequenceEdit: TEdit;
private
{ Private declarations }
public
function IniFileX(lRead: boolean; lFilename: string; var lPrefs: TPrefs): boolean;
procedure SetDefaultPrefs (var lPrefs: TPrefs);
{ Public declarations }
end;
var
SettingsForm: TSettingsForm;
const
kVersion ='6May2010 Chris Rorden www.mricro.com';
kStdMode = 0;
kTMSMode = 1;
//kDefSeq = 'SSAAASSAAASSCCCSSCCC';
kDefSeq = 'SSSSAAAAAASSSSAAAAAASSSSCCCCCCSSSSCCCCCC';
implementation
{$R *.DFM}
procedure TSettingsForm.SetDefaultPrefs (var lPrefs: TPrefs);
var
i: integer;
begin
with lPrefs do begin
//ADU:= 2;
TMSHotKey := 33;
MissHotKey := 32;
HitHotKey := 32;
TMSSequence := kDefSeq;
Design := 0;
nSubj := 20;
Seed := 1492;
Subj := 1;
Session := 1;
StimSec := 1200;
ShamSec:= 20;
Mode := kStdMode;
TMSratems := 5000;
TMSinterlockms := 1;
//TMSphasems := TMSratems div 2;
//TMSOnMS := 30000;
//TMSOffMS := 20000;
UsePerformanceCounter := true;
end;//with lPrefs
end; //Proc SetDefaultPrefs
procedure IniInt(lRead: boolean; lIniFile: TIniFile; lIdent: string; var lValue: integer);
//read or write an integer value to the initialization file
var
lStr: string;
begin
if not lRead then begin
lIniFile.WriteString('INT',lIdent,IntToStr(lValue));
exit;
end;
lStr := lIniFile.ReadString('INT',lIdent, '');
if length(lStr) > 0 then
lValue := StrToInt(lStr);
end; //IniInt
function Bool2Char (lBool: boolean): char;
begin
if lBool then
result := '1'
else
result := '0';
end;
function Char2Bool (lChar: char): boolean;
begin
if lChar = '1' then
result := true
else
result := false;
end;
procedure IniBool(lRead: boolean; lIniFile: TIniFile; lIdent: string; var lValue: boolean);
//read or write a boolean value to the initialization file
var
lStr: string;
begin
if not lRead then begin
lIniFile.WriteString('BOOL',lIdent,Bool2Char(lValue));
exit;
end;
lStr := lIniFile.ReadString('BOOL',lIdent, '');
if length(lStr) > 0 then
lValue := Char2Bool(lStr[1]);
end; //IniBool
procedure IniStr(lRead: boolean; lIniFile: TIniFile; lIdent: string; var lValue: string);
//read or write a string value to the initialization file
begin
if not lRead then begin
lIniFile.WriteString('STR',lIdent,lValue);
exit;
end;
lValue := lIniFile.ReadString('STR',lIdent, '');
end; //IniStr
function TSettingsForm.IniFileX(lRead: boolean; lFilename: string; var lPrefs: TPrefs): boolean;
//Read or write initialization variables to disk
var
lIniFile: TIniFile;
lI: integer;
begin
result := false;
if lRead then
SetDefaultPrefs(lPrefs);
if (lRead) and (not Fileexists(lFilename)) then
exit;
lIniFile := TIniFile.Create(lFilename);
lI := 1;
IniStr(lRead,lIniFile,'TMSSequence',lPrefs.TMSSequence);
IniInt(lRead,lIniFile, (FormatDateTime('yyyymmdd_hhnnss', (now))),lI);
//IniInt(lRead,lIniFile, 'ADU',lPrefs.ADU);
IniInt(lRead,lIniFile, 'Design',lPrefs.Design);
IniInt(lRead,lIniFile, 'Seed',lPrefs.Seed);
IniInt(lRead,lIniFile, 'nSubj',lPrefs.nSubj);
IniInt(lRead,lIniFile, 'Subj',lPrefs.Subj);
IniInt(lRead,lIniFile, 'Phase',lPrefs.Session);
IniInt(lRead,lIniFile, 'StimSec',lPrefs.StimSec);
IniInt(lRead,lIniFile, 'ShamSec',lPrefs.ShamSec);
IniInt(lRead,lIniFile, 'Mode',lPrefs.Mode);
IniInt(lRead,lIniFile, 'TMSratems',lPrefs.TMSratems);
IniInt(lRead,lIniFile, 'TMSinterlockms',lPrefs.TMSinterlockms);
//IniInt(lRead,lIniFile, 'TMSphasems',lPrefs.TMSphasems);
IniInt(lRead,lIniFile, 'TMSHotKey',lPrefs.TMSHotKey);
IniInt(lRead,lIniFile, 'HitHotKey',lPrefs.HitHotKey);
IniInt(lRead,lIniFile, 'MissHotKey',lPrefs.MissHotKey);
//IniInt(lRead,lIniFile, 'TMSOnms',lPrefs.TMSOnms);
//IniInt(lRead,lIniFile, 'TMSOffms',lPrefs.TMSOffms);
IniBool(lRead,lIniFile, 'UsePerformanceCounter',lPrefs.UsePerformanceCounter);
lIniFile.Free;
end;
end.
|
unit uCacheObjects;
interface
uses
System.SysUtils, System.Generics.Collections;
type
TCacheObjects = class
private
FList: TObjectDictionary<string,TObject>;
function GetClassType<T: class>: string;
public
constructor Create;
destructor Destroy; Override;
function getInstance<T: class, constructor>: T; overload;
end;
implementation
uses
Rtti, TypInfo;
{ TCacheObjects }
constructor TCacheObjects.Create;
begin
Self.FList := TObjectDictionary<string,TObject>.Create;
end;
destructor TCacheObjects.Destroy;
var
vObject: TObject;
begin
for vObject in Self.FList.Values do
vObject.Free;
Self.FList.Free;
inherited;
end;
function TCacheObjects.GetClassType<T>: string;
begin
Result := GetTypeData(PTypeInfo(TypeInfo(T)))^.ClassType.ClassName;
end;
function TCacheObjects.getInstance<T>: T;
begin
if (Self.FList.ContainsKey(Self.GetClassType<T>)) then
Exit(Self.FList.Items[Self.GetClassType<T>] as T);
Result := T.Create;
Self.FList.Add(Self.GetClassType<T>, TObject(Result));
end;
end.
|
unit UMyCloudFileControl;
interface
type
{$Region ' 云路径 修改 ' }
// 上线 扫描云路径
TCloudPathOnlineScanHandle = class
public
OnlinePcID : string;
public
procedure SetOnlinePcID( _OnlinePcID : string );
procedure Update;
private
procedure AddToInfo;
end;
// 修改
TCloudPathChangeHandle = class
protected
CloudPath : string;
public
constructor Create( _CloudlPath : string );
end;
// 读取
TCloudPathReadHandle = class( TCloudPathChangeHandle )
public
procedure Update;virtual;
protected
procedure AddToInfo;
end;
// 添加
TCloudPathAddHandle = class( TCloudPathReadHandle )
public
procedure Update;override;
private
procedure AddToXml;
end;
// 移除
TCloudPathRemoveHandle = class( TCloudPathChangeHandle )
public
procedure Update;
private
procedure RemoveFromInfo;
procedure RemoveFromXml;
end;
{$EndRegion}
{$Region ' 云路径 拥有者 修改 ' }
// 修改
TCloudPathOwnerChangeHandle = class( TCloudPathChangeHandle )
public
OwnerPcID : string;
public
procedure SetOwnerPcID( _OwnerPcID : string );
end;
// 读取
TCloudPathOwnerReadHandle = class( TCloudPathOwnerChangeHandle )
public
FileSize : Int64;
FileCount : Integer;
public
LastScanTime : TDateTime;
public
procedure SetSpaceInfo( _FileSize : Int64; _FileCount : Integer );
procedure SetLastScanTime( _LastScanTime : TDateTime );
procedure Update;
private
procedure AddToInfo;
end;
// 设置 上一次 扫描时间
TCloudPathOwnerSetLastScanTimeHandle = class( TCloudPathOwnerChangeHandle )
public
LastScanTime : TDateTime;
public
procedure SetLastScanTime( _LastScanTime : TDateTime );
procedure Update;
private
procedure SetToInfo;
procedure SetToXml;
end;
// 删除
TCloudPathOwnerRemoveHandle = class( TCloudPathOwnerChangeHandle )
public
procedure Update;
private
procedure RemoveFromInfo;
procedure RemoveFromXml;
end;
{$Region ' 修改 空间信息 ' }
// 父类
TCloudPathOwnerChangeSpaceHandle = class( TCloudPathOwnerChangeHandle )
public
FileSize : Int64;
FileCount : Integer;
public
procedure SetSpaceInfo( _FileSize : Int64; _FileCount : Integer );
end;
// 添加
TCloudPathOwnerSpaceAddHandle = class( TCloudPathOwnerChangeSpaceHandle )
public
procedure Update;
private
procedure AddToInfo;
procedure AddToXml;
end;
// 删除
TCloudPathOwnerSpaceRemoveHandle = class( TCloudPathOwnerChangeSpaceHandle )
public
procedure Update;
private
procedure RemoveFromInfo;
procedure RemoveFromXml;
end;
// 设置
TCloudPathOwnerSpaceSetHandle = class( TCloudPathOwnerChangeSpaceHandle )
private
LastFileSize : Int64;
public
procedure SetLastFileSize( _LastFileSize : Int64 );
procedure Update;
private
procedure SetToInfo;
procedure SetToXml;
end;
{$EndRegion}
{$EndRegion}
// 云文件 控制器
TMyCloudFileControl = class
public
procedure AddSharePath( FullPath : string );
procedure RemoveSharePath( FullPath : string );
end;
const
CloudFileStatus_Loading = 'Loading';
CloudFileStatus_Loaded = 'Loaded';
var
MyCloudFileControl : TMyCloudFileControl;
implementation
uses UMyCloudPathInfo, UCloudPathInfoXml;
{ TMyCloudFileControl }
procedure TMyCloudFileControl.AddSharePath(FullPath: string);
var
SharePathAddHandle : TCloudPathAddHandle;
begin
SharePathAddHandle := TCloudPathAddHandle.Create( FullPath );
SharePathAddHandle.Update;
SharePathAddHandle.Free;
end;
procedure TMyCloudFileControl.RemoveSharePath(FullPath: string);
var
SharePathRemoveHandle : TCloudPathRemoveHandle;
begin
SharePathRemoveHandle := TCloudPathRemoveHandle.Create( FullPath );
SharePathRemoveHandle.Update;
SharePathRemoveHandle.Free;
end;
{ TSharePathAddHandle }
procedure TCloudPathAddHandle.AddToXml;
var
CloudPathAddXml : TCloudPathAddXml;
begin
// 写 Xml
CloudPathAddXml := TCloudPathAddXml.Create( CloudPath );
MyCloudPathXmlWrite.AddChange( CloudPathAddXml );
end;
procedure TCloudPathAddHandle.Update;
begin
inherited;
AddToXml;
end;
{ TSharePathRemoveHandle }
procedure TCloudPathRemoveHandle.RemoveFromInfo;
var
CloudPathRemoveInfo : TCloudPathRemoveInfo;
begin
// 写 内存
CloudPathRemoveInfo := TCloudPathRemoveInfo.Create( CloudPath );
MyCloudFileInfo.AddChange( CloudPathRemoveInfo );
end;
procedure TCloudPathRemoveHandle.RemoveFromXml;
var
CloudPathRemoveXml : TCloudPathRemoveXml;
begin
// 写 Xml
CloudPathRemoveXml := TCloudPathRemoveXml.Create( CloudPath );
MyCloudPathXmlWrite.AddChange( CloudPathRemoveXml );
end;
procedure TCloudPathRemoveHandle.Update;
begin
// 删除信息
RemoveFromInfo;
RemoveFromXml;
end;
{ TCloudPathChangeHandle }
constructor TCloudPathChangeHandle.Create(_CloudlPath: string);
begin
CloudPath := _CloudlPath;
end;
{ TCloudPathReadHandle }
procedure TCloudPathReadHandle.AddToInfo;
var
CloudPathAddInfo : TCloudPathAddInfo;
begin
// 写 内存
CloudPathAddInfo := TCloudPathAddInfo.Create( CloudPath );
MyCloudFileInfo.AddChange( CloudPathAddInfo );
end;
procedure TCloudPathReadHandle.Update;
begin
AddToInfo;
end;
{ TCloudPathPcFolderChangeHandle }
procedure TCloudPathOwnerChangeHandle.SetOwnerPcID(_OwnerPcID: string);
begin
OwnerPcID := _OwnerPcID;
end;
{ TCloudPathPcFolderChangeSpaceHandle }
procedure TCloudPathOwnerChangeSpaceHandle.SetSpaceInfo(_FileSize: Int64;
_FileCount: Integer);
begin
FileSize := _FileSize;
FileCount := _FileCount;
end;
{ TCloudPathPcFolderRemoveHandle }
procedure TCloudPathOwnerRemoveHandle.RemoveFromInfo;
var
CloudPathOwnerRemoveInfo : TCloudPathOwnerRemoveInfo;
begin
CloudPathOwnerRemoveInfo := TCloudPathOwnerRemoveInfo.Create( CloudPath );
CloudPathOwnerRemoveInfo.SetOwnerPcID( OwnerPcID );
MyCloudFileInfo.AddChange( CloudPathOwnerRemoveInfo );
end;
procedure TCloudPathOwnerRemoveHandle.RemoveFromXml;
var
CloudPathOwnerRemoveXml : TCloudPathOwnerRemoveXml;
begin
CloudPathOwnerRemoveXml := TCloudPathOwnerRemoveXml.Create( CloudPath );
CloudPathOwnerRemoveXml.SetOwnerPcID( OwnerPcID );
MyCloudPathXmlWrite.AddChange( CloudPathOwnerRemoveXml );
end;
procedure TCloudPathOwnerRemoveHandle.Update;
begin
RemoveFromInfo;
RemoveFromXml;
end;
{ TCloudPathPcFolderSpaceAddHandle }
procedure TCloudPathOwnerSpaceAddHandle.AddToInfo;
var
CloudPathPcFolderAddSpaceInfo : TCloudPathOwnerAddSpaceInfo;
begin
CloudPathPcFolderAddSpaceInfo := TCloudPathOwnerAddSpaceInfo.Create( CloudPath );
CloudPathPcFolderAddSpaceInfo.SetOwnerPcID( OwnerPcID );
CloudPathPcFolderAddSpaceInfo.SetSpaceInfo( FileSize, FileCount );
MyCloudFileInfo.AddChange( CloudPathPcFolderAddSpaceInfo );
end;
procedure TCloudPathOwnerSpaceAddHandle.AddToXml;
var
CloudPathPcFolderAddSpaceXml : TCloudPathOwnerAddSpaceXml;
begin
CloudPathPcFolderAddSpaceXml := TCloudPathOwnerAddSpaceXml.Create( CloudPath );
CloudPathPcFolderAddSpaceXml.SetOwnerPcID( OwnerPcID );
CloudPathPcFolderAddSpaceXml.SetSpaceInfo( FileSize, FileCount );
MyCloudPathXmlWrite.AddChange( CloudPathPcFolderAddSpaceXml );
end;
procedure TCloudPathOwnerSpaceAddHandle.Update;
begin
AddToInfo;
AddToXml;
end;
{ TCloudPathPcFolderSpaceRemoveHandle }
procedure TCloudPathOwnerSpaceRemoveHandle.RemoveFromInfo;
var
CloudPathPcFolderRemoveSpaceInfo : TCloudPathOwnerRemoveSpaceInfo;
begin
CloudPathPcFolderRemoveSpaceInfo := TCloudPathOwnerRemoveSpaceInfo.Create( CloudPath );
CloudPathPcFolderRemoveSpaceInfo.SetOwnerPcID( OwnerPcID );
CloudPathPcFolderRemoveSpaceInfo.SetSpaceInfo( FileSize, FileCount );
MyCloudFileInfo.AddChange( CloudPathPcFolderRemoveSpaceInfo );
end;
procedure TCloudPathOwnerSpaceRemoveHandle.RemoveFromXml;
var
CloudPathPcFolderRemoveSpaceXml : TCloudPathOwnerRemoveSpaceXml;
begin
CloudPathPcFolderRemoveSpaceXml := TCloudPathOwnerRemoveSpaceXml.Create( CloudPath );
CloudPathPcFolderRemoveSpaceXml.SetOwnerPcID( OwnerPcID );
CloudPathPcFolderRemoveSpaceXml.SetSpaceInfo( FileSize, FileCount );
MyCloudPathXmlWrite.AddChange( CloudPathPcFolderRemoveSpaceXml );
end;
procedure TCloudPathOwnerSpaceRemoveHandle.Update;
begin
RemoveFromInfo;
RemoveFromXml;
end;
{ TCloudPathPcFolderSpaceSetHandle }
procedure TCloudPathOwnerSpaceSetHandle.SetLastFileSize(_LastFileSize: Int64);
begin
LastFileSize := _LastFileSize;
end;
procedure TCloudPathOwnerSpaceSetHandle.SetToInfo;
var
CloudPathPcFolderSetSpaceInfo : TCloudPathOwnerSetSpaceInfo;
begin
CloudPathPcFolderSetSpaceInfo := TCloudPathOwnerSetSpaceInfo.Create( CloudPath );
CloudPathPcFolderSetSpaceInfo.SetOwnerPcID( OwnerPcID );
CloudPathPcFolderSetSpaceInfo.SetSpaceInfo( FileSize, FileCount );
CloudPathPcFolderSetSpaceInfo.SetLastFileSize( LastFileSize );
MyCloudFileInfo.AddChange( CloudPathPcFolderSetSpaceInfo );
end;
procedure TCloudPathOwnerSpaceSetHandle.SetToXml;
var
CloudPathPcFolderSetSpaceXml : TCloudPathOwnerSetSpaceXml;
begin
CloudPathPcFolderSetSpaceXml := TCloudPathOwnerSetSpaceXml.Create( CloudPath );
CloudPathPcFolderSetSpaceXml.SetOwnerPcID( OwnerPcID );
CloudPathPcFolderSetSpaceXml.SetSpaceInfo( FileSize, FileCount );
CloudPathPcFolderSetSpaceXml.SetLastFileSize( LastFileSize );
MyCloudPathXmlWrite.AddChange( CloudPathPcFolderSetSpaceXml );
end;
procedure TCloudPathOwnerSpaceSetHandle.Update;
begin
SetToInfo;
SetToXml;
end;
{ TCloudPathOwnerReadHandle }
procedure TCloudPathOwnerReadHandle.AddToInfo;
var
CloudPathOwnerAddInfo : TCloudPathOwnerAddInfo;
begin
CloudPathOwnerAddInfo := TCloudPathOwnerAddInfo.Create( CloudPath );
CloudPathOwnerAddInfo.SetOwnerPcID( OwnerPcID );
CloudPathOwnerAddInfo.SetSpaceInfo( FileSize, FileCount );
CloudPathOwnerAddInfo.SetLastScanTime( LastScanTime );
MyCloudFileInfo.AddChange( CloudPathOwnerAddInfo );
end;
procedure TCloudPathOwnerReadHandle.SetLastScanTime(_LastScanTime: TDateTime);
begin
LastScanTime := _LastScanTime;
end;
procedure TCloudPathOwnerReadHandle.SetSpaceInfo(_FileSize: Int64;
_FileCount: Integer);
begin
FileSize := _FileSize;
FileCount := _FileCount;
end;
procedure TCloudPathOwnerReadHandle.Update;
begin
AddToInfo;
end;
{ TCloudPathOwnerSetLastScanTime }
procedure TCloudPathOwnerSetLastScanTimeHandle.SetLastScanTime(
_LastScanTime: TDateTime);
begin
LastScanTime := _LastScanTime;
end;
procedure TCloudPathOwnerSetLastScanTimeHandle.SetToInfo;
var
CloudPathOwnerSetLastScanTimeInfo : TCloudPathOwnerSetLastScanTimeInfo;
begin
CloudPathOwnerSetLastScanTimeInfo := TCloudPathOwnerSetLastScanTimeInfo.Create( CloudPath );
CloudPathOwnerSetLastScanTimeInfo.SetOwnerPcID( OwnerPcID );
CloudPathOwnerSetLastScanTimeInfo.SetLastScanTime( LastScanTime );
MyCloudFileInfo.AddChange( CloudPathOwnerSetLastScanTimeInfo );
end;
procedure TCloudPathOwnerSetLastScanTimeHandle.SetToXml;
var
CloudPathOwnerSetLastScanTimeXml : TCloudPathOwnerSetLastScanTimeXml;
begin
CloudPathOwnerSetLastScanTimeXml := TCloudPathOwnerSetLastScanTimeXml.Create( CloudPath );
CloudPathOwnerSetLastScanTimeXml.SetOwnerPcID( OwnerPcID );
CloudPathOwnerSetLastScanTimeXml.SetLastScanTime( LastScanTime );
MyCloudPathXmlWrite.AddChange( CloudPathOwnerSetLastScanTimeXml );
end;
procedure TCloudPathOwnerSetLastScanTimeHandle.Update;
begin
SetToInfo;
SetToXml;
end;
{ TCloudPathOnlineScanHandle }
procedure TCloudPathOnlineScanHandle.AddToInfo;
var
CloudPathOnlineScanInfo : TCloudPathOnlineScanInfo;
begin
CloudPathOnlineScanInfo := TCloudPathOnlineScanInfo.Create;
CloudPathOnlineScanInfo.SetPcID( OnlinePcID );
MyCloudFileInfo.AddChange( CloudPathOnlineScanInfo );
end;
procedure TCloudPathOnlineScanHandle.SetOnlinePcID(_OnlinePcID: string);
begin
OnlinePcID := _OnlinePcID;
end;
procedure TCloudPathOnlineScanHandle.Update;
begin
AddToInfo;
end;
end.
|
unit UxlWinClasses;
interface
uses Windows, Messages, ShellAPI, UxlClasses, UxlWindow, UxlWinControl, UxlMenu, UxlStrUtils, UxlMath, UxlFunctions, UxlList;
type
TxlTrayIcon = class
private
FWndParent: TxlWindow;
FPopMenu: TxlMenu;
FIcon: cardinal;
FTip: widestring;
FOnClick: TNotifyEvent;
public
constructor Create (WndParent: TxlWindow; i_icon: cardinal; const s_tip: widestring);
procedure ProcessCommand (dwEvent: DWORD);
procedure DrawIcon (b_draw: boolean);
property Menu: TxlMenu read FPopMenu write FPopMenu;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
end;
type
TxlTimer = class
private
FInterval: cardinal;
FHParent: HWND;
FOnTimer: TNotifyEvent;
FStarted: boolean;
FID: cardinal;
procedure f_SetEnable (value: boolean);
constructor Create (HParent: HWND; id: integer);
procedure SetInterval (i_interval: cardinal);
public
destructor Destroy (); override;
procedure Start ();
procedure Stop ();
procedure Reset ();
procedure TimerEvent ();
property Interval: cardinal read FInterval write SetInterval;
property Enabled: boolean read FStarted write f_SetEnable;
property OnTimer: TNotifyEvent read FOnTimer write FOnTimer;
end;
TxlTimerCenter = class
private
FTimers: TxlObjList;
FHParent: HWND;
constructor Create (HParent: HWND);
public
destructor Destroy (); override;
function NewTimer (): TxlTimer;
procedure ReleaseTimer (value: TxlTimer);
procedure OnTimer (id: integer);
end;
type
IHotkeyOwner = interface
procedure OnHotkey (id: integer; hk: THotkey);
end;
THotkeyRecord = record
Id: integer;
Owner: IHotkeyOwner;
Hotkey: THotkey;
end;
TxlHotKeyCenter = class
private
FHotkeys: array of THotkeyRecord;
FHParent: HWND;
constructor Create (HParent: HWND);
public
procedure AddHotkey (owner: IHotkeyOwner; id: integer; hk: THotKey);
procedure RemoveHotkey (owner: IHotkeyOwner; id: integer);
procedure RemoveOwner (value: IHotkeyOwner);
procedure OnHotkey (hkid: integer);
end;
type
TxlClipboard = class
private
FHOwner: HWND;
function f_gettext (): widestring;
procedure f_settext (const value: widestring);
public
constructor Create (HOwner: HWND);
function GetTextSize (): integer;
property Text: widestring read f_gettext write f_settext;
end;
function Clipboard(): TxlClipboard;
function HotkeyCenter (): TxlHotkeyCenter;
function TimerCenter (): TxlTimerCenter;
implementation
uses UxlCommDlgs, UxlWinDef, commctrl;
var
FClipbrd: TxlClipboard;
FHotkeyCenter: TxlHotkeyCenter;
FTimerCenter: TxlTimerCenter;
function Clipboard(): TxlClipboard;
begin
if FClipbrd = nil then
FClipbrd := TxlClipboard.Create (MainWinHandle);
result := FClipbrd;
end;
function HotkeyCenter(): TxlHotkeyCenter;
begin
if FHotkeyCenter = nil then
FHotkeyCenter := TxlHotkeyCenter.Create (MainWinHandle);
result := FHotkeyCenter;
end;
function TimerCenter(): TxlTimerCenter;
begin
if FTimerCenter = nil then
FTimerCenter := TxlTimerCenter.Create (MainWinHandle);
result := FTimerCenter;
end;
//------------------
constructor TxlTrayIcon.Create (WndParent: TxlWindow; i_icon: cardinal; const s_tip: widestring);
begin
FWndParent := WndParent;
FIcon := i_icon;
FTip := s_tip;
end;
procedure TxlTrayIcon.DrawIcon(b_draw: boolean);
var o_nid: TNotifyIconDataW;
begin
o_nid.cbSize := sizeof (o_nid);
with o_nid do
begin
// cbSize := sizeof (o_nid);
Wnd := FWndParent.handle;
uID := cardinal(self);
end;
if b_draw then
begin
with o_nid do
begin
uFlags := NIF_ICON or NIF_MESSAGE or NIF_TIP;
hIcon := LoadIconFromResource (Ficon);
uCallBackMessage := WM_TRAYICONMESSAGE;
StrLCopy (szTip, pwidechar(Ftip), Min (length(Ftip), length(szTip)));
end;
Shell_NotifyIconW (NIM_ADD, @o_nid);
end
else
Shell_NotifyIcon (NIM_DELETE, @o_nid);
end;
procedure TxlTrayIcon.ProcessCommand (dwEvent: DWORD);
var h: HWND;
begin
case dwEvent of
WM_LBUTTONDOWN:
if assigned (FOnClick) then FOnClick (self);
WM_RBUTTONDOWN:
begin
if Assigned(FPopMenu) then
begin
h := FWndParent.handle;
SetForegroundWindow(h);
FPopMenu.Popup(0, -1, -1, pdRightBottom, true);
SendMessageW(h, WM_TRAYICONAFTERPOPUPMENU, 0, 0);
PostMessageW(h, WM_NULL, 0, 0);
end;
end;
WM_MOUSEMOVE:
SendMessageW (FWndParent.Handle, WM_TRAYICONMOUSEMOVE, 0, 0);
end;
end;
//----------------------
constructor TxlClipboard.Create (HOwner: HWND);
begin
FHOwner := HOwner;
end;
function TxlClipboard.f_gettext (): widestring;
var hg: HGLOBAL;
p: pointer;
pt: pwidechar;
n: integer;
begin
result := '';
if IsClipboardFormatAvailable (CF_UNICODETEXT) then
begin
OpenClipboard (FHOwner);
hg := GetClipboardData (CF_UNICODETEXT);
n := globalsize (hg);
p := GlobalLock (hg);
getmem (pt, n);
copymemory (pt, p, n);
GlobalUnlock (hg);
closeclipboard ();
result := pt;
freemem (pt);
end;
end;
procedure TxlClipboard.f_settext (const value: widestring);
var hg: HGLOBAL;
p: pointer;
n: integer;
begin
n := length(value);
OpenClipboard (FHOwner);
EmptyClipboard ();
hg := GlobalAlloc (GHND or GMEM_SHARE, (n + 1)*2);
p := GlobalLock (hg);
copymemory (p, pwidechar(value), n * 2);
GlobalUnlock (hg);
SetClipboardData (CF_UNICODETEXT, hg);
CloseClipboard ();
end;
function TxlClipboard.GetTextSize (): integer;
var hg: HGlobal;
begin
result := 0;
if IsClipboardFormatAvailable (CF_UNICODETEXT) then
begin
OpenClipboard (FHOwner);
hg := GetClipboardData (CF_UNICODETEXT);
result := globalsize (hg) div 2;
CloseClipboard ();
end;
end;
//------------------------
constructor TxlTimer.Create (HParent: HWND; id: integer);
begin
FHParent := HParent;
FID := id;
FStarted := false;
end;
destructor TxlTimer.Destroy ();
begin
Stop;
inherited;
end;
procedure TxlTimer.Start ();
begin
Stop;
if FInterval > 0 then
begin
SetTimer (FHParent, FID, FInterval, nil);
FStarted := true;
end;
end;
procedure TxlTimer.Stop ();
begin
if FStarted then
KillTimer (FHparent, FID);
FStarted := false;
end;
procedure TxlTimer.Reset ();
begin
Stop;
Start;
end;
procedure TxlTimer.f_SetEnable (value: boolean);
begin
if value then
Start
else
Stop;
end;
procedure TxlTimer.SetInterval(i_interval: cardinal);
begin
if i_interval <> FInterval then
begin
FInterval := i_interval;
if FStarted then
Start;
end;
end;
procedure TxlTimer.TimerEvent ();
begin
if assigned (FOnTimer) then
FOnTimer (self);
end;
//-------------------------
constructor TxlTimerCenter.Create (HParent: HWND);
begin
FHParent := HParent;
FTimers := TxlObjList.Create;
end;
destructor TxlTimerCenter.Destroy ();
begin
FTimers.Free;
inherited;
end;
function TxlTimerCenter.NewTimer (): TxlTimer;
var id: integer;
begin
id := FTimers.GetNewIndex;
result := TxlTimer.Create (FHParent, id);
FTimers.AddByIndex (id, result);
end;
procedure TxlTimerCenter.ReleaseTimer (value: TxlTimer);
begin
FTimers.Remove (value);
value.free;
end;
procedure TxlTimerCenter.OnTimer (id: integer);
var o_timer: TxlTimer;
begin
o_timer := FTimers.ItemsByINdex [id];
if o_timer <> nil then
o_timer.TimerEvent ();
end;
//-------------------------
const cHotkeyOffset = 1000;
constructor TxlHotkeyCenter.Create (HParent: HWND);
begin
FHParent := HParent;
end;
procedure TxlHotkeyCenter.AddHotkey (owner: IHotkeyOwner; id: integer; hk: THotKey);
var i, n: integer;
modifier, vk: cardinal;
begin
RemoveHotkey (owner, id);
if hk <> 0 then
begin
n := -1;
for i := Low(FHotkeys) to High(FHotkeys) do
if FHotkeys[i].Owner = nil then
begin
n := i;
break;
end;
if n < 0 then
begin
n := Length (FHotkeys);
SetLength (FHotkeys, n + 1);
end;
SplitHotkey (hk, modifier, vk);
RegisterHotkey (FHParent, n + cHotkeyOffset, modifier, vk);
FHotkeys[n].Owner := owner;
FHotkeys[n].Id := id;
FHotkeys[n].Hotkey := hk;
end;
end;
procedure TxlHotkeyCenter.RemoveHotkey (owner: IHotkeyOwner; id: integer);
var i: integer;
begin
for i := Low(FHotkeys) to High(FHotkeys) do
if (FHotkeys[i].id = id) and (FHotkeys[i].Owner = owner) then
begin
UnRegisterHotkey (FHParent, i + cHotkeyOffset);
FHotkeys[i].Owner := nil;
exit;
end;
end;
procedure TxlHotkeyCenter.RemoveOwner (value: IHotkeyOwner);
var i: integer;
begin
for i := Low(FHotkeys) to High(FHotkeys) do
if (FHotkeys[i].Owner = value) then
begin
UnRegisterHotkey (FHParent, i + cHotkeyOffset);
FHotkeys[i].Owner := nil;
end;
end;
procedure TxlHotkeyCenter.OnHotkey (hkid: integer);
var n: integer;
begin
n := hkid - cHotkeyOffset;
if InRange (n, 0, Length(FHotkeys) - 1) and (FHotkeys[n].Owner <> nil) then
FHotkeys[n].Owner.OnHotKey (FHotkeys[n].Id, FHotkeys[n].hotkey);
end;
//------------------------
initialization
finalization
FreeAndNil (FClipbrd);
FreeAndNil (FHotkeyCenter);
FreeAndNil (FTimerCenter);
end.
|
// gets price value of item
function getPrice(item: IInterface): integer;
var
tmp: integer;
begin
Result := 0;
tmp := GetElementEditValues(item, 'DATA\Value');
if Assigned(tmp) then
Result := tmp;
end;
|
unit PokebonCSV;
interface
Uses sysutils;
type pokemon = record
ID_Pokebon : string;
Nama : string;
Tipe : string;
Evolusi_Selanjutnya : string;
end;
type inventori = record
Nomor_Inventori : string;
Nama_Pokebon : string;
Level : string;
Kondisi : string;
end;
type evolution = record
ID_Evolusi : string;
Alur_Evolusi : array [1..1000] of string;
end;
type train = record
Nama : string;
Day_Passed : string;
File_Inventori : string;
File_Stats : string;
end;
type status = record
Nama_Pokebon : string;
Max_Level : string;
end;
type EncounterChance=record
ArrNamaPokebon : array [1..1000] of string;
Neff : integer;
end;
const
mark =',';
var
File_Pokebon : TextFile;
Pokebon:pokemon;
TPok:array [0..1000] of pokemon;
jmlPokebon : integer;
File_Inven : TextFile;
Inven : inventori;
TInv : array [0..1000] of inventori;
jmlInv : integer;
File_Evolusi : TextFile;
Evo : evolution;
TEvo : array [0..1000] of evolution;
jmlEvo:integer;
last_Ev : array [0..1000] of integer;
File_Trainer : TextFile;
Trainer : train;
TTrain : array [0..1000] of train;
jmlTrain : integer;
File_Stats : TextFile;
stats : status;
TStats : array [0..1000] of status;
jmlStats : integer;
Tencounter : EncounterChance;
nama : string;
procedure PokebonCSVtoArray(CSV : string);
procedure InvenCSVtoArray(CSV : string);
procedure EvolutionCSVtoArray(CSV : string);
procedure TrainerCSVtoArray(CSV : string);
procedure StatsCSVtoArray(CSV : string);
implementation
procedure PokebonCSVtoArray(CSV : string);
var
baris:integer;
CC :String;
kolom : integer;
i: integer;
tempText : string;
begin
assign (File_Pokebon,CSV);
reset(File_Pokebon);
jmlPokebon := 0;
baris := 0;//baris 0 untuk header
while (not(eof(File_Pokebon)))do
begin
readln(File_Pokebon,CC);
kolom := 0;
i:=1;
tempText := '';
while(i<=length(CC)+1 )do //masukin pokebon sesuai kolom
begin
if((CC[i] = ',') or (i=length(CC)+1))then
begin
if(kolom=0) then
begin
TPok[baris].ID_Pokebon := tempText;
end else if (kolom =1)then
begin
TPok[baris].Nama := tempText;
end else if (kolom =2)then
begin
Tpok[baris].Tipe := tempText;
end else
begin
TPok[baris].Evolusi_Selanjutnya := tempText;
end;
tempText := '';
kolom := kolom+1;
end else if (CC[i]=' ') then
begin
end else
begin
tempText := tempText + CC[i];
end;
i := i+1;
//end
end;
baris := baris+1; //baris ditambah 1
if(baris>=1)then
begin
jmlPokebon := jmlPokebon+1;
end;
end;
close(File_Pokebon);
end;
procedure InvenCSVtoArray(CSV : string);
var
baris : integer;
CC : string;
kolom : integer;
i:integer;
tempText : string;
begin
assign(File_Inven,CSV);
reset(File_Inven);
jmlInv := 0;
baris := 0;
while (not(eof(File_Inven)))do
begin
tempText:='';
readln(File_Inven,CC);
kolom := 0;
i:=1;
{while (kolom<4) do
begin}
while(i<=length(CC)+1)do //masukin pokebon sesuai kolom
begin
if((CC[i] = ',') or (i=length(CC)+1))then
begin
if(kolom=0) then
begin
TInv[baris].Nomor_Inventori := tempText;
end else if (kolom =1)then
begin
TInv[baris].Nama_Pokebon := tempText;
end else if (kolom =2)then
begin
TInv[baris].Level := tempText;
end else
begin
TInv[baris].kondisi := tempText;
end;
kolom := kolom+1;
tempText := '';
end else if (CC[i]=' ') then
begin
end else
begin
tempText := tempText + CC[i];
end;
i := i+1;
end;
baris := baris+1; //baris ditambah 1
if(baris>=1)then
begin
jmlInv := jmlInv+1;
end;
end;
close(File_Inven);
end;
procedure EvolutionCSVtoArray(CSV:string);
var
baris : integer;
CC,tempText : string;
kolom : integer;
i:integer;
begin
assign(File_Evolusi,CSV);
reset(File_Evolusi);
jmlEvo:=0;
baris:=0;
while(not(eof(File_Evolusi)))do
begin
readln(File_Evolusi,CC);
kolom:=0;
i:=1;
tempText:='';
while(i<=length(CC)+1)do
begin
if ( (CC[i] = ',') or (i=length(CC)+1) or (CC[i]='-') )then
begin
if(kolom=0)then
begin
TEvo[baris].ID_Evolusi := tempText;
end else
begin
TEvo[baris].Alur_Evolusi[kolom]:=tempText;
end;
tempText:='';
kolom:=kolom+1;
end else if (CC[i]=' ') then
begin
end else
begin
tempText := tempText+CC[i];
end;
i:=i+1;
end;
last_Ev[baris]:=kolom-1;//buat liat evolusi terakhir baris ke-n
baris:=baris+1;
if(baris>=1)then
begin
jmlEvo:=jmlEvo+1;
end;
end;
close(File_Evolusi);
end;
procedure TrainerCSVtoArray(CSV : string);
var
baris : integer;
CC : string;
kolom : integer;
i:integer;
tempText : string;
tempday : integer;
begin
assign(File_Trainer,CSV);
reset(File_Trainer);
jmlTrain := 0;
baris := 0;
while (not(eof(File_Trainer)))do
begin
tempText:='';
readln(File_Trainer,CC);
kolom := 0;
i:=1;
{while (kolom<4) do
begin}
while(i<=length(CC)+1)do //masukin pokebon sesuai kolom
begin
if((CC[i] = ',') or (i=length(CC)+1))then
begin
if(kolom=0) then
begin
TTrain[baris].Nama := tempText;
end else if (kolom =1)then
begin
TTrain[baris].Day_Passed := tempText;
end else if (kolom =2)then
begin
TTrain[baris].File_Inventori := tempText;
end else
begin
TTrain[baris].File_Stats := tempText;
end;
kolom := kolom+1;
tempText := '';
end else if (CC[i]=' ') then
begin
end else
begin
tempText := tempText + CC[i];
end;
i := i+1;
end;
baris := baris+1; //baris ditambah 1
if(baris>=1)then
begin
jmlTrain := jmlTrain+1;
end;
end;
close(File_Trainer);
end;
procedure StatsCSVtoArray(CSV : string);
var
baris : integer;
CC : string;
kolom : integer;
i:integer;
tempText : string;
begin
assign(File_Stats,CSV);
reset(File_Stats);
jmlStats := 0;
baris := 0;
while (not(eof(File_Stats)))do
begin
tempText:='';
readln(File_Stats,CC);
kolom := 0;
i:=1;
{while (kolom<4) do
begin}
while(i<=length(CC)+1)do //masukin pokebon sesuai kolom
begin
if((CC[i] = ',') or (i=length(CC)+1))then
begin
if(kolom=0) then
begin
TStats[baris].Nama_Pokebon := tempText;
end else
begin
TStats[baris].Max_Level := tempText;
end;
kolom := kolom+1;
tempText := '';
end else if (CC[i]=' ') then
begin
end else
begin
tempText := tempText + CC[i];
end;
i := i+1;
end;
baris := baris+1; //baris ditambah 1
if(baris>=1)then
begin
jmlStats := jmlStats+1;
end;
end;
close(File_Stats);
end;
end. |
unit UTS1000;
interface
uses
Contnrs, System.Classes;
type
TS1000 = class(TObjectList)
private
function GetItem(Index: Integer): TS1000;
function Add: TS1000;
public
tpAmb_4: String;
procEmi_5: String;
verProc_6: String;
tpInsc_8: String;
nrInsc_9: String;
iniValid_13: String;
fimValid_14: String;
nmRazao_15: String;
classTrib_16: String;
natJurid_17: String;
indCoop_18: String;
indConstr_19: String;
indDesFolha_20: String;
indOptRegEletron_21: String;
indEntEd_23: String;
indEtt_24: String;
nmCtt_36: String;
cpfCtt_37: String;
foneFixo_38: String;
email_40: String;
cnpjSoftHouse_56: String;
nmRazao_57: String;
nmCont_58: String;
telefone_59: String;
email_60: String;
indSitPJ_63: String;
property Items[Index: Integer]: TS1000 read GetItem; default;
procedure GetS1000(const Arq: TStringList);
end;
implementation
{ TS1000 }
function TS1000.Add: TS1000;
begin
Result := TS1000.Create;
inherited Add(Result);
end;
function TS1000.GetItem(Index: Integer): TS1000;
begin
Result := TS1000(inherited Items[Index]);
end;
procedure TS1000.GetS1000(const Arq: TStringList);
var
I: Integer;
Lista: TStringList;
begin
inherited Clear;
for I := 0 to Pred(Arq.Count) do
if Copy(Arq[I],0,Pred(Pos('|',Arq[I]))) = 'S1000'then
begin
Lista := TStringList.Create;
ExtractStrings(['|'],[],PChar(Arq[I]),Lista);
with Add do
begin
tpAmb_4 := Lista[1];
procEmi_5 := Lista[2];
verProc_6 := Lista[3];
tpInsc_8 := Lista[4];
nrInsc_9 := Lista[5];
iniValid_13 := Lista[6];
fimValid_14 := Lista[7];
nmRazao_15 := Lista[8];
classTrib_16 := Lista[9];
natJurid_17 := Lista[10];
indCoop_18 := Lista[11];
indConstr_19 := Lista[12];
indDesFolha_20 := Lista[13];
indOptRegEletron_21 := Lista[14];
indEntEd_23 := Lista[15];
indEtt_24 := Lista[16];
nmCtt_36 := Lista[26];
cpfCtt_37 := Lista[27];
foneFixo_38 := Lista[28];
email_40 := Lista[30];
cnpjSoftHouse_56 := Lista[41];
nmRazao_57 := Lista[42];
nmCont_58 := Lista[43];
telefone_59 := Lista[44];
email_60 := Lista[45];
indSitPJ_63 := Lista[46];
end;
Lista.Free;
end;
end;
end.
|
(*-------------------------------------------------- *)
(* ARITHMOS.PAS *)
(* Arithmetik-Unit fĀr Turbo Pascal ab 5.5 *)
(* (c) 1990, 1992 Dirk Hillbrecht & DMV-Verlag *)
(* ------------------------------------------------- *)
{$A+,B-,D-,E-,F-,I-,N-,O-,R-,V-}
UNIT Arithmos;
INTERFACE
CONST
Ln10 = 2.3025850930; { Ln 10 }
Ln2 = 0.6931471856; { Ln 2 }
e = 2.718281829; { Eulersche Zahl }
pi = 3.141592654; { die KreiskonsTante }
{ wichtige physikalische Konstanten,
jeweils in normierten Einheiten }
phy_epsilon0 = 8.854219e-12;
{ elektrische Feldkonstante}
phy_my0 = 12.56637061e-7;
{ magnetische Feldkonstante}
phy_na = 6.023e23; { Avogadro-Konstante }
phy_c = 2.997935e8; { Lichtgeschwindigkeit }
phy_g = 9.80665; { Fallbeschleunigung }
phy_k = 1.3804e-23; { Boltzmann-Konstante }
{ alLgemeines Funktionsergebnis im Fehlerfall }
MaxReal = 1e+38;
{ Schalter fĀr die Winkelfunktionsdarstellung }
rad = 0;
deg = 1;
gra = 2;
FUNCTION ArithResult(x : REAL) : SHORTINT;
{ wenn |x| Ú MaxReal,
dann Fehlermeldung zurĀckgeben }
FUNCTION ArithErrMsg(ErrNummer : SHORTINT) : STRING;
{ Klartextfehlermeldung aus <ArithResult> erzeugen}
PROCEDURE Trigonomodus(modus : WORD);
{ einstellen der Einheit des WinkelmaŠes }
FUNCTION Sqr(x : REAL) : REAL;
{ berechnet xż mit Test auf BereichsĀberschreitung}
FUNCTION Sqrt(x : REAL) : REAL;
{ berechnet Żx mit PlausibilitĄtstest }
FUNCTION Faku(x : REAL) : REAL;
{ berechnet x!, wenn x Ó N und 0 ů x ů 36 gilt }
FUNCTION Power(x, y : REAL) : REAL;
{ x^y, auch gebrochene und negative Zahlen erlaubt}
FUNCTION PwrOfTen(epn : REAL) : REAL;
{ 10^epn }
FUNCTION Exp(x : REAL) : REAL;
{ berechnet e^x mit PlausibilitĄtsprĀfung }
FUNCTION Log(b, z : REAL) : REAL;
{ berechnet den Logarithmus von z zur Basis b }
FUNCTION Lg(x : REAL) : REAL;
{ Logarithmus zur Basis 10 }
FUNCTION Lb(x : REAL) : REAL;
{ Logarithmus zur Basis 2 }
FUNCTION Ln(x : REAL) : REAL;
{ berechnet den Logarithmus zur Basis e mit Test }
{ auf GĀltigkeit }
{ --- Trigonometrie ----------------------------- }
{ alle trigonometrischen Funktionen, die einen }
{ Winkel erwarten, interpretieren diesen Winkel in }
{ der eingestellten Einheit (rad/deg/gra); umgekehrt}
{ geben die Umkehrfunktionen ihren Winkel in dieser }
{ Einheit zurĀck }
FUNCTION Sin2(x : REAL) : REAL;
FUNCTION Cos2(x : REAL) : REAL;
FUNCTION Tan2(x : REAL) : REAL;
FUNCTION Cot2(x : REAL) : REAL;
FUNCTION ArcSin(x : REAL) : REAL;
FUNCTION ArcCos(x : REAL) : REAL;
FUNCTION ArcTan2(x : REAL) : REAL;
FUNCTION ArcCot(x : REAL) : REAL;
FUNCTION Sinh(x : REAL) : REAL;
FUNCTION Cosh(x : REAL) : REAL;
FUNCTION Tanh(x : REAL) : REAL;
FUNCTION Coth(x : REAL) : REAL;
FUNCTION ArSinh(x : REAL) : REAL;
FUNCTION ArCosh(x : REAL) : REAL;
FUNCTION ArTanh(x : REAL) : REAL;
FUNCTION ArCoth(x : REAL) : REAL;
(* --- Zusatzroutinen --------------------------- *)
FUNCTION RtoStr(zahl : REAL) : STRING;
{ formt eine REAL-Zahl in einen STRING um, kleine }
{ Zahlen werden normal, groŠe in wissen- }
{ schaftlicher Exponentialschreibweise darge- }
{ stellt, Rechenfehler werden in gewissen Grenzen }
{ gerundet. }
IMPLEMENTATION
CONST
durchpi180 = 1.745329252e-2; { „ / 180 }
durch180pi = 5.729577951e1; { 180 / „ }
durchpi200 = 1.570796327e-2; { „ / 200 }
durch200pi = 6.366197724e1; { 200 / „ }
pi_haLbe = 1.570796327; { „ / 2 }
minExp = -88;
maxExp = 88;
isNotRad : BOOLEAN = TRUE;
{ TRUE : RAD / FALSE : umzurechnen }
VAR
toRad, fromRad, hilf : REAL;
InternError : SHORTINT;
PROCEDURE RadWinkel(VAR Argument : REAL);
{ Winkel in beliebiger Einheit nach RAD konvertieren}
BEGIN
IF isNotRad THEN Argument := Argument * toRad;
END;
FUNCTION NormWinkel(a : REAL) : REAL;
{ RAD-Winkel in offizielle Einheit
zurĀckkonvertieren }
BEGIN
IF isNotRad THEN NormWinkel := a * fromRad
ELSE NormWinkel := a;
END;
FUNCTION ArithResult(x : REAL) : SHORTINT;
BEGIN
IF (Abs(x) >= MaxReal) THEN
ArithResult := InternError
ELSE
ArithResult := 0;
InternError := -127;
END;
PROCEDURE Trigonomodus(modus : WORD);
BEGIN
CASE modus OF
rad : isNotRad := FALSE;
deg : BEGIN
toRad := durchpi180;
fromRad := durch180pi;
isNotRad := TRUE;
END;
gra : BEGIN
toRad := durchpi200;
fromRad := durch200pi;
isNotRad := TRUE;
END;
END;
END;
FUNCTION Faku(x : REAL) : REAL;
VAR
i : WORD;
Zaehler : REAL;
BEGIN
InternError := -1;
IF (Abs(x-Round(x)) > 1e-6) OR (x < 0) OR
(x > 36) THEN
Zaehler := MaxReal
ELSE BEGIN
Zaehler := 1;
i := Round(x);
WHILE i > 1 DO BEGIN
Zaehler := Zaehler * i;
Dec(i);
END;
END;
Faku := Zaehler;
END;
FUNCTION Sqr(x : REAL) : REAL;
BEGIN
InternError := -2;
IF Abs(x) < 1e19 THEN Sqr := System.Sqr(x)
ELSE Sqr := MaxReal;
END;
FUNCTION Sqrt(x : REAL) : REAL;
BEGIN
InternError := -3;
IF x < 0.0 THEN Sqrt := MaxReal
ELSE Sqrt := System.Sqrt(x);
END;
FUNCTION Power(x, y : REAL) : REAL;
BEGIN
InternError := -4;
IF (x <> 0.0) OR (y <> 0.0) THEN BEGIN
IF x > 0.0 THEN
Power := Exp(y*Ln(x))
ELSE IF x = 0.0 THEN
Power := 0.0
ELSE IF Frac(y) = 0 THEN
IF Odd(Round(y)) THEN
Power := -Exp(y*Ln(Abs(x)))
ELSE
Power := Exp(y*Ln(Abs(x)))
ELSE BEGIN
Power := MaxReal;
InternError := -5;
END;
END ELSE Power := MaxReal;
END;
FUNCTION PwrOfTen(epn : REAL) : REAL;
BEGIN
PwrOfTen := Exp(epn*Ln10);
END;
FUNCTION Exp(x : REAL) : REAL;
BEGIN
Exp := MaxReal;
IF x > minExp THEN
IF x < maxExp THEN
Exp := System.Exp(x)
ELSE
InternError := -6
ELSE
InternError := -7;
END;
FUNCTION Log(b, z : REAL) : REAL;
BEGIN
Log := MaxReal;
IF b > 0.0 THEN
IF z > 0.0 THEN BEGIN
hilf := System.Ln(b);
IF Abs(hilf) > 1e-7 THEN
Log := System.Ln(z)/hilf
ELSE
InternError := -8
END
ELSE InternError := -9
ELSE InternError := -10;
END;
FUNCTION Lg(x : REAL) : REAL;
BEGIN
InternError := -9;
IF x > 0.0 THEN Lg := System.Ln(x)/Ln10
ELSE Lg := MaxReal;
END;
FUNCTION Lb(x : REAL) : REAL;
BEGIN
InternError := -9;
IF x > 0.0 THEN Lb := System.Ln(x)/Ln2
ELSE Lb := MaxReal;
END;
FUNCTION Ln(x : REAL) : REAL;
BEGIN
InternError := -9;
IF x > 0.0 THEN Ln := System.Ln(x)
ELSE Ln := MaxReal;
END;
FUNCTION Sin2(x : REAL) : REAL;
BEGIN
RadWinkel(x);
Sin2 := System.Sin(x);
END;
FUNCTION Cos2(x : REAL) : REAL;
BEGIN
RadWinkel(x);
Cos2 := System.Cos(x);
END;
FUNCTION Tan2(x : REAL) : REAL;
BEGIN
InternError := -11;
RadWinkel(x);
hilf := System.Cos(x);
IF hilf <> 0.0 THEN Tan2 := System.Sin(x)/hilf
ELSE Tan2 := MaxReal;
END;
FUNCTION Cot2(x : REAL) : REAL;
BEGIN
InternError := -11;
RadWinkel(x);
hilf := System.Sin(x);
IF hilf <> 0.0 THEN Cot2 := System.Cos(x)/hilf
ELSE Cot2 := MaxReal;
END;
FUNCTION ArcSin(x : REAL) : REAL;
BEGIN
InternError := -12;
hilf := Abs(x);
IF hilf > 1.0 THEN
ArcSin := MaxReal
ELSE IF hilf = 1.0 THEN
ArcSin := NormWinkel(x * pi_halbe)
ELSE
ArcSin :=
NormWinkel(System.ArcTan(x/Sqrt(1-Sqr(x))));
END;
FUNCTION ArcCos(x : REAL) : REAL;
BEGIN
InternError := -12;
ArcCos := NormWinkel(pi_haLbe) - ArcSin(x);
END;
FUNCTION ArcTan2(x : REAL) : REAL;
BEGIN
ArcTan2 := Normwinkel(System.ArcTan(x));
END;
FUNCTION ArcCot(x : REAL) : REAL;
BEGIN
ArcCot := NormWinkel(pi_halbe) - ArcTan(x);
END;
FUNCTION Sinh(x : REAL) : REAL;
BEGIN
x := Exp(x);
Sinh := 0.5 * (x - 1/x);
END;
FUNCTION Cosh(x : REAL) : REAL;
BEGIN
x := Exp(x);
Cosh := 0.5 * (x + 1/x);
END;
FUNCTION Tanh(x : REAL) : REAL;
BEGIN
Tanh := 1 - 2/(1 + Exp(2 * x));
InternError := -13;
END;
FUNCTION Coth(x : REAL) : REAL;
BEGIN
InternError := -13;
hilf := Sinh(x);
IF hilf <> 0 THEN Coth := Cosh(x) / hilf
ELSE Coth := MaxReal;
END;
FUNCTION ArSinh(x : REAL) : REAL;
BEGIN
ArSinh := Ln(x + System.Sqrt(Sqr(x) + 1));
InternError := -14;
END;
FUNCTION ArCosh(x : REAL) : REAL;
BEGIN
IF x < 1 THEN
ArCosh := MaxReal
ELSE
ArCosh := Ln(x + System.Sqrt(Sqr(x) - 1));
InternError := -14;
END;
FUNCTION ArTanh(x : REAL) : REAL;
BEGIN
IF Abs(x) < 1.0 THEN
ArTanh := 0.5 * Ln((1+x) / (1-x))
ELSE
ArTanh := MaxReal;
InternError := -14;
END;
FUNCTION ArCoth(x : REAL) : REAL;
BEGIN
IF Abs(x) > 1 THEN
ArCoth := 0.5 * Ln((x+1) / (x-1))
ELSE
ArCoth := MaxReal;
InternError := -14;
END;
FUNCTION RtoStr(zahl : REAL) : STRING;
VAR
i : INTEGER;
negativ, eneg : BOOLEAN;
rExponent : REAL;
Exponent : INTEGER;
hstr1, hstr2, ausstr : STRING [21];
tstzahl : REAL;
BEGIN
IF zahl = 0.0 THEN BEGIN
RtoStr := '0';
Exit;
END;
negativ := (zahl < 0.0);
{ Zahl muŠ wegen Logarithmen immer positiv sein,}
{ negativ wird ggf. auŠerhalb gespeichert. }
IF negativ THEN ausstr := '-'
ELSE ausstr := '';
zahl := Abs(zahl);
rExponent := Ln(zahl)/Ln10;
{ Exponent fĀr spĄtere Normalisierung
herausfiltern }
eneg := (rExponent < 0);
IF eneg THEN Exponent := Trunc(rExponent-1)
ELSE Exponent := Trunc(rExponent);
zahl := zahl / (Exp(Exponent * Ln10));
zahl := Int(zahl * 10e6) / 10e6;
tstzahl := Frac(zahl) * 1e7;
IF (Frac(tstzahl / 10) * 10) = 1 THEN
zahl := zahl -1e-7
ELSE BEGIN
tstzahl := tstzahl / 10;
tstzahl := Frac(tstzahl);
tstzahl := Round(tstzahl * 10);
IF tstzahl = 9 THEN zahl := zahl + 1e-7;
END;
WHILE zahl > 9.999999 DO BEGIN
{ Sonderfall 1*10^nn auch noch normalisieren }
{ (geschieht oben nicht korrekt) }
zahl := zahl / 10;
Inc(Exponent)
END;
IF (Exponent < -3) OR (Exponent > 6) THEN BEGIN
{ Unterscheidung zw. Darstellungen }
{ 1.) Exponentialschreibweise }
Str(zahl:9:7, hstr1);
{ Zahl in STRING umwandeln }
i := Length(hstr1);
WHILE (hstr1[i] = '0') AND
(hstr1[i-1] <> '.') DO BEGIN
Delete(hstr1, i, 1);
Dec(i);
END;
Exponent := Abs(Exponent);
Str(Exponent:2, hstr2);
IF hstr2[1] = ' ' THEN hstr2[1] := '0';
ausstr := ausstr + hstr1 + 'e';
IF eneg THEN ausstr := ausstr + '-';
ausstr := ausstr + hstr2;
END ELSE BEGIN
{ 2.) natĀrliche Schreibweise }
zahl := zahl * (Exp(Exponent * Ln10));
Str(zahl:20:10, hstr1);
WHILE hstr1[1] = ' ' DO Delete(hstr1, 1, 1);
Delete(hstr1, 9, 255);
i := Length(hstr1);
WHILE hstr1[i] = '0' DO BEGIN
Delete(hstr1, i, 1);
Dec(i);
END;
IF hstr1[i] = '.' THEN Delete(hstr1, i, 1);
ausstr := ausstr + hstr1;
END;
RtoStr := ausstr;
END;
FUNCTION ArithErrMsg(ErrNummer : SHORTINT) : STRING;
BEGIN
CASE ErrNummer Of
0 : ArithErrMsg := 'kein Fehler';
-1 : ArithErrMsg := 'FakultĄt zu groŠ';
-2 : ArithErrMsg := 'Quadratfunktion zu groŠ';
-3 : ArithErrMsg := 'WurzelArgument negativ';
-4 : ArithErrMsg := 'Potenz : 0^0 nicht definiert';
-5 : ArithErrMsg := 'Potenz : -x^(z/n) nicht ' +
'definiert';
-6 : ArithErrMsg := 'Exp : Argument zu groŠ';
-7 : ArithErrMsg := 'Exp : Argument zu klein';
-8 : ArithErrMsg := 'Log : Basis darf nicht 1 sein';
-9 : ArithErrMsg := 'LogArithmusArgument muŠ > 0 ' +
'sein';
-10 : ArithErrMsg := 'Log : Basis muŠ > 0 sein';
-11 : ArithErrMsg := 'Winkelfunktion hier nicht ' +
'definiert';
-12 : ArithErrMsg := 'Winkelumkehrfunktion hier ' +
'nicht definiert';
-13 : ArithErrMsg := 'hyp-Funktion hier nicht ' +
'definiert';
-14 : ArithErrMsg := 'Area-Funktion hier nicht ' +
'definiert';
-127 : ArithErrMsg := 'undifferenzierter ' +
'Gleitkommafehler';
END;
END;
BEGIN
Trigonomodus(rad);
InternError := -127;
END.
(* ------------------------------------------------- *)
(* Ende von ARITHMOS.PAS *)
|
unit U_FrmGeraListaPostagem;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, DBCtrls, ComCtrls, Grids, DBGrids, ExtCtrls,
FileCtrl, Math, DateUtils, Mask, IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdFTP, Registry;
type
TFrmGeraListaPostagem = class(TForm)
BitBtnGerar: TBitBtn;
GroupBoxPeridoPostagem: TGroupBox;
LabelDtIni: TLabel;
LabelDtFin: TLabel;
DtPickerDtIni: TDateTimePicker;
DtPickerDtFin: TDateTimePicker;
CboPagante: TDBLookupComboBox;
LabelProd: TLabel;
DBGridPostagem: TDBGrid;
LabelLote: TLabel;
PanelProgress: TPanel;
PanelProgressBar: TProgressBar;
BtnFechar: TBitBtn;
BtnAbrir: TBitBtn;
EdDirDestinoListagem: TEdit;
LblDirDestino: TLabel;
CheckBoxGerar: TCheckBox;
EdLote: TEdit;
StsRemSdx: TStatusBar;
procedure CheckBoxGerarClick(Sender: TObject);
procedure BtnAbrirClick(Sender: TObject);
procedure BtnFecharClick(Sender: TObject);
procedure DBGridPostagemCellClick(Column: TColumn);
procedure DtPickerDtFinUserInput(Sender: TObject; const UserString: string;
var DateAndTime: TDateTime; var AllowChange: Boolean);
procedure DtPickerDtIniUserInput(Sender: TObject; const UserString: string;
var DateAndTime: TDateTime; var AllowChange: Boolean);
procedure DtPickerDtFinCloseUp(Sender: TObject);
procedure DtPickerDtIniCloseUp(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BitBtnGerarClick(Sender: TObject);
private
{ Private declarations }
procedure AtualizaGridPostagem;
procedure ProgressBarStepItOne;
procedure XLSReport;
procedure GeraArquivoPrevisao;
procedure EnviaArquivoPrevisao;
procedure GeraImpressaoListaPostagem;
procedure GeraMidiaSara;
public
{ Public declarations }
end;
var
FrmGeraListaPostagem: TFrmGeraListaPostagem;
filename, chosenDir, fname, destdir : string; // Diretório de Destino para salvar arquivos gerados
implementation
uses DmDados, DB, U_Func, U_FrmRelArSedexListaOL, IniFiles;
{$R *.dfm}
procedure TFrmGeraListaPostagem.BitBtnGerarClick(Sender: TObject);
var i: integer;
Begin
// Preenchimento do Período para pesquisa é obrigatório
if (CompareDate(DtPickerDtIni.Date, DtPickerDtFin.Date) > 0) then
begin
Application.MessageBox(PChar('A data final não pode ser inferior a data inicial.'),
'ADS', MB_OK + MB_ICONERROR);
Exit;
end;
// Obrigatório selecionar um Cartão de Postagem ou Indicar um Lote
if (CboPagante.KeyValue = null) AND (Trim(EdLote.Text) = '') then
begin
Application.MessageBox(PChar('Indique o Lote ou Selecione um Pagante.'),
'ADS', MB_OK + MB_ICONERROR);
EdLote.SetFocus;
Exit;
end;
// checando se a informação de Lote está válida
if (Length(TRim(EdLote.Text)) > 0) AND not (TryStrToInt(EdLote.Text, i) ) then
begin
Application.MessageBox(PChar('Número de Lote inválido!'),
'ADS', MB_OK + MB_ICONERROR);
EdLote.SetFocus;
Exit;
end;
// Caso tenha sido marcado para Gerar Arquivo...
if CheckBoxGerar.Checked then
begin
try
if (EdDirDestinoListagem.Text <> '') then
destdir := chosenDir
else
destdir := GetCurrentDir;
destdir := StringReplace(destdir + '\', '\\','\', [rfReplaceAll]) +
UpperCase(FormatDateTime('yyyy\mmmm\dd', Date)) + '\';
if (not DirectoryExists(destdir))
AND (not SysUtils.ForceDirectories(destdir)) then
raise Exception.CreateFmt('Não foi possível criar o diretório %s', [destdir]);
Except on E : Exception do
begin
application.MessageBox(PChar(E.Message),
'ADS', MB_OK + MB_ICONERROR);
BtnAbrir.SetFocus;
exit;
end;
end;
end;
With Dm do
Begin
// Verificando se há registros para gerar a lista
SqlAux1.Close;
SqlAux1.SQL.Clear;
SqlAux1.SQl.Add('SELECT COUNT(t.sdx_numobj2) AS qt_regs, ');
SqlAux1.SQL.Add(' SUM(t.sdx_peso) AS peso_total, ');
SqlAux1.SQL.Add(' SUM(t.sdx_valdec) AS valdec_total, ');
SqlAux1.SQL.Add(' MIN(t.sdx_numobj) AS obj_ini, ');
SqlAux1.SQL.Add(' MAX(t.sdx_numobj) AS obj_fim ');
SqlAux1.SQl.Add('FROM public.tbsdx_ect e ');
SqlAux1.SQL.Add(' INNER JOIN public.tbsdxserv s ');
SqlAux1.SQL.Add(' ON (e.tbsdxect_prod = s.tbsdxserv_prod) ');
SqlAux1.SQL.Add(' INNER JOIN public.tbsdx02 t ');
SqlAux1.SQL.Add(' ON (e.tbsdxect_sigla || e.tbsdxect_num || ' +
'e.tbsdxect_dv || ''BR'' = t.sdx_numobj2) ');
SqlAux1.SQL.Add('WHERE t.sdx_dtenvio BETWEEN :dtini AND :dtfim ');
SqlAux1.ParamByName('dtini').AsDate := DtPickerDtIni.Date;
SqlAux1.ParamByName('dtfim').AsDate := DtPickerDtFin.Date;
if (CboPagante.KeyValue <> null) then
begin
SqlAux1.SQL.Add(' AND s.tbsdxserv_prod = :prod');
SqlAux1.ParamByName('prod').AsInteger := CboPagante.KeyValue;
end;
if (Length(TRim(EdLote.Text)) > 0) then
begin
SqlAux1.SQL.Add(' AND t.sdx_seqcarga = :lote');
SqlAux1.ParamByName('lote').AsInteger := StrToInt64(EdLote.Text);
end;
SqlAux1.Open;
if (SqlAux1.FieldByName('qt_regs').AsInteger > 0) then
Begin
// Há registros para gerar a listagem. Criando-a...
// Inciando a consulta para gerar os itens da lista a ser impressa
SqlSdx3.Close;
SqlSdx3.SQL.Clear;
// 0 1
SqlSdx3.SQL.Add('SELECT DISTINCT sdx_numobj, sdx_paisorigem, ');
// 2 3 4 5
SqlSdx3.SQL.Add(' sdx_cep, sdx_seqcarga, sdx_numobj1, sdx_peso, ');
// 6 7 8 9
SqlSdx3.SQL.Add(' sdx_valdec, sdx_siglaobj, sdx_cmp, sdx_bas, ');
// 10 11 12 13 14
SqlSdx3.SQL.Add(' sdx_alt, sdx_cobdest, sdx_numobj2, tbsdxserv_nrocto, ');
// 14 15 16 17
SqlSdx3.SQL.Add(' tbsdxserv_crtpst, sdx_nomdest, sdx_codcli, sdx_idcli, ');
// 18 19 20 21
SqlSdx3.SQL.Add(' sdx_codoperacao, sdx_numobj3, sdx_endedest, sdx_cidade, ');
// 22 22 23 24
SqlSdx3.SQL.Add(' sdx_uf, sdx_numseqarq, sdx_numseqreg, sdx_dtcarga, ');
// 25 26 27 28
SqlSdx3.SQL.Add(' sdx_cepnet, sdx_numobj4, sdx_numobj5, sdx_valor, ');
// 29 30 31
SqlSdx3.SQL.Add(' sdx_qtde, sdx_tvalor, e.tbsdxect_sigla ');
SqlSdx3.SQl.Add('FROM public.tbsdx_ect e ');
SqlSdx3.SQL.Add(' INNER JOIN public.tbsdxserv s ');
SqlSdx3.SQL.Add(' ON (e.tbsdxect_prod = s.tbsdxserv_prod) ');
SqlSdx3.SQL.Add(' INNER JOIN public.tbsdx02 t ');
SqlSdx3.SQL.Add(' ON (e.tbsdxect_sigla || e.tbsdxect_num || ' +
'e.tbsdxect_dv || ''BR'' = t.sdx_numobj2) ');
SqlSdx3.SQL.Add('WHERE t.sdx_dtenvio BETWEEN :dtini AND :dtfim ');
SqlSdx3.ParamByName('dtini').AsDate := DtPickerDtIni.Date;
SqlSdx3.ParamByName('dtfim').AsDate := DtPickerDtFin.Date;
if (CboPagante.KeyValue <> null) then
begin
SqlSdx3.SQL.Add(' AND s.tbsdxserv_prod = :prod');
SqlSdx3.ParamByName('prod').AsInteger := CboPagante.KeyValue;
end;
if (Length(TRim(EdLote.Text)) > 0) then
begin
SqlSdx3.SQL.Add(' AND t.sdx_seqcarga = :lote');
SqlSdx3.ParamByName('lote').AsInteger := StrToInt64(EdLote.Text);
end;
SqlSdx3.SQL.Add('ORDER BY sdx_cep');
SqlSdx3.Open;
// Gerando o Relatório a ser impresso
GeraImpressaoListaPostagem;
// Requisitado Geração de arquivo de postagem
if CheckBoxGerar.Checked then
Begin
Try
// Mostrando o ProgressBar
PanelProgressBar.Max := SqlSdx3.RecordCount * 3; // Serão 3 listas
PanelProgressBar.Position := 0;
PanelProgress.Visible := True;
PanelProgress.Refresh;
// Gerando Arquivo de Mídia para enviar via E-mail
GeraMidiaSara;
// Gerando o XLS
XLSReport;
// Aviso de que tudo saiu OK
Application.MessageBox(
PChar('Geração de Arquivos efetuado com sucesso!' + #13#10 +
'Os seguintes arquivos foram gerados : ' + #13#10 +
'"' + filename + '" e "' + ChangeFileExt(filename, '.xls') +
'".'
), 'ADS', MB_OK + MB_ICONINFORMATION);
finally
// Resetando e ocultando o Progress Bar
PanelProgress.Caption := 'Executando a operação. Aguarde...';
PanelProgress.Hide;
PanelProgressBar.Position := 0;
end;
end; // End Geração de Arquivo Para envio aos correios
end // End Com Resultados
else
Application.MessageBox(
PChar('Não Há Registros com os Parametros Informados'),
'ADS', MB_OK + MB_ICONERROR);
end; // End With
End;
procedure TFrmGeraListaPostagem.BtnAbrirClick(Sender: TObject);
var Registro: TRegistry;
begin
if SelectDirectory('Selecione o diretório de destino',
chosenDir,
chosenDir) then
Begin
chosenDir := StringReplace(chosenDir + '\', '\\','\', [rfReplaceAll]);
Registro := TRegistry.Create;
Registro.RootKey := HKEY_CURRENT_USER;
if Registro.OpenKey('ADS_ADSRESS', true) then
// Verificando existência do diretório base
Registro.WriteString('UltDirListaPostagem', chosenDir);
EdDirDestinoListagem.Text := chosenDir;
end;
end;
procedure TFrmGeraListaPostagem.BtnFecharClick(Sender: TObject);
begin
Close;
end;
procedure TFrmGeraListaPostagem.CheckBoxGerarClick(Sender: TObject);
var st : Boolean;
begin
st := CheckBoxGerar.Checked;
LblDirDestino.Enabled := st;
EdDirDestinoListagem.Enabled := st;
BtnAbrir.Enabled := st;
end;
procedure TFrmGeraListaPostagem.AtualizaGridPostagem;
begin
with Dm do
begin
SqlSdxServ.Close;
SqlSdxServ.SQL.Clear;
SqlSdxServ.SQL.Add('SELECT s.tbsdxserv_dsc, s.tbsdxserv_crtpst, s.tbsdxserv_sigla, ');
SqlSdxServ.SQL.Add(' s.tbsdxserv_cod, s.tbsdxserv_prod, s.tbsdxserv_dtcad, ');
SqlSdxServ.SQL.Add(' s.tbsdxserv_usu, s.tbsdxserv_nrocto, s.tbsdxserv_status, ');
SqlSdxServ.SQL.Add(' s.tbsdxserv_txasrv, ');
SqlSdxServ.SQL.Add(' COUNT(t.sdx_numobj2) AS qtobjs ');
SqlSdxServ.SQL.Add('FROM public.tbsdx_ect e ');
SqlSdxServ.SQL.Add(' INNER JOIN public.tbsdxserv s ');
SqlSdxServ.SQL.Add(' ON (e.tbsdxect_prod = s.tbsdxserv_prod) ');
SqlSdxServ.SQL.Add(' INNER JOIN public.tbsdx02 t ');
SqlSdxServ.SQL.Add(' ON (e.tbsdxect_sigla || e.tbsdxect_num || ' +
'e.tbsdxect_dv || ''BR'' = t.sdx_numobj2) ');
SqlSdxServ.SQL.Add('WHERE t.sdx_dtenvio BETWEEN :dtini AND :dtfim ');
SqlSdxServ.SQL.Add('GROUP BY s.tbsdxserv_dsc, s.tbsdxserv_crtpst, ');
SqlSdxServ.SQL.Add(' s.tbsdxserv_sigla, s.tbsdxserv_cod, ');
SqlSdxServ.SQL.Add(' s.tbsdxserv_dtcad, s.tbsdxserv_prod, s.tbsdxserv_dtcad,');
SqlSdxServ.SQL.Add(' s.tbsdxserv_usu, s.tbsdxserv_nrocto, s.tbsdxserv_status,');
SqlSdxServ.SQL.Add(' tbsdxserv_txasrv');
SqlSdxServ.SQL.Add('HAVING COUNT(t.sdx_numobj2) > 0 ');
SqlSdxServ.ParamByName('dtini').AsDate := DtPickerDtIni.Date;
SqlSdxServ.ParamByName('dtfim').AsDate := DtPickerDtFin.Date;
SqlSdxServ.Open;
CboPagante.Refresh;
SqlSdx7.Close;
SqlSdx7.ParamByName('dtini').AsDate := DtPickerDtIni.Date;
SqlSdx7.ParamByName('dtfim').AsDate := DtPickerDtFin.Date;
SqlSdx7.Open;
DBGridPostagem.Refresh;
end;
end;
procedure TFrmGeraListaPostagem.DBGridPostagemCellClick(Column: TColumn);
begin
With Dm Do
begin
DtPickerDtIni.DateTime := SqlSdx7mindt.Value;
DtPickerDtFin.DateTime := SqlSdx7maxdt.Value;
CboPagante.KeyValue := SqlSdx7tbsdxserv_prod.Value;
EdLote.Text := IntToStr(SqlSdx7lote.Value);
end;
end;
procedure TFrmGeraListaPostagem.DtPickerDtFinCloseUp(Sender: TObject);
begin
AtualizaGridPostagem;
end;
procedure TFrmGeraListaPostagem.DtPickerDtFinUserInput(Sender: TObject;
const UserString: string; var DateAndTime: TDateTime;
var AllowChange: Boolean);
begin
AtualizaGridPostagem;
end;
procedure TFrmGeraListaPostagem.DtPickerDtIniCloseUp(Sender: TObject);
begin
AtualizaGridPostagem;
end;
procedure TFrmGeraListaPostagem.DtPickerDtIniUserInput(Sender: TObject;
const UserString: string; var DateAndTime: TDateTime;
var AllowChange: Boolean);
begin
AtualizaGridPostagem;
end;
procedure TFrmGeraListaPostagem.FormShow(Sender: TObject);
var IniFile : TIniFile;
begin
// Ajustando data de exibição
DtPickerDtIni.Date := Date;
DtPickerDtFin.Date := Date;
AtualizaGridPostagem;
// Recuperando o diretório usando anteriormente
IniFile := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
chosenDir := iniFile.ReadString('Arquivos', 'Local', GetCurrentDir);
EdDirDestinoListagem.Text := chosenDir;
end;
procedure TFrmGeraListaPostagem.ProgressBarStepItOne;
begin
PanelProgressBar.StepBy(1);
PanelProgressBar.StepBy(-1);
PanelProgressBar.StepBy(1);
PanelProgressBar.Update;
PanelProgress.Refresh;
end;
{
Gera um arquivo XLS para Controle
}
procedure TFrmGeraListaPostagem.XLSReport;
var
XL : TDataSetToExcel;
cab, f : String;
Begin
PanelProgress.Caption := 'Criando Relatório de envios em XLS';
With Dm do
begin
SqlAux1.Close;
SqlAux1.SQL.Clear;
SqlAux1.SQL.Add('SELECT DISTINCT t.sdx_siglaobj as "TIPO", ');
SqlAux1.SQL.Add(' t.sdx_numobj2 as "Nº Objeto", ');
SqlAux1.SQL.Add(' SUBSTR(t.sdx_nomdest, 1, 4) AS "AG.", ');
SqlAux1.SQL.Add(' SUBSTR(t.sdx_nomdest, 7, 40) AS "DESTINO", ') ;
SqlAux1.SQL.Add(' t.sdx_endedest as "ENDERECO", t.sdx_cidade as "CIDADE",');
SqlAux1.SQL.Add(' t.sdx_uf as "UF", t.sdx_cep as "CEP", ');
SqlAux1.SQL.Add(' t.sdx_dtmov as "DATA ENVIO", ');
SqlAux1.SQL.Add(' t.sdx_peso as "PESO" ');
SqlAux1.SQl.Add('FROM public.tbsdx_ect e ');
SqlAux1.SQL.Add(' INNER JOIN public.tbsdxserv s ');
SqlAux1.SQL.Add(' ON (e.tbsdxect_prod = s.tbsdxserv_prod) ');
SqlAux1.SQL.Add(' INNER JOIN public.tbsdx02 t ');
SqlAux1.SQL.Add(' ON (e.tbsdxect_sigla || e.tbsdxect_num || ' +
'e.tbsdxect_dv || ''BR'' = t.sdx_numobj2) ');
SqlAux1.SQL.Add('WHERE t.sdx_dtenvio BETWEEN :dtini AND :dtfim ');
SqlAux1.ParamByName('dtini').AsDate := DtPickerDtIni.Date;
SqlAux1.ParamByName('dtfim').AsDate := DtPickerDtFin.Date;
if (CboPagante.KeyValue <> null) then
begin
SqlAux1.SQL.Add(' AND s.tbsdxserv_prod = :prod');
SqlAux1.ParamByName('prod').AsInteger := CboPagante.KeyValue;
end;
if (Length(TRim(EdLote.Text)) > 0) then
begin
SqlAux1.SQL.Add(' AND t.sdx_seqcarga = :lote');
SqlAux1.ParamByName('lote').AsInteger := StrToInt64(EdLote.Text);
end;
SqlAux1.SQL.Add('ORDER BY t.sdx_cep ');
SqlAux1.Open;
cab := 'LISTA DE POSTAGEM - CONTRATO ESPECIAL - SEDEX: ' +
SqlSdxServtbsdxserv_crtpst.AsString + ' - ' +
FormatDateTime('ddmmyyyy', DtPickerDtIni.Date ) + '.xls';
f := ChangeFileExt(filename, '.xls');
try
SqlAux1.First;
XL := TDataSetToExcel.Create(SqlAux1, destdir + f, cab);
XL.WriteFile;
XL.Free;
Except
application.MessageBox(PChar('Ocorreu um erro ao criar o arquivo "' + f + '".'),
'ADS', MB_OK + MB_ICONERROR);
end;
end;
end;
procedure TFrmGeraListaPostagem.GeraArquivoPrevisao;
type
TArqPrevDat = Record
nome: string[15];
diames : string[4];
seq : Char;
envio : TDateTime;
qtde : Integer;
remessa: Integer;
end;
var linha : String;
regs, remessa, i : Integer;
seq : Char;
ArqPrevDat : TArqPrevDat;
ArqReg : File of TArqPrevDat;
arq : TextFile;
Begin
PanelProgress.Caption := 'Gerando arquivo de Previsão de Postagem';
// Valores padrão para quando o arquivo não é encontrado
seq := '0';
remessa := DayOfTheYear(Date) * (CurrentYear - 2014);
try
// Lendo informação do arquivo de Dados
AssignFile(ArqReg, 'ads.dat');
if not FileExists('ads.dat') then
Rewrite(ArqReg)
else
Reset(ArqReg);
regs := FileSize(ArqReg);
if (regs > 0) then
begin
Seek(ArqReg, regs - 1);
Read(ArqReg, ArqPrevDat);
if (ArqPrevDat.diames = FormatDateTime('ddmm', Date)) then
begin
// Lendo o ultimo sequencial utilizado, incrementando-o e verificando
seq := Chr((Ord(ArqPrevDat.seq) + 1));
while not (seq in ['0'..'9','A'..'Z']) do
seq := Chr(Ord(seq)+1);
// Lendo o ultimo sequencial de arquivo utilizado e incrementando-o
remessa := ArqPrevDat.remessa + 1;
end;
end;
except on E: Exception do
Begin
Application.MessageBox(Pchar('Não foi possível encontrar a informação de ' +
'último arquivo de Previsão enviado.' + #13+#10+'Reiniciando o contador.'),
'ADS', MB_OK + MB_ICONERROR);
CloseFile(ArqReg);
end;
end;
// Nome do arquivo de destino
fname := Dm.SqlSdxServtbsdxserv_sigla.AsString + '1' +
FormatDateTime('ddmm', Date) + seq + '.SD1';
try
AssignFile(arq, destdir + fname);
Rewrite(arq);
except on E: Exception do
Begin
Application.MessageBox(Pchar('Não foi possível criar o arquivo ' +
'de Previsão de Postagem.' + #13+#10 +
'Por favor informe o ocorrido para a área de T.I..'),
'ADS', MB_OK + MB_ICONERROR);
CloseFile(arq);
end;
end;
// Iniciando a criação dos registros
// ###### REGISTRO HEADER - INÍCIO
linha := '8' + // Tipo de Registro - Header
LPad(Dm.SqlSdxServtbsdxserv_prod.AsString, 4, '0') + // Código do Cliente
LPad('0', 15, '0') + // Filler
RPad(Dm.SqlSdxServtbsdxserv_dsc.AsString, 40, ' ') + // Nome do Cliente
FormatDateTime('yyyymmdd', Date) + // Data Geração do arquivo
LPad(IntToStr(Dm.SqlSdx3.RecordCount + 1), 6, '0') + // Quantidade de Registros do Arquivo incluindo o Header
LPad('0', 94, '0') + // Filler
Format('%.5d', [remessa]) + // Número de Remessa
Format('%.7d', [1]); // Sequencial Inicial de Registro
// Escrevendo o Header o arquivo
WriteLn(arq, linha);
// ###### REGISTRO HEADER - FIM
// ##### REGISTRO DETALHE - INICIO
With Dm do
Begin
// Reposicionando o ponteiro do cursor para o primeiro resultado
SqlSdx3.First;
i := 2; // Sequencial Registro Iniciando em 2
While not SqlSdx3.Eof do
Begin
linha := '9' + // Tipo de Registro - Detalhe
LPad(Dm.SqlSdxServtbsdxserv_prod.AsString, 4, '0') + // Código Cliente
Dm.SqlSdxServtbsdxserv_sigla.AsString + // Identificador Cliente
SqlSdx3.FieldByName('sdx_numobj2').AsString + // Sigla Objeto + Numero Objeto + Pais Origem
'1101' + // Código da Operação (Vide Documento ARQUIVO_PREV_RET
RPad(' ', 16, ' ') + // Campo Livre
LPad(
ReplaceNonAscii(Trim(SqlSdx3.FieldByName('sdx_nomdest').AsString)),
40, ' ') + // Nome Destinatário
copy(LPad(
ReplaceNonAscii(Trim(SqlSdx3.FieldByName('sdx_endedest').AsString)),
40, ' '), 1, 40) + // Endereço Destinatário
copy(LPad(
ReplaceNonAscii(Trim(SqlSdx3.FieldByName('sdx_cidade').AsString)),
30, ' '), 1, 40) + // Cidade Endereço Destinatário
Trim(SqlSdx3.FieldByName('sdx_uf').AsString) + // UF Endereço Destinatário
Trim(SqlSdx3.FieldByName('sdx_cep').AsString) + // CEP Endereço Destinatário
RPad('0', 8, '0') + // Campo Livre
Format('%.5d', [remessa]) + // Número Remessa
Format('%.7d', [i]); // Sequencial Registro
i := i + 1;
WriteLn(arq, linha);
SqlSdx3.Next;
ProgressBarStepItOne;
end;
end;
// ##### REGISTRO DETALHE - FIM
// Gerando um novo Registro para incluir no arquivo de Registros
ArqPrevDat.nome := fname;
ArqPrevDat.diames := FormatDateTime('ddmm', Date);
ArqPrevDat.seq := seq;
ArqPrevDat.envio := Date;
ArqPrevDat.qtde := i;
ArqPrevDat.remessa := remessa;
Seek(ArqReg, Filesize(ArqReg));
Write(ArqReg, ArqPrevDat);
CloseFile(ArqReg);
CloseFile(arq);
end;
procedure TFrmGeraListaPostagem.EnviaArquivoPrevisao;
var iniFile : TIniFile;
IdFtp : TIdFTP;
begin
IdFtp := TIdFTP.Create(Self);
try
PanelProgress.Caption := 'Enviando arquivos para o Correios';
IniFile := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
// Nome/IP do Servidor de destino dos arquivos
IdFtp.Host := iniFile.ReadString('FTPCORREIOS', 'Host', '10.1.1.10');
// Porta de conexão ao FTP
IdFtp.Port := iniFile.ReadInteger('FTPCORREIOS', 'Porta', 21);
// Nome de usuario
IdFtp.Username := iniFile.ReadString('FTPCORREIOS', 'Usuario', 'joe');
// Senha de acesso
IdFtp.Password := iniFile.ReadString('FTPCORREIOS', 'Senha', 'doe');
// Tempo máximo de espera por uma conexão
IdFtp.ReadTimeout := iniFile.ReadInteger('FTPCORREIOS', 'Timeout', 5000);
except
raise Exception.Create('Erro ao ler informações do arquivo de configuração!');
iniFile.Free;
exit;
end;
try
IdFtp.Passive := true;
// Conectando
IdFtp.Connect;
// Diretório de Destino para o arquivo
IdFtp.ChangeDir(iniFile.ReadString('FTPCORREIOS', 'Destino', 'ENTRADA'));
// Enviando o arquivo recém-criado
IdFtp.Put(destdir + fname, fname, False);
// Fechando a conexão
IdFtp.Disconnect;
Except
IdFtp.Free;
ShowMessage('Não foi possível enviar os arquivos para o FTP destino!');
end;
end;
procedure TFrmGeraListaPostagem.GeraImpressaoListaPostagem;
begin
// Criando o formulário de Listagem de Postagem
Application.CreateForm(TFrmRelArSedexListaOL, FrmRelArSedexListaOL);
// Definindo variáveis de sumário para o relatório impresso
FrmRelArSedexListaOl.pesoTotal := Dm.SqlAux1.FieldByName('peso_total').AsFloat;
FrmRelArSedexListaOl.valDecTotal := Dm.SqlAux1.FieldByName('valdec_total').AsFloat;
FrmRelArSedexListaOl.qtObjs := Dm.SqlAux1.FieldByName('qt_regs').AsInteger;
FrmRelArSedexListaOl.objIni := Dm.SqlAux1.FieldByName('obj_ini').AsString;
FrmRelArSedexListaOl.objfim := Dm.SqlAux1.FieldByName('obj_fim').AsString;
FrmRelArSedexListaOL.RLReport1.PreviewModal;
FrmRelArSedexListaOL.RLReport1.Destroy;
end;
procedure TFrmGeraListaPostagem.GeraMidiaSara;
var seq, i, comprimento, largura, altura : Integer;
searchResult : TSearchRec;
arq : TextFile;
linhabase, linha : String;
begin
PanelProgress.Caption := 'Criando arquivo de Mídia SARA';
seq := 0;
try
// Nome do arquivo de destino
// Pesquisando o diretório corrente para gerar arquivos únicos
if (FindFirst(destdir + '*_' + FormatDateTime('ddmmyy', Date) +
'_*.txt', faArchive, searchResult) = 0 ) then
begin
repeat
// Extraindo o sequencial do arquivo
i := LastDelimiter('_', searchResult.Name);
if (TryStrToInt(copy(searchResult.Name, i, 3), i)) then
seq := Max(i, seq);
until FindNext(searchResult) <> 0;
FindClose(searchResult);
end;
filename := Dm.SqlSdxServtbsdxserv_crtpst.AsString + '_' +
FormatDateTime('ddmmyy', Date) + '_' +
LPad(IntToStr(seq + 1), 3, '0') + '.txt';
// Garantindo que não existe arquivo com a nomenclatura passada
while FileExists(destdir + filename) do
begin
seq := seq + 1;
filename := Dm.SqlSdxServtbsdxserv_crtpst.AsString + '_' +
FormatDateTime('ddmmyy', Date) + '_' +
LPad(IntToStr(seq + 1), 3, '0') + '.txt';
end;
AssignFile(arq, destdir + filename);
except
begin
Application.MessageBox(PChar('Não foi possível utilizar o diretório'),
'ADS', MB_OK + MB_ICONERROR);
exit;
end;
end; // End Try Except
try
Rewrite(arq);
except
begin
Application.MessageBox(PChar('Não foi possível criar o arquivo de registros.'),
'ADS', MB_OK + MB_ICONERROR);
exit;
end;
end; // End Try
// Iniciando a geração dos arquivos
// Iniciando a criação dos registros
// Linha Base do Registro Detalhe, apenas com os placeholders
// Ver documentação No arquivo LAYOUT LISTA POSTAGEM Sistema SARA - TXT
linhabase := '3' + // Tipo de Registro (3 - Detalhe lista de Postagem)
'0000000000000000000000' + // Filler
'%s' + // Número do Contrato Placeholder
'09036539' + // Código Administrativo do Cliente
'%s' + // Cep do Destino Placeholder
'40436' + // Código do Serviço (SFI)
'55' + // Grupo Páis (Brasil) Conforme Tabela Serv. Adic.
'37' + // Cod Serv Adic 1 (Arquivo e Controle AR (Fac)) Conforme Tabela Serv. Adic.
'19' + // Cod Serv Adic 2 (Ad Valorem)
'00' + // Cod Serv Adic 3
'%s' + // Valor Declarado Placeholder
'00000000000' + // FILLER
'%.9d' + // Número de Etiqueta Placeholder
'%.5d' + // Peso Placeholder
'0000000000000000000000000000000000000000000' + // FILLER
'%s' + // Nº Cartão Postagem Placeholder
'0000000' + // Número Nota Fiscal
'%s' + // Sigla Serviço Placeholder
'%.5d' + // Comprimento Objeto Placeholder
'%.5d' + // Largura Objeto Placeholder
'%.5d' + // Altura Objeto Placeholder
'%s' + // Valor Cobrar Destinatario Placeholder
'%s' + // Nome Destinatario Placeholder
'002' + //Código Tipo Objto (01:Envelope, 02:Pacote, 03:Rolo)
'00000'; // Diâmetro do objeto
With Dm do
Begin
// Reposicionando o ponteiro do cursor para o primeiro resultado
SqlSdx3.First;
While not SqlSdx3.Eof do
Begin
comprimento := Round(SqlSdx3.FieldByName('sdx_cmp').AsFloat * 100);
if comprimento = 0 then
comprimento := 16; // Comprimento mínimo para efeito de cálculo
largura := Round(SqlSdx3.FieldByName('sdx_bas').ASFloat * 100);
if largura = 0 then
largura := 16; // largura mínima
altura := Round(SqlSdx3.FieldByName('sdx_alt').ASFloat * 100);
if (altura = 0) then
altura := 16; // Altura mínima
linha := Format(linhabase,
[LPad(SqlSdx3.FieldByName('tbsdxserv_nrocto').AsString, 10, '0'), // Número do Contrato
SqlSdx3.FieldByName('sdx_cep').AsString, // Cep do Destino
LPad(
Format('%f', [SqlSdx3.FieldByName('sdx_valdec').AsFloat]),
8, '0'), // Valor Declarado
SqlSdx3.FieldByName('sdx_numobj').AsInteger, // Número da Etiqueta (Num Objeto)
Round(SqlSdx3.FieldByName('sdx_peso').AsFloat * 1000), // Peso (Armazenado em Kg e convertido para g)
LPad(SqlSdx3.FieldByName('tbsdxserv_crtpst').AsString, 11, '0'), // Cartão de Postagem
SqlSdx3.FieldByName('tbsdxect_sigla').AsString, // Sigla do Serviço
comprimento, // Comprimento do Objeto em cm
largura, // Largura do Objeto em cm
altura, // Altura do Objeto em cm
LPad(Format('%f', [SqlSdx3.FieldByName('sdx_valdec').AsFloat]),
8, '0'), // Valor a Cobrar do Destinatário
copy(LPad(
ReplaceNonAscii(Trim(SqlSdx3.FieldByName('sdx_nomdest').AsString)),
40, ' '),
1, 40) // Nome do Destinatário
]);
WriteLn(arq, linha);
SqlSdx3.Next;
ProgressBarStepItOne;
End; // End While SqlSdx3.Eof
// Trailer do arquivo - Ver documentação do Layout
linha := Format('9%.8d%s', [SqlSdx3.RecordCount + 1, LPad(' ', 129, ' ')]);
WriteLn(arq, linha);
CloseFile(Arq);
end;
end;
end.
|
unit Marvin.PoC.IA.StartUI;
{
MIT License
Copyright (c) 2018-2019 Marcus Vinicius D. B. Braga
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
interface
uses
{ marvin }
Marvin.Core.InterfacedList,
Marvin.Core.IA.Connectionist.Classifier,
Marvin.Utils.VCL.StyleManager,
{ embarcadero }
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
VCL.Graphics,
VCL.Controls,
VCL.Forms,
VCL.Dialogs,
VCL.StdCtrls,
VCL.ExtCtrls,
VCL.ComCtrls,
VCL.WinXCtrls,
VCL.Menus,
VclTee.TeeGDIPlus,
VclTee.TeEngine,
VclTee.Series,
VclTee.TeeProcs,
VclTee.Chart,
VCLTee.TeeSpline;
type
TFormStart = class(TForm)
ActivityIndicator: TActivityIndicator;
ButtonLoadFile: TButton;
ChartIrisDataset: TChart;
ChartTrain: TChart;
ItemStyles: TMenuItem;
Label1: TLabel;
LabelCabecalhoTeste: TLabel;
LabelCabecalhoTreino: TLabel;
LineCost: TLineSeries;
MemoData: TMemo;
MemoPredict: TMemo;
MemoTrain: TMemo;
PageControlData: TPageControl;
PageControlTrain: TPageControl;
PanelGraphicsData: TPanel;
PanelToolBar: TPanel;
pgcInfo: TPageControl;
pnl1: TPanel;
PopupMenu: TPopupMenu;
ProgressBar: TProgressBar;
SeriesSetosa: TPointSeries;
SeriesVersicolor: TPointSeries;
SeriesVirginica: TPointSeries;
TabDataFile: TTabSheet;
TabSheetCollectionData: TTabSheet;
TabSheetGraphicsData: TTabSheet;
TabSheetTrainData: TTabSheet;
TabSheetTrainGraphic: TTabSheet;
TabTest: TTabSheet;
TabTrain: TTabSheet;
TimerCost: TTimer;
procedure ButtonLoadFileClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TimerCostTimer(Sender: TObject);
private
type TMemoArray = array of TMemo;
private
FStylesManager: IVclStyleManager;
FMlp: IClassifier;
FIsRunning: Boolean;
private
function ClearSeries: TFormStart;
function GetIrisData: TFormStart;
function ShowIrisData(const AInput, AOutput: TDoubleArray): TFormStart;
function ShowData(const AMemo: TMemo; const AInputData: IList<TDoubleArray>; const AOutputData: IList<TDoubleArray>): TFormStart;
function ShowOriginalData(const AText: string): TFormStart;
function ShowConvertedData(const AInputData: IList<TDoubleArray>; const AOutputData: IList<TDoubleArray>): TFormStart;
function ShowTreinData(const AInputData: IList<TDoubleArray>; const AOutputData: IList<TDoubleArray>): TFormStart;
function ShowTestData(const AInputData: IList<TDoubleArray>; const AOutputData: IList<TDoubleArray>): TFormStart;
function ShowPredictedData(const AInputData: IList<TDoubleArray>; const AOutputData: IList<TDoubleArray>; const AFitCost: Double; const APredictCost: Double): TFormStart;
function ShowResume(const AMlp: IClassifier; const ATestOutputData: IList<TDoubleArray>; const APredictedData: IList<TDoubleArray>): TFormStart;
procedure ExecutePredict(const AFileName: string);
procedure InitProcessIndicators;
procedure ReleaseProcessIndicators;
procedure BeginUpdateMemos(const AMemos: TMemoArray);
procedure EndUpdateMemos(const AMemos: TMemoArray);
public
end;
var
FormStart: TFormStart;
implementation
uses
{ embarcadero }
System.Threading,
{ marvin }
Marvin.Core.IA.Connectionist.Metric,
Marvin.PoC.IA.DataConverter,
Marvin.PoC.IA.DataConverter.Clss,
Marvin.Core.IA.Connectionist.ActivateFunction.Clss,
Marvin.Core.IA.Connectionist.MLPClassifier.Clss,
Marvin.Core.IA.Connectionist.TestSplitter.Clss,
Marvin.Core.IA.Connectionist.Metric.Clss,
Marvin.Core.IA.Connectionist.LayerInitInfo.Clss;
{$R *.dfm}
procedure TFormStart.BeginUpdateMemos(const AMemos: TMemoArray);
var
LIndex: Integer;
begin
for LIndex := Low(AMemos) to High(AMemos) do
begin
AMemos[LIndex].Lines.BeginUpdate;
end;
end;
procedure TFormStart.ButtonLoadFileClick(Sender: TObject);
begin
Self.GetIrisData;
end;
function TFormStart.ShowIrisData(const AInput, AOutput: TDoubleArray): TFormStart;
begin
// Ainda está faltando exibir o restante dos dados nas séries.
Result := Self;
// setosa
if AOutput.IsEquals([1, 0, 0]) then
begin
SeriesSetosa.AddXY(AInput[0], AInput[1]);
end
// virginica
else if AOutput.IsEquals([0, 1, 0]) then
begin
SeriesVirginica.AddXY(AInput[0], AInput[1]);
end
// versicolor
else if AOutput.IsEquals([0, 0, 1]) then
begin
SeriesVersicolor.AddXY(AInput[0], AInput[1]);
end;
end;
function TFormStart.GetIrisData: TFormStart;
var
LFileName: TFileName;
LExecute: Boolean;
begin
Result := Self;
MemoData.Lines.Clear;
MemoTrain.Lines.Clear;
pgcInfo.ActivePage := TabTrain;
{$WARNINGS OFF}
with TFileOpenDialog.Create(nil) do
begin
try
var LFileType := FileTypes.Add;
LFileType.FileMask := '*.csv';
LFileType := FileTypes.Add;
LFileType.FileMask := '*.*';
LExecute := Execute;
if LExecute then
begin
LFileName := FileName;
end;
finally
Free;
end;
end;
{$WARNINGS ON}
if LExecute then
begin
TTask.Run(
procedure
begin
Self.ExecutePredict(LFileName);
end);
end;
end;
procedure TFormStart.InitProcessIndicators;
begin
ProgressBar.Visible := True;
ProgressBar.Position := 0;
ActivityIndicator.BringToFront;
ActivityIndicator.Animate := True;
Screen.Cursor := crHourGlass;
Self.ClearSeries;
TimerCost.Enabled := True;
end;
procedure TFormStart.ReleaseProcessIndicators;
begin
TimerCost.Enabled := False;
Screen.Cursor := crDefault;
ActivityIndicator.Animate := False;
ActivityIndicator.SendToBack;
ProgressBar.Visible := False;
end;
function TFormStart.ShowData(const AMemo: TMemo; const AInputData: IList<TDoubleArray>; const AOutputData: IList<TDoubleArray>): TFormStart;
var
LInput, LOutput: TDoubleArray;
begin
Result := Self;
{ recupera os dados }
LInput := AInputData.First;
LOutput := AOutputData.First;
{ percorre todos os dados }
while not (AInputData.Eof) do
begin
{ converte o resultado as saídas para 0 ou 1 }
LOutput.ToBinaryValue;
{ exibe }
AMemo.Lines.Add(Format('Inputs: [%3.8f, %3.8f, %3.8f, %3.8f]; Outputs: [%3.8f, %3.8f, %3.8f]', [LInput[0], LInput[1], LInput[2], LInput[3], LOutput[0], LOutput[1], LOutput[2]]));
Self.ShowIrisData(LInput, LOutput);
{ recupera os dados }
LInput := AInputData.MoveNext;
LOutput := AOutputData.MoveNext;
end;
end;
function TFormStart.ShowOriginalData(const AText: string): TFormStart;
begin
Result := Self;
MemoData.Lines.Text := AText.Trim;
MemoData.Lines.Insert(0, Format('IRIS ORIGINAL DATA: (%d)', [MemoData.Lines.Count]));
MemoData.Lines.Insert(1, '------------------');
MemoData.Lines.Insert(2, '');
end;
function TFormStart.ShowPredictedData(const AInputData: IList<TDoubleArray>; const AOutputData: IList<TDoubleArray>; const AFitCost: Double; const APredictCost: Double): TFormStart;
begin
Result := Self;
MemoPredict.Lines.Add('');
MemoPredict.Lines.Add(Format('IRIS PREDICTED DATA: (%d)', [AInputData.Count]));
MemoPredict.Lines.Add('-------------------');
MemoPredict.Lines.Add('');
Self.ShowData(MemoPredict, AInputData, AOutputData);
MemoPredict.Lines.Add('');
MemoPredict.Lines.Add(Format('FIT COST .....: (%2.8f)', [AFitCost]));
MemoPredict.Lines.Add(Format('PREDICT COST .: (%2.8f)', [APredictCost]));
end;
function TFormStart.ShowResume(const AMlp: IClassifier; const ATestOutputData: IList<TDoubleArray>; const APredictedData: IList<TDoubleArray>): TFormStart;
const
LC_CORRECT: string = 'Correct';
LC_INCORRECT: string = '<-- INCORRECT';
var
LTestData, LPredictedData: TDoubleArray;
LResult: string;
LAccuracy: IMetric;
begin
Result := Self;
MemoPredict.Lines.Add('');
MemoPredict.Lines.Add(Format('RESUME: (%d)', [ATestOutputData.Count]));
MemoPredict.Lines.Add('------');
MemoPredict.Lines.Add('');
LTestData := ATestOutputData.First;
LPredictedData := APredictedData.First;
while not (ATestOutputData.Eof) do
begin
LResult := LC_INCORRECT;
if SameText(LTestData.ToString, LPredictedData.ToString) then
begin
LResult := LC_CORRECT;
end;
MemoPredict.Lines.Add(Format('%d: %s, %s (%s)', [ATestOutputData.Position + 1, LTestData.ToString, LPredictedData.ToString, LResult]));
{ recupera o próximo dado }
LTestData := ATestOutputData.MoveNext;
LPredictedData := APredictedData.MoveNext;
end;
LAccuracy := TAccuracy.New.Calculate(ATestOutputData, APredictedData);
MemoPredict.Lines.Add('');
MemoPredict.Lines.Add(Format('Accuracy .....: Count = %d, Value = %2.8f', [LAccuracy.Count, LAccuracy.Value]));
MemoPredict.Lines.Add(Format('Epochs .......: %d', [AMlp.Epochs]));
MemoPredict.Lines.Add(Format('Epochs Covered: %d', [AMlp.EpochsCovered]));
end;
function TFormStart.ClearSeries: TFormStart;
begin
Result := Self;
LineCost.Clear;
SeriesSetosa.Clear;
SeriesVirginica.Clear;
SeriesVersicolor.Clear;
end;
procedure TFormStart.EndUpdateMemos(const AMemos: TMemoArray);
var
LIndex: Integer;
begin
for LIndex := Low(AMemos) to High(AMemos) do
begin
AMemos[LIndex].Lines.EndUpdate;
end;
end;
procedure TFormStart.ExecutePredict(const AFileName: string);
var
LStream: TStringStream;
LIrisInputData, LIrisOutputData: IList<TDoubleArray>;
LTreinInputData, LTreinOutputData: IList<TDoubleArray>;
LTestInputData, LTestOutputData: IList<TDoubleArray>;
LPredictedOutputData: IList<TDoubleArray>;
LPredictCost, LFitCost: Double;
begin
TThread.Queue(TThread.CurrentThread,
procedure
begin
Self.InitProcessIndicators;
end);
try
LStream := TStringStream.Create('', TEncoding.UTF8);
try
{ load pure data file }
LStream.LoadFromFile(AFileName);
{ transforma os dados originais para o formato compatível e ajustado }
TIrisDataConverter.New(LStream.DataString).Execute(LIrisInputData, LIrisOutputData);
{ faz o split dos dados para treino e teste }
TTestSplitter.New(LIrisInputData, LIrisOutputData, 0.3).ExecuteSplit(LTreinInputData, LTreinOutputData, LTestInputData, LTestOutputData);
{ cria o classificardor }
FMlp := TMLPClassifier.New(TSigmoid.New, [
TLayerInitInfo.New(TSigmoid.New, 10),
TLayerInitInfo.New(TSigmoid.New, 10)
],
0.5, 0.9, 2500);
ProgressBar.Max := FMlp.Epochs;
LFitCost := FMlp.Fit(LTreinInputData, LTreinOutputData).Cost;
LPredictCost := FMlp.Predict(LTestInputData, LPredictedOutputData).Cost;
TThread.Queue(TThread.CurrentThread,
procedure
begin
Self.BeginUpdateMemos([MemoData, MemoPredict, MemoTrain]);
try
Self
{ exibe os dados originais }
.ShowOriginalData(LStream.DataString)
{ exibe os dados convertidos }
.ShowConvertedData(LIrisInputData, LIrisOutputData)
{ exibe os dados de treino }
.ShowTreinData(LTreinInputData, LTreinOutputData)
{ exibe os dados de teste }
.ShowTestData(LTestInputData, LTestOutputData)
{ exibe os dados da classificação }
.ShowPredictedData(LTestInputData, LPredictedOutputData, LFitCost, LPredictCost)
{ exibe o resumo }
.ShowResume(FMlp, LTestOutputData, LPredictedOutputData);
finally
Self.EndUpdateMemos([MemoData, MemoPredict, MemoTrain]);
end;
end);
finally
LStream.Free;
end;
finally
TThread.Queue(TThread.CurrentThread,
procedure
begin
Self.ReleaseProcessIndicators;
end);
end;
end;
procedure TFormStart.FormCreate(Sender: TObject);
begin
ActivityIndicator.SendToBack;
FStylesManager := TFactoryVCLStyleManager.New(ItemStyles);
LineCost.Clear;
ProgressBar.Visible := False;
FIsRunning := False;
Self.ClearSeries;
end;
procedure TFormStart.FormDestroy(Sender: TObject);
begin
FMlp := nil;
FStylesManager := nil;
end;
procedure TFormStart.FormResize(Sender: TObject);
begin
ActivityIndicator.Top := (FormStart.Height - ActivityIndicator.Height) div 2;
ActivityIndicator.Left := (FormStart.Width - ActivityIndicator.Width) div 2;
end;
function TFormStart.ShowConvertedData(const AInputData, AOutputData: IList<TDoubleArray>): TFormStart;
begin
Result := Self;
MemoData.Lines.Add('');
MemoData.Lines.Add(Format('IRIS CONVERTED DATA: (%d)', [AInputData.Count]));
MemoData.Lines.Add('-------------------');
MemoData.Lines.Add('');
Self.ShowData(MemoData, AInputData, AOutputData);
end;
function TFormStart.ShowTestData(const AInputData, AOutputData: IList<TDoubleArray>): TFormStart;
begin
Result := Self;
MemoPredict.Lines.Add('');
MemoPredict.Lines.Add(Format('IRIS TEST DATA: (%d)', [AInputData.Count]));
MemoPredict.Lines.Add('--------------');
MemoPredict.Lines.Add('');
Self.ShowData(MemoPredict, AInputData, AOutputData);
end;
function TFormStart.ShowTreinData(const AInputData, AOutputData: IList<TDoubleArray>): TFormStart;
begin
Result := Self;
MemoTrain.Lines.Add('');
MemoTrain.Lines.Add(Format('IRIS TREIN DATA: (%d)', [AInputData.Count]));
MemoTrain.Lines.Add('---------------');
MemoTrain.Lines.Add('');
Self.ShowData(MemoTrain, AInputData, AOutputData);
end;
procedure TFormStart.TimerCostTimer(Sender: TObject);
begin
if not FIsRunning then
begin
FIsRunning := True;
try
var LEpochs := FMlp.EpochsCovered;
LineCost.AddXY(LEpochs, FMlp.Cost, '');
ProgressBar.Position := LEpochs;
ProgressBar.Update;
finally
FIsRunning := False;
end;
end;
end;
end.
|
unit USourcePPT;
interface
uses
System.Generics.Collections, USourceInfo,
PowerPoint_TLB;
type
TCachedPPT = class
private
FFileName: string;
FApp: PowerPointApplication;
FPresentation: PowerPointPresentation;
function GetPresentation: PowerPointPresentation;
public
property FileName: string read FFileName write FFileName;
property Presentation: PowerPointPresentation read GetPresentation;
destructor Destroy; override;
function SlidesAndShapes: TStringTree;
end;
TCachedPPTs = class(TObjectList<TCachedPPT>)
public
destructor Destroy; override;
function Get(strFileName: string): TCachedPPT;
function FindByName(strFileName: string): TCachedPPT;
function GetShape(ppt: TSourceInfo): PowerPoint_TLB.Shape;
function GetSlide(ppt: TSourceInfo): PowerPoint_TLB._Slide;
end;
function GetCachedPPTs: TCachedPPTs;
implementation
uses
Office_TLB, SysUtils,
USettings, UUtilsStrings, UfrmBrowseFTP;
var
gl_CachedPPTs: TCachedPPTs;
function GetCachedPPTs: TCachedPPTs;
begin
if not Assigned(gl_CachedPPTs) then begin
gl_CachedPPTs := TCachedPPTs.Create;
end;
Result := gl_CachedPPTs
end;
{ TCachedPPTs }
function TCachedPPTs.Get(strFileName: string): TCachedPPT;
begin
Result := FindByName(strFileName);
if Result = nil then begin
Result := TCachedPPT.Create;
Result.FileName := strFileName;
Add(Result);
end;
end;
destructor TCachedPPTs.Destroy;
begin
Clear;
inherited;
end;
function TCachedPPTs.FindByName(strFileName: string): TCachedPPT;
var
i: Integer;
begin
for i := 0 to Count -1 do begin
if Items[i].FileName = strFileName then begin
Result := Items[i];
Exit;
end;
end;
Result := nil;
end;
function TCachedPPTs.GetShape(ppt: TSourceInfo): PowerPoint_TLB.Shape;
var
slide: PowerPoint_TLB._Slide;
i: Integer;
begin
Result := nil;
if ppt.SourceType = sitPPT then begin
slide := GetSlide(ppt);
if Assigned(slide) then begin
for i := 1 to slide.Shapes.Count do begin
if slide.Shapes.Item(i).Name = ppt.ShapeName then begin
Result := slide.Shapes.Item(i);
Exit;
end;
end;
end;
end;
end;
function TCachedPPTs.GetSlide(ppt: TSourceInfo): PowerPoint_TLB._Slide;
var
cachedPPT: TCachedPPT;
i: Integer;
begin
Result := nil;
if ppt.SourceType = sitPPT then begin
cachedPPT := Get(ppt.FileName);
if Assigned(cachedPPT) then begin
for i := 1 to cachedPPT.Presentation.Slides.Count do begin
if cachedPPT.Presentation.Slides.Item(i).Name = ppt.SlideName then begin
Result := cachedPPT.Presentation.Slides.Item(i);
Exit;
end;
end;
end;
end;
end;
{ TCachedPPT }
destructor TCachedPPT.Destroy;
begin
FPresentation := nil;
FApp.Quit;
FApp := nil;
inherited;
end;
function TCachedPPT.GetPresentation: PowerPointPresentation;
var
strImplodedDir: string;
begin
if not Assigned(FApp) then begin
if not FileExists(FFileName) then begin
strImplodedDir := GetSettings.DirImplode(FFileName);
if strImplodedDir <> FFileName then begin
if pos('<ftp>', strImplodedDir) = 1 then begin
strImplodedDir := copy(strImplodedDir, 6, MaxInt);
strImplodedDir := StringReplace(strImplodedDir, '\', '/', [rfReplaceAll]);
CopyExternalFileToLocal(strImplodedDir)
end;
end;
end;
FApp := CoPowerPointApplication.Create;
FPresentation := FApp.Presentations.Open(FFileName, msoFalse, msoFalse, msoFalse);
end;
Result := FPresentation
end;
function TCachedPPT.SlidesAndShapes: TStringTree;
var
pres: PowerPointPresentation;
slide: PowerPoint_TLB._Slide;
i,j: integer;
slideNode: TStringTree;
begin
Result := TStringTree.Create;
pres := Presentation;
if Assigned(pres) then begin
for i := 1 to pres.Slides.Count do begin
slide := pres.Slides.Item(i);
slideNode := Result.Add(slide.Name);
for j := 1 to slide.Shapes.Count do begin
if slide.Shapes.Item(j).type_ = msoPicture then begin
slideNode.Add(slide.Shapes.Item(j).Name);
end;
end;
end;
end;
end;
initialization
gl_CachedPPTs := nil;
finalization
FreeAndNil(gl_CachedPPTs);
end.
|
unit AsmReader;
interface
uses
Windows, SysUtils, CvarDef;
function GetValidCodeLength(Addr: Pointer; MinCodeLength: LongInt = 5): LongInt;
type
TOPCode = record
Value: array[1..4] of Byte;
Size: Byte;
Name: PChar;
end;
const
Instructions: array[1..87] of TOPCode = (
(Value: ($50, $0, $0, $0); Size: 1; Name: 'push eax'),
(Value: ($51, $0, $0, $0); Size: 1; Name: 'push ecx'),
(Value: ($52, $0, $0, $0); Size: 1; Name: 'push edx'),
(Value: ($53, $0, $0, $0); Size: 1; Name: 'push ebx'),
(Value: ($55, $0, $0, $0); Size: 1; Name: 'push ebp'),
(Value: ($56, $0, $0, $0); Size: 1; Name: 'push esi'),
(Value: ($57, $0, $0, $0); Size: 1; Name: 'push edi'),
(Value: ($6A, $0, $0, $0); Size: 2; Name: 'push NUMBER'),
(Value: ($68, $0, $0, $0); Size: 5; Name: 'push offset VARIABLE'),
(Value: ($5B, $0, $0, $0); Size: 1; Name: 'pop ebx'),
(Value: ($5D, $0, $0, $0); Size: 1; Name: 'pop ebp'),
(Value: ($5E, $0, $0, $0); Size: 1; Name: 'pop esi'),
(Value: ($5F, $0, $0, $0); Size: 1; Name: 'pop edi'),
(Value: ($E8, $0, $0, $0); Size: 5; Name: 'call xxx'),
(Value: ($FF, $15, $0, $0); Size: 6; Name: 'call off_xxx'),
(Value: ($E9, $0, $0, $0); Size: 5; Name: 'jmp xxx'),
(Value: ($8B, $C1, $0, $0); Size: 2; Name: 'mov eax, ecx'),
(Value: ($B8, $0, $0, $0); Size: 5; Name: 'mov eax, NUMBER'), // 8B 00 = mov eax, [eax]
(Value: ($A1, $0, $0, $0); Size: 5; Name: 'mov eax, VARIABLE'),
(Value: ($8B, $EC, $0, $0); Size: 2; Name: 'mov ebp, esp'),
(Value: ($8B, $0D, $0, $0); Size: 6; Name: 'mov ecx, VARIABLE'),
(Value: ($8B, $CC, $0, $0); Size: 2; Name: 'mov ecx, esp'),
(Value: ($8B, $F2, $0, $0); Size: 2; Name: 'mov esi, edx'),
(Value: ($8B, $49, $0, $0); Size: 3; Name: 'mov ecx, [ecx+OFFSET]'),
(Value: ($8B, $45, $0, $0); Size: 3; Name: 'mov eax, [ebp+OFFSET]'),
(Value: ($8B, $44, $24, $0); Size: 4; Name: 'mov eax, [esp+OFFSET]'),
(Value: ($8B, $54, $24, $0); Size: 4; Name: 'mov edx, [esp+OFFSET]'),
(Value: ($8B, $4C, $24, $0); Size: 4; Name: 'mov ecx, [esp+OFFSET]'),
(Value: ($8B, $6C, $24, $0); Size: 4; Name: 'mov ebp, [esp+OFFSET]'),
(Value: ($8B, $4D, $0, $0); Size: 3; Name: 'mov ecx, [ebp+OFFSET]'),
(Value: ($8B, $75, $0, $0); Size: 3; Name: 'mov esi, [ebp+OFFSET]'),
(Value: ($8B, $74, $24, $0); Size: 4; Name: 'mov esi, [esp+4+OFFSET]'),
(Value: ($8B, $F1, $0, $0); Size: 2; Name: 'mov esi, ecx'),
(Value: ($8B, $55, $0, $0); Size: 3; Name: 'mov edx, [ebp+OFFSET]'),
(Value: ($C7, $05, $0, $0); Size: 10; Name: 'mov dword ptr VARIABLE+4, NUMBER'),
(Value: ($89, $33, $0, $0); Size: 2; Name: 'mov [ebx], esi'),
(Value: ($89, $1A, $0, $0); Size: 2; Name: 'mov [edx], ebx'),
(Value: ($B9, $0, $0, $0); Size: 5; Name: 'mov ecx, NUMBER'),
(Value: ($BE, $0, $0, $0); Size: 5; Name: 'mov esi, offset VARIABLE'),
(Value: ($89, $13, $0, $0); Size: 2; Name: 'mov [ebx], ebx'),
(Value: ($8A, $08, $0, $0); Size: 2; Name: 'mov cl, [eax]'),
(Value: ($8B, $EE, $0, $0); Size: 2; Name: 'mov ebp, esi'),
(Value: ($8B, $7C, $24, $0); Size: 4; Name: 'mov edi, [esp+OFFSET]'),
(Value: ($8B, $06, $0, $0); Size: 2; Name: 'mov eax, [esi]'),
(Value: ($8B, $FF, $0, $0); Size: 2; Name: 'mov edi, edi'),
(Value: ($8B, $4C, $24, $0); Size: 4; Name: 'mov ecx, [esp+OFFSET]'),
(Value: ($83, $E4, $0, $0); Size: 3; Name: 'and esp, NUMBER'),
(Value: ($83, $C4, $0, $0); Size: 3; Name: 'add esp, NUMBER'),
(Value: ($83, $EC, $0, $0); Size: 3; Name: 'sub esp, NUMBER'),
(Value: ($81, $EC, $0, $0); Size: 6; Name: 'sub esp, NUMBER'),
(Value: ($0B, $C5, $0, $0); Size: 2; Name: 'or eax, ebp'),
(Value: ($83, $C8, $0, $0); Size: 3; Name: 'or eax, NUMBER'),
(Value: ($33, $0, $0, $0); Size: 2; Name: 'xor xxx, xxx'),
(Value: ($80, $38, $0, $0); Size: 3; Name: 'cmp byte ptr [eax], NUMBER'),
(Value: ($80, $3E, $0, $0); Size: 3; Name: 'cmp byte ptr [esi], NUMBER'),
(Value: ($3C, $0, $0, $0); Size: 2; Name: 'cmp al, NUMBER'),
(Value: ($83, $FA, $0, $0); Size: 2; Name: 'cmp edx, NUMBER'),
(Value: ($83, $F8, $0, $0); Size: 3; Name: 'cmp eax, NUMBER'),
(Value: ($83, $3D, $C0, $0); Size: 7; Name: 'cmp VARIABLE, NUMBER'),
(Value: ($3A, $D3, $0, $0); Size: 2; Name: 'cmp dl, bl'),
(Value: ($3B, $CE, $0, $0); Size: 2; Name: 'cmp ecx, esi'),
(Value: ($3D, $0, $0, $0); Size: 5; Name: 'cmp eax, NUMBER'),
(Value: ($3B, $CD, $0, $0); Size: 3; Name: 'cmp ecx, ebp'),
(Value: ($39, $68, $0, $0); Size: 3; Name: 'cmp [eax+OFFSET], ebp'),
(Value: ($3B, $C6, $0, $0); Size: 2; Name: 'cmp eax, esi'),
(Value: ($D3, $E5, $0, $0); Size: 2; Name: 'shl ebp, cl'),
(Value: ($D3, $EF, $0, $0); Size: 2; Name: 'shr edi, cl'),
(Value: ($8D, $44, $24, $0); Size: 4; Name: 'lea eax, [esp+OFFSET]'),
(Value: ($8D, $54, $24, $0); Size: 4; Name: 'lea edx, [esp+OFFSET]'),
(Value: ($8D, $4C, $24, $0); Size: 4; Name: 'lea ecx, [esp+OFFSET]'),
(Value: ($8D, $45, $0, $0); Size: 3; Name: 'lea eax, [ebp+OFFSET]'),
(Value: ($8D, $4D, $0, $0); Size: 3; Name: 'lea ecx, [ebp+OFFSET]'),
(Value: ($8D, $55, $0, $0); Size: 3; Name: 'lea edx, [ebp+OFFSET]'),
(Value: ($D9, $05, $0, $0); Size: 6; Name: 'fld VARIABLE'),
(Value: ($D9, $41, $0, $0); Size: 3; Name: 'fld dword ptr [ecx+OFFSET]'),
(Value: ($D9, $44, $24, $0); Size: 4; Name: 'fld [esp+OFFSET]'),
(Value: ($D8, $48, $0, $0); Size: 3; Name: 'fmul dword ptr [eax+OFFSET]'),
(Value: ($D8, $08, $0, $0); Size: 2; Name: 'fmul dword ptr [eax]'),
(Value: ($DC, $0D, $0, $0); Size: 6; Name: 'fmul ds:VARIABLE'),
(Value: ($D9, $19, $0, $0); Size: 2; Name: 'fstp dword ptr [ecx]'),
(Value: ($D9, $59, $0, $0); Size: 3; Name: 'fstp dword ptr [ecx+OFFSET]'),
(Value: ($D9, $5C, $24, $0); Size: 4; Name: 'fstp [esp+OFFSET+OFFSET]'),
(Value: ($D8, $1D, $0, $0); Size: 6; Name: 'fcomp ds:VARIABLE'),
(Value: ($DF, $E0, $0, $0); Size: 2; Name: 'fnstsw ax'),
(Value: ($C2, $0, $0, $0); Size: 3; Name: 'retn xxx'),
(Value: ($C3, $0, $0, $0); Size: 1; Name: 'retn'),
(Value: ($90, $0, $0, $0); Size: 1; Name: 'nop')
);
implementation
procedure RaiseError(Msg: PChar); overload;
begin
MessageBox(0, Msg, 'AsmReader - Fatal Error', MB_OK or MB_ICONERROR or MB_SYSTEMMODAL);
Halt(1);
end;
procedure RaiseError(const Msg: String); overload;
begin
RaiseError(PChar(Msg));
end;
function GetValidCodeLength(Addr: Pointer; MinCodeLength: LongInt = 5): LongInt;
var
L: LongInt;
I: LongInt;
B: Byte;
DebugStr: String;
begin
Result := 0;
L := Low(Instructions);
B := PByte(Addr)^;
while L < High(Instructions) + 1 do
begin
if B = Instructions[L].Value[1] then
for I := 1 to 3 do
begin
if Instructions[L].Value[I + 1] <> $0 then
begin
if PByte(LongInt(Addr) + I)^ <> Instructions[L].Value[I + 1] then
Break
end
else
begin
Inc(Result, Instructions[L].Size);
if Result >= MinCodeLength then
Exit
else
begin
Inc(LongWord(Addr), Instructions[L].Size);
B := PByte(Addr)^;
L := -1;
end;
end;
end;
Inc(L);
end;
DebugStr := 'Unreadable code for AsmReader has been found!' + #10#10 + 'Dump:' + #10;
for I := 0 to 7 do
DebugStr := DebugStr + IntToHex(PByte(LongInt(Addr) + I)^, 2) + ' ';
DebugStr := DebugStr + #10 + 'Address (ModRel): $' + IntToHex(LongWord(Addr), 8);
DebugStr := DebugStr + #10 + 'Address (SelRel): $' + IntToHex(LongWord(Addr) - LongWord(PWGame.BaseStart), 8);
RaiseError(DebugStr);
end;
end.
|
{------------------------------------
功能说明:系统日志接口
创建日期:2008/11/20
作者:wzw
版权:wzw
-------------------------------------}
unit LogIntf;
{$weakpackageunit on}
interface
uses
SysUtils;
type
ILog = interface
['{472FD4AD-F589-4D4D-9051-A20D37B7E236}']
procedure WriteLog(const Str: string);
procedure WriteLogFmt(const Str: string; const Args: array of const);
function GetLogFileName: string;
end;
implementation
end.
|
unit DataSort;
interface
uses
System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ActnList,
JvExStdCtrls, JvListBox, ValEdit, JvStringHolder, Menus, ComCtrls, ToolWin, PlatformDefaultStyleActnCtrls, ActnMan,
Vcl.ImgList, BCControls.Edit, BCControls.ImageList, BCControls.ToolBar, Vcl.ExtCtrls, BCDialogs.Dlg, System.Actions;
type
TDataSortDialog = class(TDialog)
ActionList: TActionList;
ActionManager: TActionManager;
AscRadioButton: TRadioButton;
Button1: TButton;
CancelButton: TButton;
ClearSortAction: TAction;
ClientPanel: TPanel;
ColumnClickAction: TAction;
ColumnListBox: TJvListBox;
DescRadioButton: TRadioButton;
DownAction: TAction;
FirstRadioButton: TRadioButton;
ImageList: TBCImageList;
JvToolBar1: TBCToolBar;
Label1: TLabel;
LastRadioButton: TRadioButton;
NullsGroupBox: TGroupBox;
OKAction: TAction;
OKButton: TButton;
OrderGroupBox: TGroupBox;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
Panel5: TPanel;
RemoveAction: TAction;
Separator1Panel: TPanel;
SortListBox: TJvListBox;
SortMultiStringHolder: TJvMultiStringHolder;
SortNameEdit: TBCEdit;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton6: TToolButton;
UpAction: TAction;
procedure ClearSortActionExecute(Sender: TObject);
procedure ColumnClickActionExecute(Sender: TObject);
procedure DownActionExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure OKActionExecute(Sender: TObject);
procedure RemoveActionExecute(Sender: TObject);
procedure SortListBoxClick(Sender: TObject);
procedure SortNameEditChange(Sender: TObject);
procedure SortNameEditKeyPress(Sender: TObject; var Key: Char);
procedure UpActionExecute(Sender: TObject);
private
{ Private declarations }
FObjectName: string;
FSchemaParam: string;
function GetDataSort: WideString;
procedure SetFields;
public
{ Public declarations }
ValuesList: TValueListEditor; { Save filter values }
function GetCurrentDataSort(ObjectName: string; SchemaParam: string): string;
function GetCurrentSortName(ObjectName: string; SchemaParam: string): string;
function Open(ObjectName: string; SchemaParam: string; Columns: TStrings{; DataSort: WideString}): Boolean;
procedure SetCurrentDataSort(ObjectName: string; SchemaParam: string; Name: string);
property DataSort: WideString read GetDataSort;
end;
function DataSortDialog: TDataSortDialog;
implementation
{$R *.dfm}
uses
BCCommon.StyleUtils, BCCommon.StringUtils;
var
FDataSortDialog: TDataSortDialog;
function DataSortDialog: TDataSortDialog;
begin
if not Assigned(FDataSortDialog) then
Application.CreateForm(TDataSortDialog, FDataSortDialog);
Result := FDataSortDialog;
SetStyledFormSize(Result);
end;
procedure TDataSortDialog.SetFields;
var
i, Selected: Integer;
begin
OKAction.Enabled := (Trim(SortNameEdit.Text) <> '') and
(Trim(SortListBox.Items.Text) <> '');
Selected := -1;
for i := 0 to SortListBox.Count - 1 do
if SortListBox.Selected[i] then
Selected := i;
UpAction.Enabled := (Selected <> -1) and (Selected > 0);
DownAction.Enabled := (Selected <> -1) and (Selected < SortListBox.Count - 1);
RemoveAction.Enabled := SortListBox.Count <> 0;
end;
procedure TDataSortDialog.ClearSortActionExecute(Sender: TObject);
begin
SortListBox.Clear;
end;
procedure TDataSortDialog.ColumnClickActionExecute(Sender: TObject);
var
i: Integer;
Options: string;
begin
if AscRadioButton.Checked then
Options := ' ASC'
else
Options := ' DESC';
if FirstRadioButton.Checked then
Options := Options + ' NULLS FIRST'
else
Options := Options + ' NULLS LAST';
for i := 0 to ColumnListBox.Count - 1 do
if ColumnListBox.Selected[i] then
SortListBox.Items.Add(Trim(ColumnListBox.Items.Strings[i]) + Options);
SortListBox.Selected[SortListBox.Count - 1] := True;
SortListBox.SetFocus;
SetFields;
end;
procedure TDataSortDialog.SortListBoxClick(Sender: TObject);
begin
SetFields;
end;
procedure TDataSortDialog.SortNameEditChange(Sender: TObject);
begin
SetFields;
end;
procedure TDataSortDialog.SortNameEditKeyPress(Sender: TObject; var Key: Char);
begin
if not (CharInSet(Key, ['a'..'z', 'ä', 'Ä', 'å', 'Å', 'ö', 'Ö', 'A'..'Z', '0'..'9', #8, ' ', '%'])) then
Key := #0;
end;
procedure TDataSortDialog.UpActionExecute(Sender: TObject);
var
i: Integer;
begin
for i := 0 to SortListBox.Count - 1 do
if SortListBox.Selected[i] then
begin
SortListBox.Items.Exchange(i, i - 1);
SortListBox.Selected[i - 1] := True;
Break;
end;
SetFields;
end;
procedure TDataSortDialog.DownActionExecute(Sender: TObject);
var
i: Integer;
begin
for i := 0 to SortListBox.Count - 1 do
if SortListBox.Selected[i] then
begin
SortListBox.Items.Exchange(i, i + 1);
SortListBox.Selected[i + 1] := True;
Break;
end;
SetFields;
end;
procedure TDataSortDialog.FormCreate(Sender: TObject);
begin
ValuesList := TValueListEditor.Create(nil);
ValuesList.Strings.Clear;
end;
procedure TDataSortDialog.SetCurrentDataSort(ObjectName: string; SchemaParam: string; Name: string);
var
i: Integer;
Found: Boolean;
KeyValue: string;
begin
{ Get Data Sort }
KeyValue := EncryptString(ObjectName + '@' + SchemaParam + ':' + Name);
for i := 0 to ValuesList.RowCount - 1 do
if KeyValue = ValuesList.Keys[i] then
begin
SortNameEdit.Text := Name;
SortListBox.Items.Text := DecryptString(ValuesList.Values[ValuesList.Keys[i]]);
Break;
end;
{ Update Current Data Sort }
Found := False;
KeyValue := EncryptString(ObjectName + '@' + SchemaParam + ':CURRENT');
for i := 0 to ValuesList.RowCount - 1 do
if KeyValue = ValuesList.Keys[i] then
begin
Found := True;
//ValuesList.Keys[i] := ObjectName + '@' + SchemaParam + ':CURRENT' + ':$' + Name;
ValuesList.Values[ValuesList.Keys[i]] := EncryptString(Name);
Break;
end;
{ insert if not found }
if not Found then
ValuesList.InsertRow(KeyValue, EncryptString(Name), True);
end;
function TDataSortDialog.GetCurrentDataSort(ObjectName: string; SchemaParam: string): string;
var
i: Integer;
KeyValue, SortName: string;
begin
Result := '';
SortName := GetCurrentSortName(ObjectName, SchemaParam);
KeyValue := EncryptString(ObjectName + '@' + SchemaParam + ':' + SortName);
for i := 0 to ValuesList.RowCount - 1 do
if KeyValue = ValuesList.Keys[i] then
begin
Result := DecryptString(ValuesList.Values[ValuesList.Keys[i]]);
Result := StringReplace(Result, 'NULLS FIRST,', 'NULLS FIRST', [rfReplaceAll]);
Result := StringReplace(Result, 'NULLS FIRST', 'NULLS FIRST, ', [rfReplaceAll]);
Result := StringReplace(Result, 'NULLS LAST,', 'NULLS LAST', [rfReplaceAll]);
Result := StringReplace(Result, 'NULLS LAST', 'NULLS LAST, ', [rfReplaceAll]);
Result := Trim(Result);
Result := Copy(Result, 0, Length(Result) - 1); // remove last spot
Break;
end;
end;
function TDataSortDialog.GetCurrentSortName(ObjectName: string; SchemaParam: string): string;
var
i: Integer;
KeyValue: string;
begin
Result := '';
KeyValue := EncryptString(ObjectName + '@' + SchemaParam + ':CURRENT');
for i := 0 to ValuesList.RowCount - 1 do
if KeyValue = ValuesList.Keys[i] then
begin
Result := DecryptString(ValuesList.Values[ValuesList.Keys[i]]);
Break;
end;
end;
procedure TDataSortDialog.FormDestroy(Sender: TObject);
begin
ValuesList.Free;
FDataSortDialog := nil;
end;
// SortMultiStringHolder name: Object Name@S@SchemaParam
// object name@F@FilterName
procedure TDataSortDialog.OKActionExecute(Sender: TObject);
var
i: Integer;
KeyValue, SortName: string;
Found: Boolean;
begin
{ Update Current Data Sort }
Found := False;
KeyValue := EncryptString(FObjectName + '@' + FSchemaParam + ':CURRENT');
for i := 0 to ValuesList.RowCount - 1 do
if KeyValue = ValuesList.Keys[i] then
begin
Found := True;
//ValuesList.Keys[i] := FObjectName + '@' + FSchemaParam + ':CURRENT' + ':$' + SortNameEdit.Text;
ValuesList.Values[ValuesList.Keys[i]] := EncryptString(SortNameEdit.Text);
Break;
end;
{ insert if not found }
if not Found then
ValuesList.InsertRow(KeyValue, EncryptString(SortNameEdit.Text), True);
SortName := EncryptString(FObjectName + '@' + FSchemaParam + ':' + SortNameEdit.Text);
if not ValuesList.FindRow(SortName, i) then
ValuesList.InsertRow(SortName, EncryptString(DataSort), True)
else
ValuesList.Values[ValuesList.Keys[i]] := EncryptString(DataSort);
ModalResult := mrOk;
end;
function TDataSortDialog.Open(ObjectName: string; SchemaParam: string; Columns: TStrings{; DataSort: WideString}): Boolean;
var
Rslt: Integer;
begin
ColumnListBox.Items := Columns;
SortListBox.Items.Text := '';
SortNameEdit.Text := GetCurrentSortName(ObjectName, SchemaParam);
if SortNameEdit.Text = '' then
SortNameEdit.Text := 'Unnamed';
if Trim(SortNameEdit.Text) <> '' then
SortListBox.Items.Text := GetCurrentDataSort(ObjectName, SchemaParam);
FObjectName := ObjectName;
FSchemaParam := SchemaParam;
SetFields;
Rslt := ShowModal;
Result := Rslt = mrOk;
end;
procedure TDataSortDialog.RemoveActionExecute(Sender: TObject);
var
i: Integer;
begin
for i := 0 to SortListBox.Count - 1 do
if SortListBox.Selected[i] then
begin
SortListBox.Items.Delete(i);
Break;
end;
SetFields;
end;
function TDataSortDialog.GetDataSort: WideString;
begin
Result := SortListBox.Items.Text;
end;
end.
|
unit RT_Updater;
interface
uses
Windows, Classes, SysUtils, Contnrs, JvUIB, JvUIBLib, PxThread;
const
SLEEP_INTERVAL = 2000;
type
TStringsQueue = class (TObject)
private
FStrings: TStrings;
FLock: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
function Empty: Boolean;
function Pop: String;
procedure Push(Value: String);
end;
TUpdateListener = class (TObject)
private
FTables: TStrings;
FUpdatedTables: TStringsQueue;
FLock: TRTLCriticalSection;
function GetTables: TStrings;
procedure GatherTables(TablesArray: array of String);
public
constructor Create(Tables: array of String);
destructor Destroy; override;
procedure Lock;
procedure Unlock;
property Tables: TStrings read GetTables;
property UpdatedTables: TStringsQueue read FUpdatedTables;
end;
TUpdateListenerList = class (TObjectList)
private
function GetItem(Index: Integer): TUpdateListener;
public
property Items[Index: Integer]: TUpdateListener read GetItem; default;
end;
TRTUpdaterTable = class (TObject)
private
FName: String;
FLastUpdate: TDateTime;
public
constructor Create(AName: String);
property Name: String read FName;
property LastUpdate: TDateTime read FLastUpdate write FLastUpdate;
end;
TRTUpdaterTableList = class (TObjectList)
private
function GetItem(Index: Integer): TRTUpdaterTable;
function GetByName(Name: String): TRTUpdaterTable;
public
property Items[Index: Integer]: TRTUpdaterTable read GetItem; default;
property ByName[Name: String]: TRTUpdaterTable read GetByName;
end;
TRTUpdater = class (TPxThread)
private
FRegisterCS: TRTLCriticalSection;
FListeners: TUpdateListenerList;
FQuery: TJvUIBQuery;
FUpdates: TRTUpdaterTableList;
class procedure Initialize;
class procedure Shutdown;
protected
procedure GatherTables(Tables: TStrings);
procedure NotifyTablechanges(TableName: String);
procedure CheckForModifications;
procedure Execute; override;
property Listeners: TUpdateListenerList read FListeners;
property Query: TJvUIBQuery read FQuery;
property Updates: TRTUpdaterTableList read FUpdates;
public
class function Instance: TRTUpdater;
constructor Create;
destructor Destroy; override;
procedure RegisterListener(Listener: TUpdateListener);
procedure UnregisterListener(Listener: TUpdateListener);
end;
implementation
uses
RT_SQL;
{ TStringsQueue }
{ Private declarations }
{ Public declarations }
constructor TStringsQueue.Create;
begin
inherited Create;
FStrings := TStringList.Create;
InitializeCriticalSection(FLock);
end;
destructor TStringsQueue.Destroy;
begin
FreeAndNil(FStrings);
DeleteCriticalSection(FLock);
inherited Destroy;
end;
function TStringsQueue.Empty: Boolean;
begin
Result := FStrings.Count = 0;
end;
function TStringsQueue.Pop: String;
begin
EnterCriticalSection(FLock);
try
Result := FStrings[0];
FStrings.Delete(0);
finally
LeaveCriticalSection(FLock);
end;
end;
procedure TStringsQueue.Push(Value: String);
begin
EnterCriticalSection(FLock);
try
if FStrings.IndexOf(Value) = -1 then
FStrings.Append(Value);
finally
LeaveCriticalSection(FLock);
end;
end;
{ TUpdateListenerList }
{ Private declarations }
function TUpdateListenerList.GetItem(Index: Integer): TUpdateListener;
begin
Result := TObject(Get(Index)) as TUpdateListener;
end;
{ TUpdateListener }
{ Private declarations }
function TUpdateListener.GetTables: TStrings;
begin
Result := FTables;
end;
procedure TUpdateListener.GatherTables(TablesArray: array of String);
var
I: Integer;
begin
for I := Low(TablesArray) to High(TablesArray) do
begin
TablesArray[I] := UpperCase(TablesArray[I]);
if Tables.IndexOf(TablesArray[I]) = -1 then
Tables.Add(TablesArray[I]);
end;
end;
{ Public declarations }
constructor TUpdateListener.Create(Tables: array of String);
begin
inherited Create;
InitializeCriticalSection(FLock);
FTables := TStringList.Create;
GatherTables(Tables);
FUpdatedTables := TStringsQueue.Create;
end;
destructor TUpdateListener.Destroy;
begin
FreeAndNil(FUpdatedTables);
FreeAndNil(FTables);
DeleteCriticalSection(FLock);
inherited Destroy;
end;
procedure TUpdateListener.Lock;
begin
EnterCriticalSection(FLock);
end;
procedure TUpdateListener.Unlock;
begin
LeaveCriticalSection(FLock);
end;
{ TRTUpdaterTable }
{ Private declarations }
{ Public declarations }
constructor TRTUpdaterTable.Create(AName: String);
begin
inherited Create;
FName := AName;
FLastUpdate := Now;
end;
{ TRTUpdaterTableList }
{ Private declarations }
function TRTUpdaterTableList.GetItem(Index: Integer): TRTUpdaterTable;
begin
Result := TObject(Get(Index)) as TRTUpdaterTable;
end;
function TRTUpdaterTableList.GetByName(Name: String): TRTUpdaterTable;
var
I: Integer;
begin
Result := nil;
for I := 0 to Count - 1 do
if AnsiSameText(Items[I].Name, Name) then
begin
Result := Items[I];
Break;
end;
end;
{ TRTUpdater }
var
_Instance: TRTUpdater = nil;
{ Private declarations }
class procedure TRTUpdater.Initialize;
begin
_Instance := TRTUpdater.Create;
end;
class procedure TRTUpdater.Shutdown;
begin
_Instance.Terminate;
FreeAndNil(_Instance);
end;
{ Protected declarations }
procedure TRTUpdater.GatherTables(Tables: TStrings);
var
I, J: Integer;
begin
Tables.Clear;
for I := 0 to Listeners.Count - 1 do
for J := 0 to Listeners[I].Tables.Count - 1 do
if Tables.IndexOf(Listeners[I].Tables[J]) = -1 then
Tables.Add(Listeners[I].Tables[J]);
end;
procedure TRTUpdater.NotifyTablechanges(TableName: String);
var
I: Integer;
begin
for I := 0 to Listeners.Count - 1 do
if Listeners[I].Tables.IndexOf(TableName) <> -1 then
begin
Listeners[I].Lock;
try
Listeners[I].UpdatedTables.Push(TableName);
finally
Listeners[I].Unlock;
end;
end;
end;
procedure TRTUpdater.CheckForModifications;
var
I: Integer;
Tables: TStrings;
Table: TRTUpdaterTable;
begin
Tables := TStringList.Create;
try
GatherTables(Tables);
for I := 0 to Tables.Count - 1 do
begin
Table := Updates.ByName[Tables[I]];
if not Assigned(Table) then
begin
Table := TRTUpdaterTable.Create(Tables[I]);
Updates.Add(Table);
end;
Query.Transaction.RollBack;
Query.SQL.Text := Format('SELECT DATA FROM UPDATES WHERE TABLENAME=%s AND DATA>%s', [
QuotedStr(Tables[I]),
QuotedStr(FormatDateTime('YYYY-MM-DD HH:NN:SS.ZZZ', Table.LastUpdate))
]);
Query.Open;
if not Query.Eof then
begin
Query.Last;
Table.LastUpdate := Query.Fields.AsDateTime[0];
NotifyTablechanges(Table.Name);
end;
Query.Close(etmRollback);
end
finally
Tables.Free;
end;
end;
procedure TRTUpdater.Execute;
begin
while not Terminated do
begin
Sleep(SLEEP_INTERVAL);
if not Terminated then
CheckForModifications;
end;
end;
{ Public declarations }
class function TRTUpdater.Instance: TRTUpdater;
begin
Result := _Instance;
end;
constructor TRTUpdater.Create;
begin
inherited Create(True);
InitializeCriticalSection(FRegisterCS);
FListeners := TUpdateListenerList.Create(True);
FQuery := TSQL.Instance.CreateQuery;
FUpdates := TRTUpdaterTableList.Create(True);
Resume;
end;
destructor TRTUpdater.Destroy;
begin
FreeAndNil(FUpdates);
FreeAndNil(FQuery);
FreeAndNil(FListeners);
DeleteCriticalSection(FRegisterCS);
inherited Destroy;
end;
procedure TRTUpdater.RegisterListener(Listener: TUpdateListener);
begin
EnterCriticalSection(FRegisterCS);
try
Assert(Listeners.IndexOf(Listener) = -1, 'Error: this listener has already been registered');
Listeners.Add(Listener);
finally
LeaveCriticalSection(FRegisterCS);
end;
end;
procedure TRTUpdater.UnregisterListener(Listener: TUpdateListener);
begin
EnterCriticalSection(FRegisterCS);
try
Assert(Listeners.IndexOf(Listener) <> -1, 'Error: this listener has not been registered');
Listeners.Remove(Listener);
finally
LeaveCriticalSection(FRegisterCS);
end;
end;
initialization
TRTUpdater.Initialize;
finalization
TRTUpdater.Shutdown;
end.
|
unit Infotec.Utils;
interface
uses System.SysUtils, System.JSON, System.Generics.Collections, GBJSON.Interfaces, GBJSON.Helper,
System.Classes;
type
TInfotecUtils = class
class function ObjectToJson(pObject: TObject): String;
class function ObjectToJsonObject(pObject: TObject): TJSONValue;
class function ObjectToJsonArray<T: class, constructor>(pObject: TObjectList<T>): TJSONArray;
class function RemoverEspasDuplas(const psValue: string): string;
class function JsonToObject<T: class, constructor>(const psJSon: string): T;
end;
implementation
{ TInfotecUtils }
class function TInfotecUtils.JsonToObject<T>(const psJSon: string): T;
begin
Result := TGBJSONDefault.Serializer<T>.JsonStringToObject(psJSon);
end;
class function TInfotecUtils.ObjectToJson(pObject: TObject): String;
begin
Result := pObject.ToJSONString(true);
end;
class function TInfotecUtils.ObjectToJsonArray<T>(pObject: TObjectList<T>): TJSONArray;
begin
Result := TGBJSONDefault.Deserializer<T>.ListToJSONArray(pObject);
end;
class function TInfotecUtils.ObjectToJsonObject(pObject: TObject): TJSONValue;
{$IFDEF DEBUG}
var
oJson: TStringList;
{$ENDIF}
begin
Result := pObject.ToJSONObject;
if not Assigned(Result) then
begin
{$IFDEF DEBUG}
oJson:= TStringList.Create;
try
oJson.Text := pObject.ToJSONString();
oJson.SaveToFile('JsonErro.Json');
finally
FreeAndNil(oJson);
end;
{$ENDIF}
Writeln('Erro: Result = nil: ' + ObjectToJson(pObject));
end;
end;
class function TInfotecUtils.RemoverEspasDuplas(const psValue: string): string;
begin
Result := StringReplace(psValue, '"', ' ', [rfReplaceAll]);
end;
end.
|
unit UModel;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ToolWin, ExtCtrls, StdCtrls, ImgList, ActnList, tc;
type
TFModel = class(TForm)
Panel1: TPanel;
Splitter1: TSplitter;
Panel2: TPanel;
ToolBar1: TToolBar;
Panel3: TPanel;
Panel4: TPanel;
Label1: TLabel;
Label2: TLabel;
TreeView1: TTreeView;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
ToolButton7: TToolButton;
ModelParamsActions: TActionList;
AAddElement: TAction;
ADeleteElement: TAction;
AApply: TAction;
AllImages: TImageList;
OpenD: TOpenDialog;
SaveD: TSaveDialog;
ASave: TAction;
ALoad: TAction;
Status: TStatusBar;
TreeImages: TImageList;
ToolButton8: TToolButton;
APrint: TAction;
ToolButton9: TToolButton;
NoObjectLabel: TLabel;
AClear: TAction;
ToolButton10: TToolButton;
procedure AApplyExecute(Sender: TObject);
procedure ALoadExecute(Sender: TObject);
procedure ASaveExecute(Sender: TObject);
procedure TreeView1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure AAddElementExecute(Sender: TObject);
procedure TreeView1Editing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
procedure ADeleteElementExecute(Sender: TObject);
procedure TreeView1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure TreeView1Change(Sender: TObject; Node: TTreeNode);
procedure TreeView1Edited(Sender: TObject; Node: TTreeNode;
var S: String);
procedure TreeView1Changing(Sender: TObject; Node: TTreeNode;
var AllowChange: Boolean);
procedure FormActivate(Sender: TObject);
procedure TreeView1Expanding(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean);
procedure APrintExecute(Sender: TObject);
procedure AClearExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
Model : TModel;
ModelCopy : TModel;
ModelName : string;
Modified : boolean;
procedure InitTreeView;
procedure SaveToModel;
procedure LoadFromModel;
procedure Ref;
end;
var
FModel: TFModel;
implementation
uses UAllTime, UBunker, UMaterial, ULine, UModelReport;
{$R *.DFM}
procedure TFModel.AApplyExecute(Sender: TObject);
begin
SaveToModel;
ModalResult := mrOK;
end;
procedure TFModel.ALoadExecute(Sender: TObject);
begin
if not OpenD.Execute then exit;
if visible then TreeView1.FullCollapse;
if visible then TreeView1Change(TreeView1,TreeView1.Selected);
Model.LoadFromFile (OPenD.FileName);
Modified := false;
if visible then LoadFromModel;
ModelName := ExtractFileName(OpenD.FileName);
MessageDlg(LoadSuccesfully, mtInformation, [mbOk], 0);
end;
procedure TFModel.ASaveExecute(Sender: TObject);
begin
if not SaveD.Execute then exit;
SaveToModel;
TreeView1.FullCollapse;
Model.SaveToFile (SaveD.FileName);
Modified := false;
ModelName := ExtractFileName(SaveD.FileName);
MessageDlg(SaveSuccesfully, mtInformation, [mbOk], 0);
end;
procedure TFModel.TreeView1Click(Sender: TObject);
begin
TreeView1Change(Sender, TreeView1.Selected);
end;
procedure TFModel.FormCreate(Sender: TObject);
begin
InitTreeView;
Model := TModel.Create;
ModelCopy := TModel.Create;
ModelName := NO_NAME;
Modified := false;
FAllTime := TFAllTime.CreateEmbedded(self, Panel2);
FAllTime.SetBounds (10, 30, FAllTime.width, FAllTime.Height);
FBunker := TFBunker.CreateEmbedded(self, Panel2);
FBunker.SetBounds(10, 30, FBunker.width, FBunker.Height);
FMaterial := TFMaterial.CreateEmbedded(self, Panel2);
FMaterial.SetBounds(10, 30, FMaterial.width, FMaterial.Height);
FLine := TFLine.CreateEmbedded (self, Panel2);
FLine.SetBounds(10, 30, FLine.width, FLine.Height);
end;
procedure TFModel.InitTreeView;
var
Data : ^TNodeData;
ModelFolder : TTreeNode;
BunkerFolder : TTreeNode;
GivenFolder : TTreeNode;
CommFolder : TTreeNode;
LineFolder : TTreeNode;
MaterialFolder : TTreeNode;
begin
with TreeView1 do
begin
repeat
Items[0].Delete;
until items.count = 0;
Data := nil;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntModelFolder;
Data^.LinkedObject := Model;
ModelFolder := Items.AddObjectFirst(nil, 'Модель', Data);
Data := nil;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntBunkerFolder;
Data^.LinkedObject := nil;
BunkerFolder := Items.AddChildObject(ModelFolder, 'Бункеры', Data);
BunkerFolder.ImageIndex := 2;
BunkerFolder.SelectedIndex := 2;
Data := nil;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntCommFolder;
Data^.LinkedObject := nil;
CommFolder := Items.AddChildObject(BunkerFolder, 'Коммерческое', Data);
CommFolder.ImageIndex := 2;
CommFolder.SelectedIndex := 2;
Data := nil;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntGivenFolder;
Data^.LinkedObject := nil;
GivenFolder := Items.AddChildObject(BunkerFolder, 'Давальческое', Data);
GivenFolder.ImageIndex := 2;
GivenFolder.SelectedIndex := 2;
Data := nil;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntLineFolder;
Data^.LinkedObject := nil;
LineFolder := Items.AddChildObject(ModelFolder, 'Линии обработки', Data);
LineFolder.ImageIndex := 2;
LineFolder.SelectedIndex := 2;
Data := nil;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntMaterialFolder;
Data^.LinkedObject := nil;
MaterialFolder := Items.AddChildObject(ModelFolder, 'Типы сырья', Data);
MaterialFolder.ImageIndex := 2;
MaterialFolder.SelectedIndex := 2;
Data := nil;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntAllTime;
Data^.LinkedObject := nil;
MaterialFolder := Items.AddChildObject(ModelFolder, 'Время моделирования', Data);
MaterialFolder.ImageIndex := 3;
MaterialFolder.SelectedIndex := 3;
end;
AAddElement.Enabled := false;
ADeleteElement.Enabled := false;
end;
procedure TFModel.AAddElementExecute(Sender: TObject);
var
SelNode, node : TTreeNode;
Data : ^TNodeData;
Bunker : TBunker;
Line : TAssembleLine;
Material : TMaterial;
begin
node := nil;
SelNode := TreeView1.Selected;
case TNodeData(SelNode.Data^).NodeType of
ntCommFolder,
ntGivenFolder :
begin
Data := nil;
case TNodeData(SelNode.Data^).NodeType of
ntCommFolder : Bunker := TBunker.Create(Model.CommBunkers);
ntGivenFolder : Bunker := TBunker.Create(Model.GivenBunkers);
end;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntBunker;
case TNodeData(SelNode.Data^).NodeType of
ntCommFolder : Model.CommBunkers.Append(Bunker);
ntGivenFolder : Model.GivenBunkers.Append(Bunker);
end;
Data^.LinkedObject := Bunker;
node := TreeView1.Items.AddChildObject(SelNode, Bunker.Name , Data);
node.ImageIndex := 1;
node.SelectedIndex := 1;
end;
ntLineFolder :
begin
Data := nil;
Line := TAssembleLine.Create(Model.Lines);
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntLine;
Model.Lines.Append (Line);
Data^.LinkedObject := Line;
node := TreeView1.Items.AddChildObject(SelNode, Line.Name , Data);
node.ImageIndex := 4;
node.SelectedIndex := 4;
end;
ntMaterialFolder:
begin
Data := nil;
Material := TMaterial.Create(Model.Materials);
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntMaterial;
Model.Materials.Append(Material);
Data^.LinkedObject := Material;
node := TreeView1.Items.AddChildObject(SelNode, Material.Name, Data);
node.ImageIndex := 5;
node.SelectedIndex := 5;
end;
end;
SelNode.Expand(false);
if assigned(node) then
begin
node.Selected := true;
node.EditText;
end;
TreeView1Click(TreeView1);
end;
procedure TFModel.TreeView1Editing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
var
Data : TNodeData;
begin
Data := TNodeData(TreeView1.Selected.Data^);
case Data.NodeType of
ntBunker,
ntLine,
ntMaterial :
AllowEdit := true;
else
AllowEdit := false;
end;
end;
procedure TFModel.ADeleteElementExecute(Sender: TObject);
var
Data : TNodeData;
begin
Data := TNodeData(TreeView1.Selected.Data^);
if not (Data.LinkedObject is TListObject) then
begin
ShowMessage('ooops!');
exit;
end;
if Data.NodeType = ntMaterial then
if Model.IsMaterialUsed((Data.LinkedObject as TMaterial).Number) then
begin
MessageDlg(mCantDeleteMaterial,mtWarning, [mbOK], 0);
exit;
end;
if Data.NodeType = ntLine then
if Model.IsLineUsed((Data.LinkedObject as TAssembleLine).Number) then
begin
MessageDlg(mCantDeleteLine,mtWarning, [mbOK], 0);
exit;
end;
(Data.LinkedObject as TListObject).ObjectList.Delete(TreeView1.Selected.Index);
Data.LinkedObject.free;
TreeView1.Items.Delete(TreeView1.Selected);
TreeView1Click(TreeView1);
end;
procedure TFModel.TreeView1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_F2 : TreeView1.Selected.editText;
VK_NEXT : TreeView1.Selected.Expand(false);
VK_PRIOR : TreeView1.Selected.Collapse(false);
end;
end;
procedure HideAllEditors;
begin
FAllTime.hide;
FBunker.Hide;
FMaterial.Hide;
FLine.Hide;
end;
procedure TFModel.TreeView1Change(Sender: TObject; Node: TTreeNode);
var
Data : TNodeData;
begin
Data := TNodeData(TreeView1.Selected.Data^);
case Data.NodeType of
ntBunker,
ntLine,
ntMaterial :
begin
AAddElement.Enabled := false;
ADeleteElement.Enabled := true;
end;
ntModelFolder,
ntAllTime,
ntBunkerFolder :
begin
AAddElement.Enabled := false;
ADeleteElement.Enabled := false;
end;
else
begin
AAddElement.Enabled := true;
ADeleteElement.Enabled := false;
end;
end;
case Data.NodeType of
ntAllTime :
begin
NoObjectLabel.Hide;
FAllTime.Load(Model);
FAllTime.Show;
FAllTime.ActivateFocus;
end;
ntBunker :
begin
NoObjectLabel.Hide;
FBunker.Load(Data.LinkedObject as TBunker);
FBunker.Show;
end;
ntMaterial :
begin
NoObjectLabel.Hide;
FMaterial.Load(Data.LinkedObject as TMaterial);
FMaterial.Show;
end;
ntLine :
begin
NoObjectLabel.Hide;
FLine.Load(Data.LinkedObject as TAssembleLine);
FLine.Show;
end;
else
begin
HideAllEditors;
NoObjectLabel.Show;
NoObjectLabel.BringToFront;
end;
end;
end;
procedure TFModel.TreeView1Changing(Sender: TObject; Node: TTreeNode;
var AllowChange: Boolean);
var
Data : TNodeData;
begin
if TreeView1.Selected = nil then exit;
Data := TNodeData(TreeView1.Selected.Data^);
HideAllEditors;
case Data.NodeType of
ntAllTime : FAllTime.Save(Model);
ntBunker : FBunker.Save(Data.LinkedObject as TBunker);
ntMaterial : FMaterial.Save(Data.LinkedObject as TMaterial);
ntLine : FLine.Save(Data.LinkedObject as TAssembleLine);
end;
end;
procedure TFModel.TreeView1Edited(Sender: TObject; Node: TTreeNode;
var S: String);
begin
(TNodeData(Node.Data^).LinkedObject as TListObject).Name := S;
end;
procedure TFModel.LoadFromModel;
var
i : integer;
Data : ^TNodeData;
node , root: TTreeNode;
begin
TreeView1.FullCollapse;
InitTreeView;
root := TreeView1.Items[0];
// коммерческие бункеры
with Model.CommBunkers do
for i := Low(List) to High(List) do
begin
Data := nil;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntBunker;
Data^.LinkedObject := List[i];
node := TreeView1.Items.AddChildObject(root.Item[0].Item[0] , List[i].Name , Data);
node.ImageIndex := 1;
node.SelectedIndex := 1;
end;
// давальческие бункеры
with Model.GivenBunkers do
for i := Low(List) to High(List) do
begin
Data := nil;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntBunker;
Data^.LinkedObject := List[i];
node := TreeView1.Items.AddChildObject(root.Item[0].Item[1], List[i].Name , Data);
node.ImageIndex := 1;
node.SelectedIndex := 1;
end;
// Линии обработки
with Model.Lines do
for i := Low(List) to High(List) do
begin
Data := nil;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntLine;
Data^.LinkedObject := List[i];
node := TreeView1.Items.AddChildObject(root.item[1], List[i].Name , Data);
node.ImageIndex := 4;
node.SelectedIndex := 4;
end;
// Типы сырья
with Model.Materials do
for i := Low(List) to High(List) do
begin
Data := nil;
GetMem(Data, sizeof(TNodeData));
Data^.NodeType := ntMaterial;
Data^.LinkedObject := List[i];
node := TreeView1.Items.AddChildObject(root.item[2], List[i].Name , Data);
node.ImageIndex := 5;
node.SelectedIndex := 5;
end;
end;
procedure TFModel.SaveToModel;
var
temp : boolean;
begin
TreeView1Changing(TreeView1, TreeView1.Selected, temp);
end;
procedure TFModel.Ref;
begin
TreeView1Change(TreeView1, TreeView1.Selected);
end;
procedure TFModel.FormActivate(Sender: TObject);
begin
// LoadFromModel;
TreeView1.OnExpanding := TreeView1Expanding;
TreeView1.FullCollapse;
HideAllEditors;
Modified := true;
// Ref;
end;
procedure TFModel.TreeView1Expanding(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean);
begin
if TNodeData(Node.Data^).NodeType = ntModelFolder then
LoadFromModel;
TreeView1.OnExpanding := nil;
TreeView1.Items[0].Expand(false);
AllowExpansion := false;
end;
procedure TFModel.APrintExecute(Sender: TObject);
begin
SaveToModel;
if assigned(ModelReport) then ModelReport.free;
ModelReport := TModelReport.Create(nil);
ModelReport.Model := Model;
ModelReport.loadFromModel;
ModelReport.Update;
ModelReport.Preview;
end;
procedure TFModel.AClearExecute(Sender: TObject);
begin
if visible then TreeView1.FullCollapse;
if visible then TreeView1Change(TreeView1,TreeView1.Selected);
Model.Clear;
if visible then LoadFromModel;
end;
procedure TFModel.FormDestroy(Sender: TObject);
begin
Model.Free;
ModelCopy.Free;
end;
end.
|
{ ***************************************************************************
Dannyrooh Fernandes | https://github.com/dannyrooh | Licenša MIT
mapeametno da url
08/2021 - created
*************************************************************************** }
unit Bcb.Servico.Url;
interface
uses
System.SysUtils;
type
TBcbServicoUrl = class
strict private
const
URL_BCB_SERVICO = 'https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/';
URL_BCB_SERVICO_V1 = 'v1/odata/';
URL_BCB_SERVICO_COTACAO_DOLAR_PERIODO =
URL_BCB_SERVICO +
URL_BCB_SERVICO_V1 +
'CotacaoDolarPeriodo(dataInicial=@dataInicial,dataFinalCotacao=@dataFinalCotacao)?' +
'@dataInicial=:dataInicial' +
'&@dataFinalCotacao=:dataFinalCotacao' +
'&$format=json' +
'&$select=cotacaoCompra,cotacaoVenda,dataHoraCotacao';
DATA_FORMAT = 'MM-DD-YYYY';
public
class function CotacaoDolarPeriodo(dataInicial, dataFinalCotacao: TDateTime): string;
end;
implementation
{ TBcbServico }
class function TBcbServicoUrl.CotacaoDolarPeriodo(dataInicial,
dataFinalCotacao: TDateTime): string;
begin
result := URL_BCB_SERVICO_COTACAO_DOLAR_PERIODO
.Replace(':dataInicial',QuotedStr( FormatDateTime( DATA_FORMAT , dataInicial) ))
.Replace(':dataFinalCotacao',QuotedStr( FormatDateTime( DATA_FORMAT , dataFinalCotacao) ));
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado à tabela [PRODUTO]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
******************************************************************************* }
unit ProdutoController;
interface
uses
Classes, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti,
Atributos, VO, EcfProdutoVO, Generics.Collections, EcfE3VO, Biblioteca;
type
TProdutoController = class(TController)
private
class var FDataSet: TClientDataSet;
public
class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False);
class function ConsultaLista(pFiltro: String): TObjectList<TEcfProdutoVO>;
class function ConsultaObjeto(pFiltro: String): TEcfProdutoVO;
class function ConsultaPorTipo(pCodigo: String; pTipo: Integer): TEcfProdutoVO;
class procedure Produto(pFiltro: String);
class function Altera(pObjeto: TEcfProdutoVO): Boolean;
class function GetDataSet: TClientDataSet; override;
class procedure SetDataSet(pDataSet: TClientDataSet); override;
class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
end;
implementation
uses T2TiORM;
class procedure TProdutoController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean);
var
Retorno: TObjectList<TEcfProdutoVO>;
begin
try
Retorno := TT2TiORM.Consultar<TEcfProdutoVO>(pFiltro, pPagina, pConsultaCompleta);
TratarRetorno<TEcfProdutoVO>(Retorno);
finally
end;
end;
class function TProdutoController.ConsultaLista(pFiltro: String): TObjectList<TEcfProdutoVO>;
begin
try
Result := TT2TiORM.Consultar<TEcfProdutoVO>(pFiltro, '-1', True);
finally
end;
end;
class function TProdutoController.ConsultaObjeto(pFiltro: String): TEcfProdutoVO;
begin
try
Result := TT2TiORM.ConsultarUmObjeto<TEcfProdutoVO>(pFiltro, True);
finally
end;
end;
class function TProdutoController.ConsultaPorTipo(pCodigo: String; pTipo: Integer): TEcfProdutoVO;
var
Filtro: String;
begin
try
case pTipo of
1:
begin // pesquisa pelo codigo da balanca
Filtro := 'CODIGO_BALANCA = ' + QuotedStr(pCodigo);
end;
2:
begin // pesquisa pelo GTIN
Filtro := 'GTIN = ' + QuotedStr(pCodigo);
end;
3:
begin // pesquisa pelo CODIGO_INTERNO ou GTIN
Filtro := 'CODIGO_INTERNO = ' + QuotedStr(pCodigo);
end;
4:
begin // pesquisa pelo Id
Filtro := 'ID = ' + QuotedStr(pCodigo);
end;
end;
Result := TT2TiORM.ConsultarUmObjeto<TEcfProdutoVO>(Filtro, True);
finally
end;
end;
class procedure TProdutoController.Produto(pFiltro: String);
var
ObjetoLocal: TEcfProdutoVO;
begin
try
ObjetoLocal := TT2TiORM.ConsultarUmObjeto<TEcfProdutoVO>(pFiltro, True);
TratarRetorno<TEcfProdutoVO>(ObjetoLocal);
finally
end;
end;
class function TProdutoController.Altera(pObjeto: TEcfProdutoVO): Boolean;
begin
try
FormatSettings.DecimalSeparator := '.';
pObjeto.HashRegistro := '0';
pObjeto.HashRegistro := MD5String(pObjeto.ToJSONString);
Result := TT2TiORM.Alterar(pObjeto);
finally
FormatSettings.DecimalSeparator := ',';
end;
end;
class function TProdutoController.GetDataSet: TClientDataSet;
begin
Result := FDataSet;
end;
class procedure TProdutoController.SetDataSet(pDataSet: TClientDataSet);
begin
FDataSet := pDataSet;
end;
class procedure TProdutoController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
begin
try
TratarRetorno<TEcfProdutoVO>(TObjectList<TEcfProdutoVO>(pListaObjetos));
finally
FreeAndNil(pListaObjetos);
end;
end;
initialization
Classes.RegisterClass(TProdutoController);
finalization
Classes.UnRegisterClass(TProdutoController);
end.
|
unit UnitGame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, Menus, UnitSoko, StdCtrls, Buttons, ExtCtrls;
type
TFormGame = class(TForm)
MainMenu: TMainMenu;
NGame: TMenuItem;
DrawSoko: TDrawGrid;
NHelp: TMenuItem;
NDo: TMenuItem;
NCancelMove: TMenuItem;
NGameRestart: TMenuItem;
NExit: TMenuItem;
Timer: TTimer;
NPause: TMenuItem;
procedure FormActivate(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure RestoreMove;
procedure NExitClick(Sender: TObject);
procedure NCancelMoveClick(Sender: TObject);
procedure DrawCaption;
procedure GameRestart;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TimerTimer(Sender: TObject);
procedure NGameRestartClick(Sender: TObject);
procedure NPauseClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure WMMoving(var Msg: TWMMoving); message WM_MOVING;
end;
var
FormGame: TFormGame;
Path: string;
LevelName: string;
implementation
{$R *.dfm}
uses
{UnitMenu,} DateUtils;
var
Map: TMap;
IsGamePlayed: Boolean;
X,Y: Integer; // Позиции игрока
PoolCount: Integer; //Кол-во лунок
Steps, Pushes: Integer;
Time: TDateTime;
MoveStack: TMoveStackClass;
procedure TFormGame.FormActivate(Sender: TObject);
begin
IsGamePlayed := False;
Steps := 0;
Pushes := 0;
end;
procedure DrawOrPool(aGrid: TDrawGrid; x,y: Integer);
{В зависимости от состояния игрока ставит на его пред. поле лунку или дорогу}
begin
if Map[y,x] = CPlayerChar then
begin
Map[y,x] := CDrawChar;
DrawCell(aGrid, x, y, CDrawChar);
end
else
begin
Map[y,x] := CPoolChar;
DrawCell(aGrid, x, y, CPoolChar);
end;
end;
procedure TFormGame.RestoreMove;
var
Move: TMove;
begin
if MoveStack.pHead <> nil then
begin
Move := MoveStack.Pop;
if MoveStack.pHead = nil then
NCancelMove.Enabled := False;
x := x - ord(Move.PlayerDX);
y := y - ord(Move.PlayerDY);
Map[y,x] := Move.Char1;
Map[y + Ord(Move.PlayerDY), x + ord(Move.PlayerDX)] := Move.Char2;
Map[y+2*Ord(Move.PlayerDY), x+2*Ord(Move.PlayerDX)] := Move.Char3;
DrawPlayer(DrawSoko, x, y, Move.PlayerDX, Move.PlayerDY);
DrawCell(DrawSoko, x + ord(Move.PlayerDX), y + Ord(Move.PlayerDY), Move.Char2);
DrawCell(DrawSoko, x + 2*ord(Move.PlayerDX), y + 2*Ord(Move.PlayerDY), Move.Char3);
if Move.IsPushedBox then
begin
Dec(Pushes);
Dec(PoolCount, Move.PoolChange);
end;
Dec(Steps);
DrawCaption;
end;
end;
procedure TFormGame.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
dx: TDxMove;
dy: TDyMove;
Move: TMove;
Rec, OldRec: TRecord;
begin
if IsGamePlayed and InitilizeInput(Key, dx, dy) then
begin
if (Map[y+Ord(dy), x+Ord(dx)] = CDrawChar) or // Переход на дорогу
(Map[y+Ord(dy), x+Ord(dx)] = CPoolChar) then // Переход на лунку
begin
// Сохраняем ход
with Move do
begin
PlayerDX := dx;
PlayerDY := dy;
Char1 := Map[y,x];
Char2 := Map[y + Ord(dy), x + ord(dx)];
Char3 := Map[y+2*Ord(dy), x+2*Ord(dx)];
IsPushedBox := False;
PoolChange := 0;
end;
MoveStack.Push(Move);
NCancelMove.Enabled := True;
if (Map[y+Ord(dy), x+Ord(dx)] = CDrawChar) then //Перешли на дорогу
Map[y+Ord(dy), x+Ord(dx)] := CPlayerChar
else //Перешли на лунку
Map[y+Ord(dy), x+Ord(dx)] := CPlayerInPoolChar;
DrawOrPool(DrawSoko, x, y);
x := x + Ord(dx);
y := y + Ord(dy);
Inc(Steps);
DrawPlayer(DrawSoko, x, y, dx, dy);
end
else if ((Map[y+Ord(dy), x+Ord(dx)] = CBoxChar) or
(Map[y+Ord(dy), x+Ord(dx)] = CBoxInPoolChar)) and
((Map[y+2*Ord(dy), x+2*Ord(dx)] = CDrawChar) or
(Map[y+2*Ord(dy), x+2*Ord(dx)] = CPoolChar)) then // Двигаем коробку
begin
// Сохраняем ход
with Move do
begin
PlayerDX := dx;
PlayerDY := dy;
Char1 := Map[y,x];
Char2 := Map[y + Ord(dy), x + ord(dx)];
Char3 := Map[y+2*Ord(dy), x+2*Ord(dx)];
IsPushedBox := True;
PoolChange := 0;
end;
if (Map[y+2*Ord(dy), x+2*Ord(dx)] = CDrawChar) then // на дорогу
begin
Map[y+2*Ord(dy), x+2*Ord(dx)] := CBoxChar;
DrawCell(DrawSoko, x + 2*Ord(dx), y + 2*Ord(dy), CBoxChar);
end;
if (Map[y+2*Ord(dy), x+2*Ord(dx)] = CPoolChar) then //на лунку
begin
Map[y+2*Ord(dy), x+2*Ord(dx)] := CBoxInPoolChar;
DrawCell(DrawSoko, x + 2*Ord(dx), y + 2*Ord(dy), CBoxInPoolChar);
end;
DrawOrPool(DrawSoko, x, y); // вместо игрока ставим лунку или дорогу
if (Map[y+Ord(dy), x+Ord(dx)] = CBoxChar) then
Map[y+Ord(dy), x+Ord(dx)] := CPlayerChar
else // На место коробки ставим игрока
Map[y+Ord(dy), x+Ord(dx)] := CPlayerInPoolChar;
//DrawCell(DrawSoko, x + Ord(dx), y + Ord(dy), CPlayerPath);
DrawPlayer(DrawSoko, x + Ord(dx), y + Ord(dy), dx, dy);
// Увеличиваем счёт задвинутых коробок
if (Map[y+Ord(dy), x+Ord(dx)] = CPlayerChar) and
(Map[y+2*Ord(dy), x+2*Ord(dx)] = CBoxInPoolChar) then
begin
Dec(PoolCount);
Move.PoolChange := -1;
end;
// Уменьшаем счёт задвинутых коробок
if (Map[y+Ord(dy), x+Ord(dx)] = CPlayerInPoolChar) and
(Map[y+2*Ord(dy), x+2*Ord(dx)] = CBoxChar) then
begin
Inc(PoolCount);
Move.PoolChange := 1;
end;
MoveStack.Push(Move);
NCancelMove.Enabled := True;
x := x + Ord(dx);
y := y + Ord(dy);
Inc(Steps);
Inc(Pushes);
// Проверка на победу
if PoolCount = 0 then
begin
Timer.Enabled := False;
Rec.Moves := Steps;
Rec.Pushes := Pushes;
Rec.Time := TimeToStr(Time); // Сохраняем текущий счёт
if FileExists(Path + '.rec') and GetRecord(Path + '.rec', OldRec) then
begin
if (Rec.Moves <= OldRec.Moves) and (Rec.Pushes <= OldRec.Pushes) and
(Rec.Time <= OldRec.Time) then
SaveRecord(Path + '.rec', Rec);
end
else
SaveRecord(Path + '.rec', Rec);
IsGamePlayed := False;
end;
end;
DrawCaption;
end
else
begin
case Key of
Ord('Q'):
FormGame.Close;
Ord('R'):
GameRestart;
Ord('P'):
begin
IsGamePlayed := not IsGamePlayed;
DrawCaption;
end;
end;
if IsGamePlayed then
begin
case Key of
Ord('U'):
begin
RestoreMove;
end;
end;
end;
end;
end;
procedure TFormGame.FormPaint(Sender: TObject);
begin
if GetMapInFile(Path + '.skb', Map) then
IsGamePlayed := True
else
begin
MessageBox(Handle, 'Файл, содержащий данный уровень, неверен!', 'Ошибка',
MB_OK + MB_ICONERROR);
FormGame.Close;
end;
if IsGamePlayed then
begin
MakeBorder(Map, DrawSoko, FormGame);
FormGame.Left := (Screen.WorkAreaWidth - FormGame.Width) div 2;
FormGame.Top := (Screen.WorkAreaHeight - FormGame.Height) div 2;
DrawGrid(DrawSoko, Map);
GetVariables(Map, X, Y, PoolCount);
IsGamePlayed := True;
Steps := 0;
Pushes := 0;
DrawCaption;
Timer.Enabled := True;
end;
end;
procedure TFormGame.GameRestart;
begin
if GetMapInFile(Path + '.skb', Map) then
begin
IsGamePlayed := True;
DrawGrid(DrawSoko, Map);
GetVariables(Map, X, Y, PoolCount);
IsGamePlayed := True;
Steps := 0;
Pushes := 0;
Time := EncodeTime(0,0,0,0);
DrawCaption;
FreeAndNil(MoveStack);
MoveStack := TMoveStackClass.Create(StackSize);
Timer.Enabled := True;
MoveStack.Create(StackSize);
NCancelMove.Enabled := False;
end;
end;
procedure TFormGame.DrawCaption;
begin
if IsGamePlayed then
FormGame.Caption := '[PLAYED] '
else
FormGame.Caption := '[STOP] ';
FormGame.Caption := FormGame.Caption + 'LVL: ' + LevelName + ' MOVES: ' + IntToStr(Steps) + ' PUSHES: ' +
IntToStr(Pushes) + ' TIME: ' + TimeToStr(Time);
end;
procedure TFormGame.WMMoving(var Msg: TWMMoving);
var
workArea: TRect;
begin
workArea := Screen.WorkareaRect;
with Msg.DragRect^ do
begin
if Left < workArea.Left then
OffsetRect(Msg.DragRect^, workArea.Left-Left, 0) ;
if Top < workArea.Top then
OffsetRect(Msg.DragRect^, 0, workArea.Top-Top) ;
if Right > workArea.Right then
OffsetRect(Msg.DragRect^, workArea.Right-Right, 0) ;
if Bottom > workArea.Bottom then
OffsetRect(Msg.DragRect^, 0, workArea.Bottom-Bottom) ;
end;
inherited;
end;
procedure TFormGame.FormCreate(Sender: TObject);
begin
MoveStack := TMoveStackClass.Create(StackSize);
NCancelMove.Enabled := False;
Time := EncodeTime(0,0,0,0);
LongTimeFormat := 'hh:mm:ss';
end;
procedure TFormGame.FormDestroy(Sender: TObject);
begin
FreeAndNil(MoveStack);
end;
procedure TFormGame.NExitClick(Sender: TObject);
begin
FormGame.Close;
end;
procedure TFormGame.NCancelMoveClick(Sender: TObject);
begin
RestoreMove;
end;
procedure TFormGame.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFormGame.TimerTimer(Sender: TObject);
begin
if IsGamePlayed then
begin
Time := IncSecond(Time);
DrawCaption;
end;
end;
procedure TFormGame.NGameRestartClick(Sender: TObject);
begin
GameRestart;
end;
procedure TFormGame.NPauseClick(Sender: TObject);
begin
IsGamePlayed := not IsGamePlayed;
DrawCaption;
end;
end.
|
(**
* $Id: dco.transport.wm.WMTransportImpl.pas 845 2014-05-25 17:42:00Z QXu $
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either
* express or implied. See the License for the specific language governing rights and limitations under the License.
*)
unit dco.transport.wm.WMTransportImpl;
interface
uses
Winapi.Messages,
Winapi.Windows,
dutil.sys.win32.MessageWindowThread,
dco.transport.AbstractTransportImpl,
dco.transport.Pdu,
dco.util.ThreadedConsumer;
type
/// <summary>The class implements a transport resource via Windows messaging.</summary>
TWMTransportImpl = class(TAbstractTransportImpl)
private
FReceiverThread: TMessageWindowThread;
FSenderThread: TThreadedConsumer<TPdu>;
procedure CheckWMCopyData(var Message_: TMessage);
function MessageTaken(const Message_: TWMCopyData): Boolean;
function LocalWindow: HWND;
public
function WriteEnsured(const Pdu: TPdu): Boolean; override;
function GetUri: string; override;
private
procedure SendMessage(const Pdu: TPdu);
class function SendMessageAwait(const Pdu: TPdu): Boolean; static;
public
constructor Create;
destructor Destroy; override;
end;
implementation
uses
{$IFDEF LOGGING}
Log4D,
{$ENDIF}
System.SysUtils,
dco.transport.Uri;
type
TWMUri = record
private
FMessageWindow: HWND;
FId: Cardinal;
public
property MessageWindow: HWND read FMessageWindow;
property Id: Cardinal read FId;
public
constructor Create(MessageWindow: HWND; Id: Cardinal);
function ToString: string;
class function FromUri(const S: string): TWMUri; static;
end;
constructor TWMUri.Create(MessageWindow: HWND; Id: Cardinal);
begin
FMessageWindow := MessageWindow;
FId := Id;
end;
function TWMUri.ToString: string;
begin
Result := TUri.Create(Format('%d', [FMessageWindow]), FId).ToString;
end;
class function TWMUri.FromUri(const S: string): TWMUri;
var
Uri: TUri;
begin
Uri := TUri.FromString(S);
Result := TWMUri.Create(StrToInt(Uri.Domain), Uri.Id);
end;
constructor TWMTransportImpl.Create;
begin
inherited;
FSenderThread := TThreadedConsumer<TPdu>.Create(FOutboundQueue, SendMessage);
FSenderThread.NameThreadForDebugging('dco.system.sender <wm>', FSenderThread.ThreadID);
FReceiverThread := TMessageWindowThread.Create;
FReceiverThread.NameThreadForDebugging('dco.system.receiver <wm>', FReceiverThread.ThreadID);
FReceiverThread.OnMessage := CheckWMCopyData;
FSenderThread.Start;
FReceiverThread.Start;
end;
destructor TWMTransportImpl.Destroy;
begin
FReceiverThread.Free;
FSenderThread.Free;
inherited;
end;
procedure TWMTransportImpl.CheckWMCopyData(var Message_: TMessage);
begin
if Message_.Msg = WM_COPYDATA then
begin
if MessageTaken(TWMCopyData(Message_)) then
Message_.Result := Integer({Handled=}True);
end;
end;
function TWMTransportImpl.MessageTaken(const Message_: TWMCopyData): Boolean;
var
Id: Cardinal;
Pdu: TPdu;
begin
Id := Message_.CopyDataStruct.dwData;
try
Pdu := TPdu.Create(
TWMUri.Create(LocalWindow, Id).ToString,
TWMUri.Create(Message_.From, Id).ToString,
PChar(Message_.CopyDataStruct.lpData) // Copies data onto heap
);
except
Exit(False); // Unexpected message
end;
FInboundQueue.Put(Pdu);
Result := True;
{$IFDEF LOGGING}
TLogLogger.GetLogger(ClassName).Trace('<-%s: %s', [Pdu.Sender, Pdu.Message_]);
{$ENDIF}
end;
function TWMTransportImpl.LocalWindow: HWND;
begin
Result := FReceiverThread.WindowHandle;
end;
function TWMTransportImpl.WriteEnsured(const Pdu: TPdu): Boolean;
begin
// This message is expected to be sent immediately with ensurance, so we call the static method directly!
Result := SendMessageAwait(Pdu);
end;
function TWMTransportImpl.GetUri: string;
begin
Result := IntToStr(LocalWindow);
end;
procedure TWMTransportImpl.SendMessage(const Pdu: TPdu);
begin
SendMessageAwait(Pdu);
end;
class function TWMTransportImpl.SendMessageAwait(const Pdu: TPdu): Boolean;
var
Recipient: TWMUri;
Sender: TWMUri;
CopyData: CopyDataStruct;
begin
try
Recipient := TWMUri.FromUri(Pdu.Recipient);
Sender := TWMUri.FromUri(Pdu.Sender);
except
on E: Exception do
begin
{$IFDEF LOGGING}
TLogLogger.GetLogger(ClassName).Error(E.ToString);
{$ENDIF}
Exit(False);
end;
end;
if Recipient.Id <> Sender.Id then
begin
{$IFDEF LOGGING}
TLogLogger.GetLogger(ClassName).Error(
Format('Untrusted message header detected: Recipient=%s, Sender=%s, Message=%s',
[Pdu.Recipient, Pdu.Sender, Pdu.Message_]));
{$ENDIF}
Exit(False);
end;
if not IsWindow(Recipient.MessageWindow) then
Exit(False);
CopyData.dwData := Recipient.Id;
CopyData.lpData := PChar(Pdu.Message_);
CopyData.cbData := (Length(Pdu.Message_) + 1) * StringElementSize(Pdu.Message_);
Winapi.Windows.SendMessage(Recipient.MessageWindow, WM_COPYDATA, WPARAM(Sender.MessageWindow), LPARAM(@CopyData));
Result := True;
{$IFDEF LOGGING}
TLogLogger.GetLogger(ClassName).Trace('->%s: %s', [Pdu.Recipient, Pdu.Message_]);
{$ENDIF}
end;
end.
|
{12-En astrofísica, una galaxia se identifica por su nombre, su tipo (1. elíptica; 2. espiral; 3. lenticular; 4.
irregular), su masa (medida en kg) y la distancia en pársecs (pc) medida desde la Tierra. La Unión
Astronómica Internacional cuenta con datos correspondientes a las 53 galaxias que componen el Grupo
Local. Realizar un programa que lea y almacene estos datos y, una vez finalizada la carga, informe:
a) la cantidad de galaxias de cada tipo.
b) la masa total acumulada de las 3 galaxias principales (la Vía Láctea, Andrómeda y Triángulo) y el
porcentaje que esto representa respecto a la masa de todas las galaxias.
c) la cantidad de galaxias no irregulares que se encuentran a menos de 1000 pc.
d) el nombre de las dos galaxias con mayor masa y el de las dos galaxias con menor masa.}
Program ejer12;
Const
dimF = 53;
Type
str10 = string [10];
r_galaxia = record
nombre: str10;
tipo: 1..4;
masaKG: real;
distanciaPC: integer;
end;
v_gala = array [1..dimF] of r_galaxia;
v_tipo = array [1..4] of integer;
Procedure LEER (VAR g: r_galaxia);
Begin
with g do begin
writeln('Ingrese el nombre de la galaxia');
readln(nombre);
writeln('Ingrese tipo (de 1 a 4): ');
readln(tipo);
writeln('Ingrese su masa en KG ');
readln(masaKG);
writeln('Ingrese la distancia en parsecs medida desde la Tierra');
readln(distanciaPC);
end;
End;
Procedure CARGA (VAR v: v_gala);
VAR
i: integer;
g: r_galaxia;
Begin
For i:= 1 to dimF do begin
LEER (g);
v[i]:= g;
end;
End;
Procedure CARGATIPO (VAR vec2: v_tipo);
VAR
i: integer;
Begin
For i:= 1 to 4 do begin
vec2[i]:= 0;
end;
End;
//a) la cantidad de galaxias de cada tipo.
Procedure CANT_GALAXIA (tipoGal: integer; VAR vec2: v_tipo);
VAR
j: integer;
Begin
//j:= tipoGal;
vec2[tipoGal]:= vec2[tipoGal] + 1;
End;
//b) la masa total acumulada de las 3 galaxias principales (la Vía Láctea, Andrómeda y Triángulo) y el
//porcentaje que esto representa respecto a la masa de todas las galaxias.
FUNCTION MASAS3 (name: str10; masa_total:real): real;
Begin
If (name = 'VIA LACTEA') or (name = 'ANDROMEDA') or (name = 'TRIANGULO') then
MASAS3:= masa_total;
else
MASAS3:=0;
End;
FUNCTION PORCENT (masas,Total_Masas3: real): real;
Begin
PORCENT:= (Total_Masas3*100) / masas;
End;
//c) la cantidad de galaxias no irregulares que se encuentran a menos de 1000 pc.
FUNCTION NOIRREGULAR (tip,distancia:integer): integer;
Begin
If (tip <> 4 ) AND ( distancia < 1000) then
NOIRREGULAR:= 1
Else
NOIRREGULAR:= 0;
End;
//d) el nombre de las dos galaxias con mayor masa y el de las dos galaxias con menor masa
Procedure MAXIMOS (name:str10; VAR nameMax1,nameMax2: str10; masa:real; VAR masaMax1,masaMax2: real);
Begin
If (masa > masaMax1) then begin
masaMax2:= masaMax2;
masaMax1:= masa;
nameMax2:= nameMax1;
nameMax1:= name;
end
Else
If (masa > masaMax2) then begin
masaMax2:= masa;
nameMax2:= name;
end;
End;
Procedure MINIMOS (name:str10; VAR nameMin1,nameMin2: str10; masa:real; VAR masaMin1,masaMin2: real);
Begin
If (masa < masaMin1) then begin
masaMin2:= masaMin2;
masaMin1:= masa;
nameMin2:= nameMin1;
nameMin1:= name;
end
Else
If (masa < masaMin2) then begin
masaMin2:= masa;
nameMin2:= name;
end;
End;
Procedure IMPRIMIR (vec2: v_tipo);
Var
i: integer;
Begin
For i:= 1 to 4 do begin
writeln ('Para el tipo ',i,' hay ',vec2[i],' galaxias');
end;
End;
VAR
v: v_gala;
g: r_galaxia;
vec2: v_tipo;
i,no_irreg: integer;
Total_Masas3,masas: real;
nameMax1,nameMax2,nameMin1,nameMin2: str10;
masaMax1,masaMax2,masaMin1,masaMin2: real;
Begin
Total_Masas3:= 0;
masas:= 0;
no_irreg:=0;
masaMax1:= -1;
masaMax2:= -1;
masaMin1:= 99999;
masaMin2:= 99999;
CARGA (v); //guarda las galaxias
CARGATIPO (vec2); //inicializa el vector contador
For i:= 1 to dimF do begin
masas:= masas + v[i].masaKG; //suma todas las masas de las galaxias
CANT_GALAXIA (v[i].tipo, vec2); //INCISO A
//vec2[v[i].tipo] := vec2[v[i].tipo]+1;
Total_Masas3:= Total_Masas3 + MASAS3(v[i].nombre,v[i].masaKG);
no_irreg:= no_irreg + NOIRREGULAR(v[i].tipo,v[i].distanciaPC);
MAXIMOS (v[i].nombre,nameMax1,nameMax2,v[i].masaKG,masaMax1,masaMax2);
MINIMOS (v[i].nombre,nameMin1,nameMin2,v[i].masaKG,masaMin1,masaMin2);
end;
IMPRIMIR (vec2);
writeln('La masa total acumulada de las 3 galaxias principales (la Via Láctea, Andromeda y Triangulo) es de: ',Total_Masas3:6:2);
writeln('El porcentaje de la masa total acumulada de las 3 galaxias principales respecto a la masa de todas las galaxias es: ',PORCENT(masas,Total_Masas3):6:2,'%');
writeln('La cantidad de galaxias no irregulares que se encuentran a menos de 1000 pc es: ',no_irreg);
writeln('el nombre de las dos galaxias con mayor masa: ',nameMax1,' y ',nameMax2,' y el de las dos galaxias con menor masa: ',nameMin1,' y ',nameMin2);
readln();
End.
Program ejer7;
CONST
dimF = 9;
TYPE
v_numero = array [0..dimF] of integer;
Procedure INCIALIZAR_VECTOR (VAR v: v_numero);
Var
i: integer;
Begin
for i:= 1 to dimF do begin
v[i]:= 0;
end;
End;
Procedure DESCOMPONER(VAR v: v_numero; num:integer); //la cantidad de ocurrencias de cada dígito procesado.
var
dig: integer;
Begin
if(num=0)then
v[0]:= v[0] + 1;
while (num <> 0) do begin
dig:= num MOD 10;
v[dig]:= v[dig] + 1;
num:= num DIV 10;
end;
End;
Procedure LEER (VAR v: v_numero);
var
numero:integer;
Begin
writeln('Ingrese un numero: ');
readln(numero);
while (numero <> -1) do begin
DESCOMPONER(v,numero);
writeln('Ingrese un numero: ');
readln(numero);
end;
End;
Procedure IMPRIMIR (v: v_numero);
Var
i: integer;
Begin
writeln;
for i:= 0 to dimF do begin
writeln('La carga es : v[',i,']= ',v[i]);
end;
writeln;
end;
Procedure MAXDIG (v: v_numero;i:integer; VAR max,pos: integer); //el dígito más leído.
Begin
if (v[i] > max) then begin
max:= v[i];
pos:=i;
end;
end;
Procedure CERO_OCURRENCIA (v: v_numero; i: integer);
Begin
if (v[i] = 0) then
writeln('El digito ',i,' tuvo 0 ocurrencias');
End;
VAR
v: v_numero;
i,num: integer;
max: integer;
Begin
max:= -1;
INCIALIZAR_VECTOR(v);
LEER (v,num);
//IMPRIMIR (v);
For i:= 0 to dimF do begin
writeln('La carga es : v[',i,']= ',v[i]);
MAXDIG (v,i,max,pos);
CERO_OCURRENCIA (v,i);
end;
writeln('El mayor digito leido fue el : ',pos);
readln();
End.
{10. Realizar un programa que lea y almacene el salario de los empleados de una empresa de turismo (a lo
sumo 300 empleados). La carga finaliza cuando se lea el salario 0 (que no debe procesarse) o cuando se
completa el vector. Una vez finalizada la carga de datos se pide:
a) Realizar un módulo que incremente el salario de cada empleado en un 15%. Para ello, implementar un
módulo que reciba como parámetro un valor real X, el vector de valores reales y su dimensión lógica y
retorne el mismo vector en el cual cada elemento fue multiplicado por el valor X.
b) Realizar un módulo que muestre en pantalla el sueldo promedio de los empleados de la empresa.}
program ejercicio10; // A LO SUMO es <=
const
dimF = 3; //300; uso 5 para probar
type
rango= 1..dimF;
vec_Empleados = array [rango] of real;
function promedio (sueldoTotal:real; dimL:rango):real;
begin
promedio:=sueldoTotal/dimL;
end;
Procedure incrementarsueldo (x: real; var v: vec_Empleados; dimL:integer);
var
i:integer;
begin
for i:=1 to dimL do
v[i]:= v[i] + (v[i]*x);
end;
Procedure imprimir (v: vec_Empleados;dimL:integer);
var
i: integer;
total_sueldo:real;
Begin
total_sueldo:=0;
for i:=1 to dimL do
total_sueldo:= total_sueldo + v[i];
writeln('kjasnkjasd');
writeln(dimL);
writeln('El sueldo promedio de los empleados de la empresa es: $ ',(total_sueldo/dimL));
End;
Procedure cargarsueldos (var v:vec_Empleados;var dimL:integer);
var
sueldo:real;
begin
writeln('SUELDO:');
readln(sueldo);
while (sueldo <> 0 ) and (dimL<dimF) do begin
dimL:=dimL+1;
v[dimL]:=sueldo;
writeln('SUELDO:');
readln(sueldo);
end;
end;
var
vec:vec_Empleados;
i,dimL:integer;
numX:real;
begin
dimL:=0;
numX:=0.15;
cargarsueldos(vec,dimL);
writeln(vec[1]);
incrementarsueldo(numX,vec,dimL);
imprimir(vec,dimL);
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
}
unit ormbr.dml.generator.postgresql;
interface
uses
Classes,
SysUtils,
StrUtils,
Variants,
Rtti,
ormbr.dml.generator,
dbcbr.mapping.classes,
dbcbr.mapping.explorer,
dbebr.factory.interfaces,
ormbr.driver.register,
ormbr.dml.commands,
ormbr.dml.cache,
ormbr.criteria;
type
// Classe de banco de dados PostgreSQL
TDMLGeneratorPostgreSQL = class(TDMLGeneratorAbstract)
protected
function GetGeneratorSelect(const ACriteria: ICriteria): string; override;
public
constructor Create; override;
destructor Destroy; override;
function GeneratorSelectAll(AClass: TClass;
APageSize: Integer; AID: Variant): string; override;
function GeneratorSelectWhere(AClass: TClass;
AWhere: string; AOrderBy: string; APageSize: Integer): string; override;
function GeneratorAutoIncCurrentValue(AObject: TObject;
AAutoInc: TDMLCommandAutoInc): Int64; override;
function GeneratorAutoIncNextValue(AObject: TObject;
AAutoInc: TDMLCommandAutoInc): Int64; override;
end;
implementation
{ TDMLGeneratorPostgreSQL }
constructor TDMLGeneratorPostgreSQL.Create;
begin
inherited;
FDateFormat := 'yyyy-MM-dd';
FTimeFormat := 'HH:MM:SS';
end;
destructor TDMLGeneratorPostgreSQL.Destroy;
begin
inherited;
end;
function TDMLGeneratorPostgreSQL.GeneratorSelectAll(AClass: TClass;
APageSize: Integer; AID: Variant): string;
var
LCriteria: ICriteria;
LTable: TTableMapping;
begin
// Pesquisa se já existe o SQL padrão no cache, não tendo que montar toda vez
if not TQueryCache.Get.TryGetValue(AClass.ClassName, Result) then
begin
LCriteria := GetCriteriaSelect(AClass, AID);
Result := LCriteria.AsString;
// Faz cache do comando padrão
TQueryCache.Get.AddOrSetValue(AClass.ClassName, Result);
end;
LTable := TMappingExplorer.GetMappingTable(AClass);
// Where
Result := Result + GetGeneratorWhere(AClass, LTable.Name, AID);
// OrderBy
Result := Result + GetGeneratorOrderBy(AClass, LTable.Name, AID);
// Monta SQL para paginação
if APageSize > -1 then
Result := Result + GetGeneratorSelect(LCriteria);
end;
function TDMLGeneratorPostgreSQL.GeneratorSelectWhere(AClass: TClass;
AWhere: string; AOrderBy: string; APageSize: Integer): string;
var
LCriteria: ICriteria;
LScopeWhere: String;
LScopeOrderBy: String;
begin
// Pesquisa se já existe o SQL padrão no cache, não tendo que montar toda vez
if not TQueryCache.Get.TryGetValue(AClass.ClassName, Result) then
begin
LCriteria := GetCriteriaSelect(AClass, -1);
Result := LCriteria.AsString;
// Faz cache do comando padrão
TQueryCache.Get.AddOrSetValue(AClass.ClassName, Result);
end;
// Scope
LScopeWhere := GetGeneratorQueryScopeWhere(AClass);
if LScopeWhere <> '' then
Result := ' WHERE ' + LScopeWhere;
LScopeOrderBy := GetGeneratorQueryScopeOrderBy(AClass);
if LScopeOrderBy <> '' then
Result := ' ORDER BY ' + LScopeOrderBy;
// Params Where and OrderBy
if Length(AWhere) > 0 then
begin
Result := Result + IfThen(LScopeWhere = '', ' WHERE ', ' AND ');
Result := Result + AWhere;
end;
if Length(AOrderBy) > 0 then
begin
Result := Result + IfThen(LScopeOrderBy = '', ' ORDER BY ', ', ');
Result := Result + AOrderBy;
end;
// Monta SQL para paginação
if APageSize > -1 then
Result := Result + GetGeneratorSelect(LCriteria);
end;
function TDMLGeneratorPostgreSQL.GetGeneratorSelect(const ACriteria: ICriteria): string;
begin
Result := ' LIMIT %s OFFSET %s';
end;
function TDMLGeneratorPostgreSQL.GeneratorAutoIncCurrentValue(AObject: TObject;
AAutoInc: TDMLCommandAutoInc): Int64;
begin
Result := ExecuteSequence(Format('SELECT CURRVAL(''%s'')',
[AAutoInc.Sequence.Name]));
end;
function TDMLGeneratorPostgreSQL.GeneratorAutoIncNextValue(AObject: TObject;
AAutoInc: TDMLCommandAutoInc): Int64;
begin
Result := ExecuteSequence(Format('SELECT NEXTVAL(''%s'')',
[AAutoInc.Sequence.Name]));
end;
initialization
TDriverRegister.RegisterDriver(dnPostgreSQL, TDMLGeneratorPostgreSQL.Create);
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [FIN_COBRANCA_PARCELA_RECEBER]
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit FinCobrancaParcelaReceberVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils;
type
[TEntity]
[TTable('FIN_COBRANCA_PARCELA_RECEBER')]
TFinCobrancaParcelaReceberVO = class(TVO)
private
FID: Integer;
FID_FIN_COBRANCA: Integer;
FID_FIN_LANCAMENTO_RECEBER: Integer;
FID_FIN_PARCELA_RECEBER: Integer;
FDATA_VENCIMENTO: TDateTime;
FVALOR_PARCELA: Extended;
FVALOR_JURO_SIMULADO: Extended;
FVALOR_MULTA_SIMULADO: Extended;
FVALOR_RECEBER_SIMULADO: Extended;
FVALOR_JURO_ACORDO: Extended;
FVALOR_MULTA_ACORDO: Extended;
FVALOR_RECEBER_ACORDO: Extended;
//Transientes
public
[TId('ID', [ldGrid, ldLookup, ldComboBox])]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_FIN_COBRANCA', 'Id Fin Cobranca', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdFinCobranca: Integer read FID_FIN_COBRANCA write FID_FIN_COBRANCA;
[TColumn('ID_FIN_LANCAMENTO_RECEBER', 'Id Fin Lancamento Receber', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdFinLancamentoReceber: Integer read FID_FIN_LANCAMENTO_RECEBER write FID_FIN_LANCAMENTO_RECEBER;
[TColumn('ID_FIN_PARCELA_RECEBER', 'Id Fin Parcela Receber', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdFinParcelaReceber: Integer read FID_FIN_PARCELA_RECEBER write FID_FIN_PARCELA_RECEBER;
[TColumn('DATA_VENCIMENTO', 'Data Vencimento', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataVencimento: TDateTime read FDATA_VENCIMENTO write FDATA_VENCIMENTO;
[TColumn('VALOR_PARCELA', 'Valor Parcela', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorParcela: Extended read FVALOR_PARCELA write FVALOR_PARCELA;
[TColumn('VALOR_JURO_SIMULADO', 'Valor Juro Simulado', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorJuroSimulado: Extended read FVALOR_JURO_SIMULADO write FVALOR_JURO_SIMULADO;
[TColumn('VALOR_MULTA_SIMULADO', 'Valor Multa Simulado', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorMultaSimulado: Extended read FVALOR_MULTA_SIMULADO write FVALOR_MULTA_SIMULADO;
[TColumn('VALOR_RECEBER_SIMULADO', 'Valor Receber Simulado', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorReceberSimulado: Extended read FVALOR_RECEBER_SIMULADO write FVALOR_RECEBER_SIMULADO;
[TColumn('VALOR_JURO_ACORDO', 'Valor Juro Acordo', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorJuroAcordo: Extended read FVALOR_JURO_ACORDO write FVALOR_JURO_ACORDO;
[TColumn('VALOR_MULTA_ACORDO', 'Valor Multa Acordo', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorMultaAcordo: Extended read FVALOR_MULTA_ACORDO write FVALOR_MULTA_ACORDO;
[TColumn('VALOR_RECEBER_ACORDO', 'Valor Receber Acordo', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorReceberAcordo: Extended read FVALOR_RECEBER_ACORDO write FVALOR_RECEBER_ACORDO;
//Transientes
end;
implementation
initialization
Classes.RegisterClass(TFinCobrancaParcelaReceberVO);
finalization
Classes.UnRegisterClass(TFinCobrancaParcelaReceberVO);
end.
|
unit GameStages;
interface
uses
AvL, avlUtils, avlEventBus, avlMath, avlVectors, VSECore, Game;
type
TStageStart = class(TGameStage)
private
FCurrentPlayer: Integer;
FSceneSetQuarterHlColor: Integer;
procedure ActionCompleted(Sender: TObject; const Args: array of const);
public
constructor Create(Game: TGame);
destructor Destroy; override;
end;
TStageDoctorPrepare = class(TGameStage)
private
FPlayer: TPlayer;
FCtr: Integer;
public
constructor Create(Game: TGame; Player: TPlayer);
function Update: TGameStage; override;
end;
implementation
uses GameData, Scene, GameObjects, PlayerActions, Missions
{$IFDEF VSE_CONSOLE}, VSEConsole{$ENDIF}{$IFDEF VSE_LOG}, VSELog{$ENDIF};
{ TStageStart }
constructor TStageStart.Create(Game: TGame);
var
i: Integer;
r: TResourceType;
Char: TCharacter;
begin
inherited;
FCurrentPlayer := 0;
FSceneSetQuarterHlColor := EventBus.GetEventId(SceneSetQuarterHlColor);
EventBus.AddListener(EventBus.RegisterEvent(PlayerOnActionCompleted), ActionCompleted);
EventBus.SendEvent(SceneShowTitleMessage, Self, ['Подготовка', 0]);
for i := 0 to High(PlayerNames) do
with FGame.Player[PlayerNames[i]] do
if Character.Profile.IsDoctor then
begin
Arguments := 3;
for r := Low(TResourceType) to High(TResourceType) do
Resources[r] := 0;
Resources[(Objects[Objects.Add(FGame.Character[Name])] as TCharacter).Profile.Resource] := 1;
//TODO: Give Recipes deck and one Recipe
end
else begin
//TODO: Give plague decks of Doomed and Strains, select Targets
end;
for i := 0 to High(Characters) do
begin
Char := FGame.Character[Characters[i].Name];
Char.Quarantined := true;
if not Char.Profile.IsDoctor and (Char.Profile.Master <> '') then
FGame.Player[Char.Profile.Master].Objects.Add(Char);
end;
ActionCompleted(Self, []);
end;
destructor TStageStart.Destroy;
begin
EventBus.RemoveListener(ActionCompleted);
inherited;
end;
procedure TStageStart.ActionCompleted(Sender: TObject; const Args: array of const);
begin
if Sender = FGame.Player[SPlague] then
begin
FNextStage := TStageDoctorPrepare.Create(FGame, FGame.Player[SBachelor]);
Exit;
end;
Inc(FCurrentPlayer);
if FCurrentPlayer > High(PlayerNames) then
FCurrentPlayer := 1;
if Assigned(FGame.Player[PlayerNames[FCurrentPlayer]].Objects.ObjOfType[TCharacter, 0]) then
TPlaceCharacterAction.Create(FGame.Player[PlayerNames[FCurrentPlayer]])
else
TSelectQuarterAction.Create(FGame.Player[SPlague], qscFree);
end;
{ TStageDoctorPrepare }
constructor TStageDoctorPrepare.Create(Game: TGame; Player: TPlayer);
begin
inherited Create(Game);
EventBus.SendEvent(SceneShowTitleMessage, Self, [Player.Character.Profile.RuName + ': подготовка', 0])
end;
function TStageDoctorPrepare.Update: TGameStage;
begin
Result := inherited Update;
Inc(FCtr);
if (FCtr mod 200 = 0) and (FGame.Missions.Count > 0) then
(FGame.Missions.Take as TMission).Activate(FGame.ActivePlayer);
end;
end.
|
{$include kode.inc}
unit fx_blur;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_plugin,
kode_types;
const
str_onoff : array[0..1] of PChar = ('off','on');
type
myPlugin = class(KPlugin)
private
BUF : PSingle;
BUF_t : PSingle;
pos : Single;//LongInt;
bufsize : Single;//LongInt;
bufsize_t : Single;//LongInt;
public
decay, decay_t : Single;
decay2 : Single;
vol : Single;
bs,{d,d2,v,}fr : Single;
public
procedure on_create; override;
procedure on_destroy; override;
//procedure on_stateChange(AState:LongWord); override;
procedure on_parameterChange(AIndex:LongWord; AValue:Single); override;
procedure on_processBlock(AInputs, AOutputs: PPSingle; ASize: LongWord); override;
procedure on_processSample(AInputs,AOutputs:PPSingle); override;
end;
KPluginClass = myPlugin;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
_plugin_id,
kode_const,
kode_flags,
kode_memory,
kode_parameter,
kode_utils;
//----------
procedure myPlugin.on_create;
begin
FName := 'fx_blur';
FAuthor := 'skei.audio';
FProduct := FName;
FVersion := 0;
FUniqueId := KODE_MAGIC + fx_blur_id;
KSetFlag(FFlags,kpf_perSample);
appendParameter( KParamFloat.create('size', 0.5 ) );
appendParameter( KParamFloat.create('decay', 0.2 ) );
appendParameter( KParamFloat.create('xfade', 0.5 ) );
appendParameter( KParamFloat.create('volume', 0.7 ) );
appendParameter( KParamText.create( 'freeze', 0, 2, str_onoff) );
BUF := KMalloc($40000);
KMemset(BUF,0,$30000*4);
BUF_t := BUF + $10000;
pos := 0;
bufsize := 0;
decay := 0;
end;
//----------
procedure myPlugin.on_destroy;
begin
KFree(BUF);
end;
//----------
procedure myPlugin.on_parameterChange(AIndex:LongWord; AValue:Single);
var
//srate:single;
//index:longint;
v:single;
begin
// crash !!!
//srate := FSampleRate; // not available until is_Resume
case AIndex of
0:
begin
bs := AValue / 2;
//bufsize_t := ( srate * (bs*bs) ) ; //+ 1;
end;
1:
begin
decay_t := AValue*AValue;
end;
2:
begin
v := AValue / 10;
decay2 := v*v;
end;
3:
begin
v := AValue * 2;
vol := v*v;
end;
4:
begin
fr := AValue;
end;
end;
end;
//----------
procedure myPlugin.on_processBlock(AInputs, AOutputs: PPSingle; ASize: LongWord);
begin
bufsize_t := ( FSampleRate * (bs*bs) ) ; //+ 1;
end;
//----------
procedure myPlugin.on_processSample(AInputs,AOutputs:PPSingle);
var
spl0,spl1 : single;
//po2 : longint;
pp : longint;
begin
spl0 := AInputs[0]^;
spl1 := AInputs[1]^;
bufsize += ( bufsize_t - bufsize ) * decay2;
decay += ( decay_t - decay ) * decay2;
// left
pp := trunc(pos);
if (fr<0.5) then BUF_t[pp] := spl0;
BUF[pp] += (BUF_t[pp]-BUF[pp]) * decay;
spl0 := BUF[pp] * vol;
// right
pp := trunc(pos) + $20000;
if fr < 0.5 then BUF_t[pp] := spl1;
BUF[pp] += ( BUF_t[pp] - BUF[pp] ) * decay;
spl1 := BUF[pp] * vol;
pos += 1;
if pos >= bufsize then pos := 0;
AOutputs[0]^ := spl0;
AOutputs[1]^ := spl1;
end;
//----------------------------------------------------------------------
end.
|
unit Filters.Method;
interface
uses
System.Generics.Collections,
{--}
Metrics.UnitMethod;
type
TMethodFilter = class abstract
public
function IsMatching(const aMethodMetrics: TUnitMethodMetrics): boolean;
virtual; abstract;
end;
TMethodFilters = class
public
constructor Create();
destructor Destroy; override;
procedure Add(aMethodFilter: TMethodFilter);
procedure AddRange(aMethodFilters: TArray<TMethodFilter>);
function IsMatching(const aMethodMetrics: TUnitMethodMetrics): boolean;
procedure Clear;
function Count: Integer;
private
fFilters: TObjectList<TMethodFilter>;
end;
implementation
{ TMethodFiltes }
constructor TMethodFilters.Create;
begin
fFilters := TObjectList<TMethodFilter>.Create;
end;
destructor TMethodFilters.Destroy;
begin
fFilters.Free;
inherited;
end;
procedure TMethodFilters.Add(aMethodFilter: TMethodFilter);
begin
fFilters.Add(aMethodFilter);
end;
procedure TMethodFilters.AddRange(aMethodFilters: TArray<TMethodFilter>);
begin
fFilters.AddRange(aMethodFilters);
end;
procedure TMethodFilters.Clear;
begin
fFilters.Clear;
end;
function TMethodFilters.Count: Integer;
begin
Result := fFilters.Count;
end;
function TMethodFilters.IsMatching(
const aMethodMetrics: TUnitMethodMetrics): boolean;
var
filter: TMethodFilter;
begin
for filter in fFilters do begin
if not filter.IsMatching(aMethodMetrics) then
exit( False);
end;
Result := True;
end;
end.
|
unit uGnCsv;
interface
uses
SysUtils, Types, IOUtils, uGnStructures, uGnArray, uGnGeneral, uGnTextFile;
type
IGnCsvFile = interface(IGnContainer)
// setters getters
function GetColumns: NativeUInt;
procedure SetColumns(const AColumns: NativeUInt);
function GetItem(const AIndex: NativeUInt): TStringDynArray;
// ---
procedure LoadFromFile(const AFileName: string);
procedure SaveToFile(const AFileName: string);
procedure NewLine;
function Last: TStringDynArray;
property Columns: NativeUInt read GetColumns write SetColumns;
property Items[const Aindex: NativeUInt]: TStringDynArray read GetItem; default;
end;
TGnCsvFile = class(TInterfacedObject, IGnCsvFile)
strict private
type
TCsvArray = TGnArray<TStringDynArray>;
strict private
FColumns: NativeUInt;
FLines: TCsvArray.IGnArraySpec;
function GetCount: NativeUInt;
function GetColumns: NativeUInt;
procedure SetColumns(const AColumns: NativeUInt);
function GetItem(const AIndex: NativeUInt): TStringDynArray;
public
constructor Create(const AColumns: NativeUInt = 1);
procedure Clear;
function IsEmpty: Boolean;
procedure NewLine;
function Last: TStringDynArray;
procedure LoadFromFile(const AFileName: string);
procedure SaveToFile(const AFileName: string);
property Columns: NativeUInt read GetColumns write SetColumns;
property Count: NativeUInt read GetCount;
property Items[const Aindex: NativeUInt]: TStringDynArray read GetItem; default;
end;
implementation
{ TGnCsvFile }
procedure TGnCsvFile.Clear;
begin
FLines.Clear;
end;
constructor TGnCsvFile.Create(const AColumns: NativeUInt = 1);
begin
Assert(AColumns > 0, 'TGnCsvFile.Create');
inherited Create;
FLines := TCsvArray.Create;
FColumns := AColumns;
end;
function TGnCsvFile.GetColumns: NativeUInt;
begin
Result := FColumns;
end;
function TGnCsvFile.GetCount: NativeUInt;
begin
Result := FLines.Count;
end;
function TGnCsvFile.GetItem(const AIndex: NativeUInt): TStringDynArray;
begin
Result := FLines[AIndex];
end;
function TGnCsvFile.IsEmpty: Boolean;
begin
Result := FLines.IsEmpty;
end;
function TGnCsvFile.Last: TStringDynArray;
begin
Assert(FLines.Count > 0, 'TGnCsvFile.Last');
Result := FLines[FLines.Count - 1];
end;
procedure TGnCsvFile.LoadFromFile(const AFileName: string);
var
F: IGnTextFileNav;
ValueIndex, Pos: NativeUInt;
FirstFlag: Boolean;
procedure ReadValue;
begin
Pos := F.Pos.Pos;
if F.Ch = '"' then
begin
repeat
F.Next;
if F.NextIf('"') then
begin
if F.Ch = '"' then
Continue;
Last[ValueIndex] := AnsiDequotedStr(Copy(F.Text, Pos, F.Pos.Pos - Pos), '"');
Exit;
end;
until False;
end
else
begin
while not CharInSet(F.Ch, [',', #13, #10]) do
F.Next;
Last[ValueIndex] := Copy(F.Text, Pos, F.Pos.Pos - Pos);
end;
end;
procedure ReadLine;
begin
if CharInSet(F.Ch, [#0, #13, #10]) then
Exit;
NewLine;
repeat
ValueIndex := 0;
ReadValue;
while F.NextIf(',') do
begin
Inc(ValueIndex);
if FirstFlag then
Columns := Columns + 1;
ReadValue;
end;
until CharInSet(F.Ch, [#0, #13, #10]);
FirstFlag := False;
end;
begin
Clear;
Columns := 1;
F := TGnTextFileNav.Create(AFileName);
FirstFlag := True;
repeat
ReadLine;
F.NextIf(#13);
F.NextIf(#10);
until F.EOF;
end;
procedure TGnCsvFile.NewLine;
var
NewLine: TStringDynArray;
begin
SetLength(NewLine, FColumns);
FLines.Append(NewLine);
end;
procedure TGnCsvFile.SaveToFile(const AFileName: string);
var
Text: string;
Line: TStringDynArray;
i :Integer;
function Screening(const AStr: string): string;
var
Ch: Char;
begin
if AStr.IsEmpty then
Exit('');
for Ch in AStr do
if CharInSet(Ch, [#13, #10, '"', ',']) then
Exit(AnsiQuotedStr(AStr, '"'));
Result := AStr;
end;
begin
Text := '';
for Line in FLines do
begin
for i := 0 to FColumns - 2 do
Text := Text + Screening(Line[i]) + ',';
Text := Text + Screening(Line[FColumns - 1]) + #13#10;
end;
TFile.WriteAllText(AFileName, Text);
end;
procedure TGnCsvFile.SetColumns(const AColumns: NativeUInt);
var
i: Integer;
Temp: TStringDynArray;
begin
Assert(AColumns > 0, 'TGnCsvFile.SetColumns');
if AColumns = FColumns then
Exit;
for i := 0 to FLines.Count - 1 do
begin
Temp := FLines[i];
SetLength(Temp, AColumns);
FLines[i] := Temp;
end;
FColumns := AColumns;
end;
end.
|
unit Domino;
{
TDominoCard - Freeware
Version 1.0 - 6 February 2003
-----------------------------
Created by: Bee Jay
Copyright (C) BeeSoft Technology, 2003.
DESCRIPTION
-----------
TDominoCard is a domino card component for Delphi and Kylix.
* PROPERTIES
- TopValue
The value of the top side card, between 0 and 6.
- BottomValue
The value of the bottom side card, between 0 and 6.
- Deck
The type of deck that is shown if ShowDeck is True.
- ShowDeck
If True shows the back of the card.
- Orientation
Select card orientation, portrait or landscape.
* METHODS
- procedure Turn
Turn the card and show the deck, or viceversa.
- procedure Flip
Flip the top side down, or viceversa.
- procedure SelectRandom
Randomly choose value card.
- procedure SelectCard
Quickly set domino card's Value.
- function DifferentFrom
Returns True if the card is different from the specified one.
- function CompareCard
Returns comparison result between two specified domino card.
ACKNOWLEDGMENT
--------------
My big thank goes to all people who share their knowledges
about Delphi for free, I learned a lot from them. This
component is a small contribution from me to the community.
LICENSE
-------
This component is a freeware. Feel free to use, copy, modify,
and distribute it as long as for non-commercial use. However,
if you do some modification, please send me a copy of it.
DISCLAIMER
----------
This component is provided 'as is', and the author is under
no circumstances responsible for any damage, what soever,
that it might cause to anyone or anything.
CONTACT
-------
ICQ: 232400751
Email: bee.ography@gmail.com
}
interface
uses
{$IFDEF LINUX}
Messages, SysUtils, Classes, QGraphics, QControls, QForms, QDialogs;
{$ELSE}
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
{$ENDIF}
type
TDominoValue = 0..6;
TDominoDecks = (cdDeck, cdDefault);
TDominoCardMatch = (cmExact, cmReversed, cmTop, cmBottom, cmTopBottom, cmBottomTop, cmDifferent);
TDominoCardOrientation = (coPortrait, coLandscape);
(* TDominoCard *)
TDominoCard = class(TGraphicControl)
private
FTopValue: TDominoValue;
FBottomValue: TDominoValue;
FOrientation: TDominoCardOrientation;
FDeck: TDominoDecks;
FShowDeck: Boolean;
FFlipped: Boolean;
procedure SetTopValue(TheValue : TDominoValue);
procedure SetBottomValue(TheValue : TDominoValue);
procedure SetDeck(const TheDeck: TDominoDecks);
procedure SetShowDeck(const TheShowDeck: Boolean);
procedure SetOrientation(const TheOrientation: TDominoCardOrientation);
protected
property Height default 82;
property Width default 41;
property Constraints;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Flip;
procedure Turn;
procedure SelectRandom;
function DifferentFrom(const AnotherCard: TDominoCard): Boolean;
procedure SelectCard(const TheTopValue, TheBottomValue: TDominoValue);
function CompareCard(const FirstCard, SecondCard: TDominoCard): TDominoCardMatch;
published
property TopValue: TDominoValue read FTopValue write SetTopValue;
property BottomValue: TDominoValue read FBottomValue write SetBottomValue;
property Orientation: TDominoCardOrientation read FOrientation write SetOrientation default coPortrait;
property Deck: TDominoDecks read FDeck write SetDeck default cdDefault;
property ShowDeck: Boolean read FShowDeck write SetShowDeck default False;
property Action;
property Anchors;
property Cursor;
property DragMode;
property Enabled;
property ShowHint;
property Visible;
property PopupMenu;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
procedure Register;
implementation
{$R DOMINO.RES}
procedure Register;
begin
RegisterComponents('Samples', [TDominoCard]);
end;
(* === TDominoCard component === *)
(* TDominoCard constructor/destructor *)
constructor TDominoCard.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Randomize;
FTopValue := 0;
FBottomValue := 0;
FOrientation := coPortrait;
FDeck := cdDefault;
FShowDeck := False;
FFlipped := False;
// unchangeable size
Height := 82;
Width := 41;
Constraints.MaxHeight := Height;
Constraints.MaxWidth := Width;
Constraints.MinHeight := Height;
Constraints.MinWidth := Width;
end;
destructor TDominoCard.Destroy;
begin
inherited Destroy;
end;
(* TDominoCard private methods *)
procedure TDominoCard.SetTopValue(TheValue : TDominoValue);
begin
if TheValue < 0 then TheValue := 0;
if TheValue > 6 then TheValue := 6;
FTopValue := TheValue;
Repaint;
end;
procedure TDominoCard.SetBottomValue(TheValue : TDominoValue);
begin
if TheValue < 0 then TheValue := 0;
if TheValue > 6 then TheValue := 6;
FBottomValue := TheValue;
Repaint;
end;
procedure TDominoCard.SetDeck(const TheDeck: TDominoDecks);
begin
FDeck := TheDeck;
Repaint;
end;
procedure TDominoCard.SetShowDeck(const TheShowDeck: Boolean);
begin
FShowDeck := TheShowDeck;
Repaint;
end;
procedure TDominoCard.SetOrientation(const TheOrientation: TDominoCardOrientation);
begin
FOrientation := TheOrientation;
Constraints.MaxHeight := 0;
Constraints.MaxWidth := 0;
Constraints.MinHeight := 0;
Constraints.MinWidth := 0;
case FOrientation of
coPortrait:
begin
Height := 82;
Width := 41;
end;
coLandscape:
begin
Height := 41;
Width := 82;
end;
end;
Constraints.MaxHeight := Height;
Constraints.MaxWidth := Width;
Constraints.MinHeight := Height;
Constraints.MinWidth := Width;
Repaint;
end;
(* TDominoCard protected methods *)
procedure TDominoCard.Paint;
var
CardBmp: TBitmap;
ResName: string;
i,j: integer;
begin
FFlipped := (FTopValue > FBottomValue);
// show selected card
if not FShowDeck then
begin
if FFlipped then
ResName := IntToStr(FBottomValue)+'_'+IntToStr(FTopValue)
else
ResName := IntToStr(FTopValue)+'_'+IntToStr(FBottomValue);
end
// show selected deck
else
begin
case FDeck of
cdDeck: ResName := 'DECK';
cdDefault: ResName := 'BACK';
end;
if FOrientation = coLandscape then ResName := ResName+'_LS';
end;
// load bitmap from resources
if Visible then
begin
CardBmp := TBitmap.Create;
CardBmp.LoadFromResourceName(HInstance,ResName);
if FShowDeck then
Canvas.Draw(0,0,CardBmp)
else
begin
case FOrientation of
coPortrait:
if not FFlipped then
Canvas.Draw(0,0,CardBmp)
else
begin
Canvas.Draw(0,-41,CardBmp);
Canvas.Draw(0,41,CardBmp);
end;
coLandscape:
begin
ResName := IntToStr(FTopValue)+'_LS';
CardBmp.LoadFromResourceName(HInstance,ResName);
Canvas.Draw(0,0,CardBmp);
ResName := IntToStr(FBottomValue)+'_LS';
CardBmp.LoadFromResourceName(HInstance,ResName);
Canvas.Draw(41,0,CardBmp);
end;
end;
// gray disabled card
if not Enabled then
for i := 1 to (Width div 2)-1 do
for j := 1 to (Height div 2)-1 do
Canvas.Pixels[i*2,j*2] := clBlue;
end;
CardBmp.Free;
end
else
begin
// design state
if csDesigning in self.ComponentState then
Canvas.Rectangle(0,0,Width,Height);
end;
end;
(* TDominoCard public methods *)
procedure TDominoCard.Turn;
begin
ShowDeck := not ShowDeck;
end;
procedure TDominoCard.Flip;
var
tempval: TDominoValue;
begin
tempval := FTopValue;
FTopValue := FBottomValue;
FBottomValue := tempval;
Repaint;
end;
procedure TDominoCard.SelectRandom;
var
rand: Integer;
begin
rand := Random(7);
FTopValue := rand;
rand := Random(7);
FBottomValue := rand;
Repaint;
end;
function TDominoCard.DifferentFrom(const AnotherCard: TDominoCard): Boolean;
begin
Result := ((FTopValue <> AnotherCard.TopValue) or (FBottomValue <> AnotherCard.BottomValue)) and
((FTopValue <> AnotherCard.BottomValue) or (FBottomValue <> AnotherCard.TopValue));
end;
procedure TDominoCard.SelectCard(const TheTopValue, TheBottomValue: TDominoValue);
begin
if (TheTopValue >= 0) and (TheTopValue <= 6) then TopValue := TheTopValue;
if (TheBottomValue >= 0) and (TheBottomValue <= 6) then BottomValue := TheBottomValue;
end;
function TDominoCard.CompareCard(const FirstCard, SecondCard: TDominoCard): TDominoCardMatch;
begin
// first card equal second card in exact order
if (FirstCard.TopValue = SecondCard.TopValue) and (FirstCard.BottomValue = SecondCard.BottomValue) then
Result := cmExact
// first card equal second card in reverse order
else if (FirstCard.TopValue = SecondCard.BottomValue) and (FirstCard.BottomValue = SecondCard.TopValue) then
Result := cmReversed
// first card equal second card only on top side
else if (FirstCard.TopValue = SecondCard.TopValue) and (FirstCard.BottomValue <> SecondCard.BottomValue) then
Result := cmTop
// first card equal second card only on bottom side
else if (FirstCard.BottomValue = SecondCard.BottomValue) and (FirstCard.TopValue <> SecondCard.TopValue) then
Result := cmBottom
// first card top_value equal second card bottom_value
else if (FirstCard.TopValue = SecondCard.BottomValue) and (FirstCard.BottomValue <> SecondCard.TopValue) then
Result := cmTopBottom
// first card bottom_value equal second card top_value
else if (FirstCard.BottomValue = SecondCard.TopValue) and (FirstCard.TopValue <> SecondCard.BottomValue) then
Result := cmBottomTop
// first card different from second card
else Result := cmDifferent;
end;
end.
|
{
JS Beautifier
---------------
Delphi port by Mihail Slobodyanuk, <slobodyanukma@gmail.com>
Written by Einar Lielmanis, <einar@jsbeautifier.org>
http://jsbeautifier.org/
Originally converted to javascript by Vital, <vital76@gmail.com>
You are free to use this in any way you want, in case you find this useful or working for you.
Usage:
js_beautify(js_source_text);
js_beautify(js_source_text, options);
The options are:
indent_size (default 4) - indentation size,
indent_char (default space) - character to indent with,
preserve_newlines (default true) - whether existing line breaks should be preserved,
preserve_max_newlines (default 0) - maximum number of line breaks to be preserved in one chunk 0 - unlimited,
indent_level (default 0) - initial indentation level, you probably won't need this ever,
space_after_anon_function (default false) - if true, then space is added between "function ()"
(jslint is happy about this); if false, then the common "function()" output is used.
braces_on_own_line (default false) - ANSI / Allman brace style, each opening/closing brace gets its own line.
e.g
js_beautify(js_source_text, 1, #9);
}
unit jsbeautify;
interface
uses Classes;
function js_beautify(js_source_text: string;
indent_size: Integer = 4;
indent_char: Char = ' ';
preserve_newlines: Boolean = True;
max_preserve_newlines: Integer = 0;
indent_level: Integer = 0;
space_after_anon_function: Boolean = False;
braces_on_own_line: Boolean = False;
keep_array_indentation: Boolean = False):string;
implementation
uses SysUtils, StrUtils, functions;
type
TToken = array[0..1] of string;
TFlags = class
public
previous_mode: string;
mode: string;
var_line: Boolean;
var_line_tainted: Boolean;
var_line_reindented: Boolean;
in_html_comment: Boolean;
if_line: Boolean;
in_case: Boolean;
eat_next_space: Boolean;
indentation_baseline: Integer;
indentation_level: Integer;
end;
Tjs_beautify = class
input, token_text, last_type, last_text, last_last_text, last_word, indent_string: string;
flags: TFlags;
output, flag_store: TStringList;
whitespace, wordchar, punct, line_starters, digits: TStringArray;
parser_pos: integer;
prefix, token_type: string;
wanted_newline, just_added_newline, do_block_just_closed: Boolean;
n_newlines: Integer;
js_source_text: string;
opt_braces_on_own_line: Boolean;
opt_indent_size: Integer;
opt_indent_char: Char;
opt_preserve_newlines: Boolean;
opt_max_preserve_newlines: Integer;
opt_indent_level: Integer; // starting indentation
opt_space_after_anon_function: Boolean;
opt_keep_array_indentation: Boolean;
input_length: Integer;
procedure set_mode(mode: string);
function get_next_token(): TToken;
procedure print_single_space;
procedure print_token;
procedure trim_output(eat_newlines:Boolean = false);
function is_array(mode: string): Boolean;
procedure print_newline(ignore_repeated: Boolean = true);
procedure indent;
procedure remove_indent;
function is_expression(mode: string): Boolean;
procedure restore_mode;
function is_ternary_op(): Boolean;
public
constructor Create(js_source_text: string;
indent_size: Integer = 4;
indent_char: Char = ' ';
preserve_newlines: Boolean = True;
max_preserve_newlines: Integer = 0;
indent_level: Integer = 0;
space_after_anon_function: Boolean = False;
braces_on_own_line: Boolean = False;
keep_array_indentation: Boolean = False);
destructor Destroy; override;
function getBeauty: string;
end;
constructor Tjs_beautify.Create(js_source_text: string;
indent_size: Integer;
indent_char: Char;
preserve_newlines: Boolean;
max_preserve_newlines: Integer;
indent_level: Integer;
space_after_anon_function: Boolean;
braces_on_own_line: Boolean;
keep_array_indentation: Boolean);
begin
Self.js_source_text := js_source_text;
self.opt_braces_on_own_line := braces_on_own_line;
self.opt_indent_size := indent_size;
self.opt_indent_char := indent_char;
self.opt_preserve_newlines := preserve_newlines;
self.opt_max_preserve_newlines := max_preserve_newlines;
self.opt_indent_level := indent_level; // starting indentation
self.opt_space_after_anon_function := space_after_anon_function;
self.opt_keep_array_indentation := keep_array_indentation;
output := TStringList.Create();
whitespace := split(#13#10#9' ');
wordchar := split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$');
punct := split('+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! !! , : ? ^ ^= |= ::', ' ');
// words which should always start on new line.
line_starters := split('continue,try,throw,return,var,if,switch,case,default,for,while,break,function', ',');
digits := split('0123456789');
// states showing if we are currently in expression (i.e. "if" case) - 'EXPRESSION', or in usual block (like, procedure), 'BLOCK'.
// some formatting depends on that.
flag_store := TStringList.Create();
self.flags := TFlags.Create;
self.flags.previous_mode := '';
self.flags.mode := 'BLOCK';
self.flags.indentation_level := self.opt_indent_level;
self.flags.var_line := false;
self.flags.var_line_tainted := false;
self.flags.var_line_reindented := false;
self.flags.in_html_comment := false;
self.flags.if_line := false;
self.flags.in_case := false;
self.flags.eat_next_space := false;
self.flags.indentation_baseline := -1;
end;
destructor Tjs_beautify.Destroy;
begin
Output.free;
flag_store.free;
FreeAndNil(flags);
end;
function Tjs_beautify.getBeauty(): string;
var
t: TToken;
i: Integer;
space_before, space_after: Boolean;
lines: TStringArray;
label
next_token;
begin
just_added_newline := false;
// cache the source's length.
input_length := length(js_source_text);
//----------------------------------
indent_string := '';
while opt_indent_size > 0 do
begin
indent_string := indent_string + opt_indent_char;
opt_indent_size := opt_indent_size - 1;
end;
input := js_source_text;
last_word := ''; // last 'TK_WORD' passed
last_type := 'TK_START_EXPR'; // last token type
last_text := ''; // last token text
last_last_text := ''; // pre-last token text
do_block_just_closed := false;
set_mode('BLOCK');
parser_pos := 0;
while true do
begin
t := get_next_token;
token_text := t[0];
token_type := t[1];
if token_type = 'TK_EOF' then
begin
break;
end;
//swich ro string
if token_type = 'TK_START_EXPR' then
begin
if token_text = '[' then
begin
if (last_type = 'TK_WORD') or (last_text = ')') then
begin
// this is array index specifier, break immediately
// a[x], fn()[x]
if in_array(last_text, line_starters) then
begin
print_single_space;
end;
set_mode('(EXPRESSION)');
print_token;
goto next_token;
end;
if (flags.mode = '[EXPRESSION]') or (flags.mode = '[INDENTED-EXPRESSION]') then
begin
if (last_last_text = ']') and (last_text = ',') then
begin
// ], [ goes to new line
if flags.mode = '[EXPRESSION]' then
begin
flags.mode := '[INDENTED-EXPRESSION]';
if not opt_keep_array_indentation then
begin
indent;
end;
end;
set_mode('[EXPRESSION]');
if not opt_keep_array_indentation then
begin
print_newline;
end;
end
else if last_text = '[' then
begin
if flags.mode = '[EXPRESSION]' then
begin
flags.mode := '[INDENTED-EXPRESSION]';
if not opt_keep_array_indentation then
begin
indent();
end;
end;
set_mode('[EXPRESSION]');
if not opt_keep_array_indentation then
begin
print_newline;
end;
end
else
begin
set_mode('[EXPRESSION]');
end;
end
else
begin
set_mode('[EXPRESSION]');
end;
end
else
begin
set_mode('(EXPRESSION)');
end;
if (last_text = ';') or (last_type = 'TK_START_BLOCK') then
begin
print_newline();
end
else if (last_type = 'TK_END_EXPR') or (last_type = 'TK_START_EXPR') or (last_type = 'TK_END_BLOCK') or (last_text = '.') then
begin
// do nothing on (( and )( and ][ and ]( and .(
end
else if (last_type <> 'TK_WORD') and (last_type <> 'TK_OPERATOR') then
begin
print_single_space;
end
else if last_word = 'function' then
begin
// function() vs function ()
if opt_space_after_anon_function then
begin
print_single_space;
end;
end
else if (in_array(last_text, line_starters)) or (last_text = 'catch') then
begin
print_single_space;
end;
print_token();
end
else if token_type = 'TK_END_EXPR' then
begin
if token_text = ']' then
begin
if (opt_keep_array_indentation) then
begin
if (last_text = '}') then
begin
// trim_output();
// print_newline(true);
remove_indent();
print_token();
restore_mode();
goto next_token;
end;
end
else
begin
if (flags.mode = '[INDENTED-EXPRESSION]') then
begin
if (last_text = ']') then
begin
restore_mode();
print_newline();
print_token();
goto next_token;
end;
end;
end;
end;
restore_mode();
print_token();
end
else if token_type = 'TK_START_BLOCK' then
begin
if (last_word = 'do') then
begin
set_mode('DO_BLOCK');
end
else
begin
set_mode('BLOCK');
end;
if (opt_braces_on_own_line) then
begin
if (last_type <> 'TK_OPERATOR') then
begin
if (last_text = 'return') then
begin
print_single_space();
end
else
begin
print_newline(true);
end;
end;
print_token();
indent();
end
else
begin
if (last_type <> 'TK_OPERATOR') and (last_type <> 'TK_START_EXPR') then
begin
if (last_type = 'TK_START_BLOCK') then
begin
print_newline();
end
else
begin
print_single_space();
end;
end
else
begin
// if TK_OPERATOR or TK_START_EXPR
if is_array(flags.previous_mode) and (last_text = ',') then
begin
print_newline(); // [a, b, c, begin
end;
end;
indent();
print_token();
end;
end
else if token_type = 'TK_END_BLOCK' then
begin
restore_mode();
if (opt_braces_on_own_line) then
begin
print_newline();
print_token();
end
else
begin
if (last_type = 'TK_START_BLOCK') then
begin
// nothing
if (just_added_newline) then
begin
remove_indent();
end
else
begin
// {};
trim_output();
end;
end
else
begin
if is_array(flags.mode) and opt_keep_array_indentation then
begin
// we REALLY need a newline here, but newliner would skip that
opt_keep_array_indentation := false;
print_newline();
opt_keep_array_indentation := true;
end
else print_newline();
end;
print_token();
end;
end
else if token_type = 'TK_WORD' then
begin
// no, it's not you. even I have problems understanding how this works
// and what does what.
if (do_block_just_closed) then
begin
// do beginend; ## while ()
print_single_space();
print_token();
print_single_space();
do_block_just_closed := false;
goto next_token;
end;
if (token_text = 'function') then
begin
if (just_added_newline or (last_text = ';')) and (last_text <> '{') then
begin
// make sure there is a nice clean space of at least one blank line
// before a new function definition
if just_added_newline then
n_newlines := n_newlines
else n_newlines := 0;
if not opt_preserve_newlines then n_newlines := 1;
for i := 0 to 1 - n_newlines do
begin
print_newline(false);
end;
end;
end;
if ((token_text = 'case') or (token_text = 'default')) then
begin
if (last_text = ':') then
begin
// switch cases following one another
remove_indent();
end
else
begin
// case statement starts in the same line where switch
Dec(flags.indentation_level);
print_newline();
Inc(flags.indentation_level);
end;
print_token();
flags.in_case := true;
goto next_token;
end;
prefix := 'NONE';
if (last_type = 'TK_END_BLOCK') then
begin
if not in_array(LowerCase(token_text), ['else', 'catch', 'finally']) then
begin
prefix := 'NEWLINE';
end
else
begin
if (opt_braces_on_own_line) then
begin
prefix := 'NEWLINE';
end
else
begin
prefix := 'SPACE';
print_single_space();
end;
end;
end
else if (last_type = 'TK_SEMICOLON') and ((flags.mode = 'BLOCK') or (flags.mode = 'DO_BLOCK')) then
begin
prefix := 'NEWLINE';
end
else if ((last_type = 'TK_SEMICOLON') and is_expression(flags.mode)) then
begin
prefix := 'SPACE';
end
else if (last_type = 'TK_STRING') then
begin
prefix := 'NEWLINE';
end
else if (last_type = 'TK_WORD') then
begin
prefix := 'SPACE';
end
else if (last_type = 'TK_START_BLOCK') then
begin
prefix := 'NEWLINE';
end
else if (last_type = 'TK_END_EXPR') then
begin
print_single_space();
prefix := 'NEWLINE';
end;
if (flags.if_line and (last_type = 'TK_END_EXPR')) then flags.if_line := false;
if (in_array(LowerCase(token_text), ['else', 'catch', 'finally'])) then
begin
if (last_type <> 'TK_END_BLOCK') or opt_braces_on_own_line then
print_newline()
else
begin
trim_output(true);
print_single_space();
end;
end
else if (in_array(token_text, line_starters) or (prefix = 'NEWLINE')) then
begin
if (((last_type = 'TK_START_EXPR') or (last_text = '=') or (last_text = ',')) and (token_text = 'function')) then
begin
// no need to force newline on 'function': (function
// DONOTHING
end
else if ((last_text = 'return') or (last_text = 'throw')) then
begin
// no newline between 'return nnn'
print_single_space();
end
else if (last_type <> 'TK_END_EXPR') then
begin
if (((last_type <> 'TK_START_EXPR') or (token_text <> 'var')) and (last_text <> ':')) then
begin
// no need to force newline on 'var': for (var x = 0...)
if ((token_text = 'if') and (last_word = 'else') and (last_text <> '{')) then
begin
// no newline for end; else if begin
print_single_space();
end
else
begin
print_newline();
end;
end;
end
else
begin
if (in_array(token_text, line_starters) and (last_text <> ')')) then
begin
print_newline();
end;
end;
end
else if (is_array(flags.mode) and (last_text = ',') and (last_last_text = '}')) then
begin
print_newline(); // end;, in lists get a newline treatment
end
else if (prefix = 'SPACE') then
begin
print_single_space();
end;
print_token();
last_word := token_text;
if (token_text = 'var') then
begin
flags.var_line := true;
flags.var_line_reindented := false;
flags.var_line_tainted := false;
end;
if (token_text = 'if') then
begin
flags.if_line := true;
end;
if (token_text = 'else') then
begin
flags.if_line := false;
end;
end
else if token_type = 'TK_SEMICOLON' then
begin
print_token();
flags.var_line := false;
flags.var_line_reindented := false;
end
else if token_type = 'TK_STRING' then
begin
if (last_type = 'TK_START_BLOCK') or (last_type = 'TK_END_BLOCK') or (last_type = 'TK_SEMICOLON') then
begin
print_newline();
end
else if (last_type = 'TK_WORD') then
begin
print_single_space();
end;
print_token();
end
else if token_type = 'TK_EQUALS' then
begin
if (flags.var_line) then
begin
// just got an '=' in a var-line, different formatting/line-breaking, etc will now be done
flags.var_line_tainted := true;
end;
print_single_space();
print_token();
print_single_space();
end
else if token_type = 'TK_OPERATOR' then
begin
space_before := true;
space_after := true;
if (flags.var_line and (token_text = ',') and (is_expression(flags.mode))) then
begin
// do not break on comma, for(var a = 1, b = 2)
flags.var_line_tainted := false;
end;
if (flags.var_line) then
begin
if (token_text = ',') then
begin
if (flags.var_line_tainted) then
begin
print_token();
flags.var_line_reindented := true;
flags.var_line_tainted := false;
print_newline();
goto next_token;
end
else
begin
flags.var_line_tainted := false;
end;
// end; else if (token_text = ':') begin
// hmm, when does this happen? tests don't catch this
// flags.var_line = false;
end;
end;
if ((last_text = 'return') or (last_text = 'throw')) then
begin
// "return" had a special handling in TK_WORD. Now we need to return the favor
print_single_space();
print_token();
goto next_token;
end;
if (token_text = ':') and flags.in_case then
begin
print_token(); // colon really asks for separate treatment
print_newline();
flags.in_case := false;
goto next_token;
end;
if (token_text = '::') then
begin
// no spaces around exotic namespacing syntax operator
print_token();
goto next_token;
end;
if (token_text = ',') then
begin
if (flags.var_line) then
begin
if (flags.var_line_tainted) then
begin
print_token();
print_newline();
flags.var_line_tainted := false;
end
else
begin
print_token();
print_single_space();
end;
end
else if (last_type = 'TK_END_BLOCK') and (flags.mode <> '(EXPRESSION)') then
begin
print_token();
if (flags.mode = 'OBJECT') and (last_text = '}') then
begin
print_newline();
end
else
begin
print_single_space();
end;
end
else
begin
if (flags.mode = 'OBJECT') then
begin
print_token();
print_newline();
end
else
begin
// EXPR or DO_BLOCK
print_token();
print_single_space();
end;
end;
goto next_token;
end
else if (in_array(token_text, ['--', '++', '!']) or (in_array(token_text, ['-', '+']) and (in_array(last_type, ['TK_START_BLOCK', 'TK_START_EXPR', 'TK_EQUALS', 'TK_OPERATOR']) or in_array(last_text, line_starters)))) then
begin
// unary operators (and binary +/- pretending to be unary) special cases
space_before := false;
space_after := false;
if (last_text = ';') and is_expression(flags.mode) then
begin
// for (;; ++i)
// ^^^
space_before := true;
end;
if (last_type = 'TK_WORD') and in_array(last_text, line_starters) then
begin
space_before := true;
end;
if (flags.mode = 'BLOCK') and ((last_text = '{') or (last_text = ';')) then
begin
// begin foo; --i end;
// foo(); --bar;
print_newline();
end;
end
else if (token_text = '.') then
begin
// decimal digits or object.property
space_before := false;
end
else if (token_text = ':') then
begin
if (not is_ternary_op()) then
begin
flags.mode := 'OBJECT';
space_before := false;
end;
end;
if (space_before) then
begin
print_single_space();
end;
print_token();
if (space_after) then
begin
print_single_space();
end;
if (token_text = '!') then
begin
// flags.eat_next_space = true;
end;
end
else if token_type = 'TK_BLOCK_COMMENT' then
begin
lines := split(StringReplace(token_text, #13#10, #10, [rfReplaceAll]), #10);
if (Pos('/**', token_text) > 0) then
begin
// javadoc: reformat and reindent
print_newline();
output.add(lines[0]);
for i := 1 to high(lines) do
begin
print_newline();
output.add(' ');
output.add(Trim(lines[i]));
end;
end
else
begin
// simple block comment: leave intact
if (length(lines) > 1) then
begin
// multiline comment block starts with a new line
print_newline();
trim_output();
end
else
begin
// single-line /* comment */ stays where it is
print_single_space();
end;
for i := 0 to high(lines) do
begin
output.add(lines[i]);
output.add(#10);
end;
end;
print_newline();
end
else if token_type = 'TK_INLINE_COMMENT' then
begin
print_single_space();
print_token();
if (is_expression(flags.mode)) then
begin
print_single_space();
end
else
begin
print_newline();
end;
end
else if token_type = 'TK_COMMENT' then
begin
// print_newline();
if (wanted_newline) then
begin
print_newline();
end
else
begin
print_single_space();
end;
print_token();
print_newline();
end
else if token_type = 'TK_UNKNOWN' then
begin
if (last_text = 'return') or (last_text = 'throw') then
print_single_space();
print_token();
end;
next_token:
last_last_text := last_text;
last_type := token_type;
last_text := token_text;
end;
result := join(output);
if Copy(result, Length(Result), 1)=#10 then
result:=Copy(result, 1, Length(Result)-1);
result := StringReplace(result, #10, #13#10, [rfReplaceAll]);
end;
procedure Tjs_beautify.trim_output(eat_newlines:Boolean = false);
begin
while ((output.Count > 0) and ((output.Strings[output.Count - 1] = ' ')
or (output.Strings[output.Count - 1] = indent_string) or
(eat_newlines and ((output.Strings[output.Count - 1] = #10) or (output.Strings[output.Count - 1] = #13))))) do
begin
output.Delete(output.Count - 1);
end;
end;
function Tjs_beautify.is_array(mode: string): Boolean;
begin
result := (mode = '[EXPRESSION]') or (mode = '[INDENTED-EXPRESSION]');
end;
procedure Tjs_beautify.print_newline(ignore_repeated: Boolean = true);
var
i: Integer;
begin
flags.eat_next_space := false;
if (opt_keep_array_indentation and is_array(flags.mode)) then
begin
exit;
end;
flags.if_line := false;
trim_output();
if (output.Count = 0) then
begin
exit; // no newline on start of file
end;
if ((output.Strings[output.Count - 1] <> #10) or not ignore_repeated) then
begin
just_added_newline := true;
output.add(#10);
end;
for i := 0 to flags.indentation_level - 1 do
begin
output.add(indent_string);
end;
if (flags.var_line and flags.var_line_reindented) then
begin
if (opt_indent_char = ' ') then
begin
output.add(' '); // var_line always pushes 4 spaces, so that the variables would be one under another
end
else
begin
output.add(indent_string); // skip space-stuffing, if indenting with a tab
end;
end;
end;
procedure Tjs_beautify.print_single_space;
var
last_output: string;
begin
if (flags.eat_next_space) then
begin
flags.eat_next_space := false;
exit;
end;
last_output := ' ';
if (output.count > 0) then
begin
last_output := output.Strings[output.count - 1];
end;
if ((last_output <> ' ') and (last_output <> #10) and (last_output <> indent_string)) then
begin // prevent occassional duplicate space
output.add(' ');
end;
end;
procedure Tjs_beautify.print_token;
begin
just_added_newline := false;
flags.eat_next_space := false;
output.add(token_text);
end;
procedure Tjs_beautify.indent;
begin
Inc(flags.indentation_level);
end;
procedure Tjs_beautify.remove_indent;
begin
if ((output.count > 0) and (output.Strings[output.count - 1] = indent_string)) then
begin
output.Delete(output.Count - 1);
end;
end;
procedure Tjs_beautify.set_mode(mode: string);
var
newflags: TFlags;
begin
flag_store.AddObject('', flags);
newflags := TFlags.Create;
newflags.previous_mode := flags.mode;
newflags.mode := mode;
newflags.var_line := false;
newflags.var_line_tainted := false;
newflags.var_line_reindented := false;
newflags.in_html_comment := false;
newflags.if_line := false;
newflags.in_case := false;
newflags.eat_next_space := false;
newflags.indentation_baseline := -1;
newflags.indentation_level := flags.indentation_level;
if flags.var_line and flags.var_line_reindented then
Inc(newflags.indentation_level);
flags := newflags;
end;
function Tjs_beautify.is_expression(mode: string): Boolean;
begin
result := (mode = '[EXPRESSION]') or (mode = '[INDENTED-EXPRESSION]') or (mode = '(EXPRESSION)');
end;
procedure Tjs_beautify.restore_mode;
begin
do_block_just_closed := (flags.mode = 'DO_BLOCK');
flags.mode := 'DO_BLOCK';
if (flag_store.count > 0) then
begin
flags.free();
flags := TFlags(flag_store.Objects[flag_store.Count - 1]);
flag_store.Delete(flag_store.Count - 1);
end;
end;
// Walk backwards from the colon to find a '?' (colon is part of a ternary op)
// or a '{' (colon is part of a class literal). Along the way, keep track of
// the blocks and expressions we pass so we only trigger on those chars in our
// own level, and keep track of the colons so we only trigger on the matching '?'.
function Tjs_beautify.is_ternary_op(): Boolean;
var
i, level, colon_count: Integer;
begin
result := false;
level := 0;
colon_count := 0;
for i := output.count - 1 downto 0 do
begin
if output.Strings[i] = ':' then
begin
if (level = 0) then
begin
Inc(colon_count);
end;
end
else if output.Strings[i] = '?' then
begin
if (level = 0) then
begin
if (colon_count = 0) then
begin
result := true;
Exit;
end
else
begin
Dec(colon_count);
end;
end;
end
else if output.Strings[i] = '{' then
begin
if (level = 0) then
begin
result := false;
Exit;
end;
Dec(level);
end
else if in_array(output.Strings[i], ['(', '[']) then
Dec(level)
else if in_array(output.Strings[i], ['}', ')', ']']) then
inc(level)
end;
end;
function Tjs_beautify.get_next_token(): TToken;
var
c: string;
keep_whitespace: Boolean;
whitespace_count, i: Integer;
sign, comment: string;
t: TToken;
inline_comment: boolean;
tmp_float: Extended;
sep, resulting_string: string;
esc, in_char_class: boolean;
sharp: string;
begin
n_newlines := 0;
if (parser_pos >= input_length) then
begin
result[0] := '';
result[1] := 'TK_EOF';
Exit;
end;
wanted_newline := false;
c := input[parser_pos + 1];
Inc(parser_pos);
keep_whitespace := opt_keep_array_indentation and is_array(flags.mode);
if (keep_whitespace) then
begin
//
// slight mess to allow nice preservation of array indentation and reindent that correctly
// first time when we get to the arrays:
// var a = [
// ....'something'
// we make note of whitespace_count = 4 into flags.indentation_baseline
// so we know that 4 whitespaces in original source match indent_level of reindented source
//
// and afterwards, when we get to
// 'something,
// .......'something else'
// we know that this should be indented to indent_level + (7 - indentation_baseline) spaces
//
whitespace_count := 0;
while (in_array(c, whitespace)) do
begin
if (c = #10) then
begin
trim_output();
output.add(#10);
just_added_newline := true;
whitespace_count := 0;
end
else
begin
if (c = #9) then
begin
Inc(whitespace_count, 4);
end
else if c = #10 then
begin
//nothing
end
else
begin
Inc(whitespace_count, 1);
end;
end;
if (parser_pos >= input_length) then
begin
result[0] := '';
result[1] := 'TK_EOF';
Exit;
end;
c := input[parser_pos + 1];
Inc(parser_pos);
end;
if (flags.indentation_baseline = -1) then
begin
flags.indentation_baseline := whitespace_count;
end;
if (just_added_newline) then
begin
for i := 0 to flags.indentation_level do
begin
output.add(indent_string);
end;
if (flags.indentation_baseline <> -1) then
begin
for i := 0 to whitespace_count - flags.indentation_baseline - 1 do
begin
output.add(' ');
end;
end;
end;
end
else
begin
while (in_array(c, whitespace)) do
begin
if (c = #10) then
begin
if opt_max_preserve_newlines > 0 then
begin
if n_newlines <= opt_max_preserve_newlines then Inc(n_newlines);
end
else
Inc(n_newlines);
end;
if (parser_pos >= input_length) then
begin
result[0] := '';
result[1] := 'TK_EOF';
Exit;
end;
c := input[parser_pos + 1];
Inc(parser_pos);
end;
if (opt_preserve_newlines) then
begin
if (n_newlines > 1) then
begin
for i := 0 to n_newlines - 1 do
begin
print_newline(i = 0);
just_added_newline := true;
end;
end;
end;
wanted_newline := n_newlines > 0;
end;
if (in_array(c, wordchar)) then
begin
if (parser_pos < input_length) then
begin
while (in_array(input[parser_pos + 1], wordchar)) do
begin
c := c + input[parser_pos + 1];
Inc(parser_pos);
if (parser_pos = input_length) then
begin
break;
end;
end;
end;
// small and surprisingly unugly hack for 1E-10 representation
if (parser_pos <> input_length) and in_array(Copy(c, length(c), 1), ['e', 'E']) and
TryStrToFloat(Copy(c, 1, length(c) - 1), tmp_float) and
in_array(input[parser_pos + 1], ['-', '+']) then
begin
sign := input[parser_pos + 1];
Inc(parser_pos);
t := get_next_token;
c := c + sign + t[0];
result[0] := c;
result[1] := 'TK_WORD';
Exit;
end;
if (c = 'in') then
begin // hack for 'in' operator
result[0] := c;
result[1] := 'TK_OPERATOR';
Exit;
end;
if (wanted_newline and (last_type <> 'TK_OPERATOR') and
not flags.if_line and (opt_preserve_newlines or (last_text <> 'var'))) then
begin
print_newline();
end;
result[0] := c;
result[1] := 'TK_WORD';
Exit;
end;
if (c = '(') or (c = '[') then
begin
result[0] := c;
result[1] := 'TK_START_EXPR';
Exit;
end;
if (c = ')') or (c = ']') then
begin
result[0] := c;
result[1] := 'TK_END_EXPR';
Exit;
end;
if (c = '{') then
begin
result[0] := c;
result[1] := 'TK_START_BLOCK';
Exit;
end;
if (c = '}') then
begin
result[0] := c;
result[1] := 'TK_END_BLOCK';
Exit;
end;
if (c = ';') then
begin
result[0] := c;
result[1] := 'TK_SEMICOLON';
Exit;
end;
if (c = '/') then
begin
comment := '';
// peek for comment /* ... */
inline_comment := true;
if (input[parser_pos + 1] = '*') then
begin
Inc(parser_pos);
if (parser_pos < input_length) then
begin
while not ((input[parser_pos + 1] = '*') and
(input[parser_pos + 2] = '/') and (parser_pos < input_length)) do
begin
c := input[parser_pos + 1];
comment := comment + c;
if (c = #13) or (c = #10) then
begin
inline_comment := false;
end;
Inc(parser_pos);
if (parser_pos >= input_length) then
begin
break;
end;
end;
end;
Inc(parser_pos, 2);
if (inline_comment) then
begin
result[0] := '/*' + comment + '*/';
result[1] := 'TK_INLINE_COMMENT';
Exit;
end
else
begin
result[0] := '/*' + comment + '*/';
result[1] := 'TK_BLOCK_COMMENT';
Exit;
end;
end;
// peek for comment // ...
if (input[parser_pos + 1] = '/') then
begin
comment := c;
while (input[parser_pos + 1] <> #13) and (input[parser_pos + 1] <> #10) do
begin
comment := comment + input[parser_pos + 1];
Inc(parser_pos);
if (parser_pos >= input_length) then
begin
break;
end;
end;
Inc(parser_pos);
if (wanted_newline) then
begin
print_newline();
end;
result[0] := comment;
result[1] := 'TK_COMMENT';
Exit;
end;
end;
if (c = '''') or // string
(c = '"') or // string
((c = '/') and (((last_type = 'TK_WORD') and in_array(last_text, ['return', 'do']))
or ((last_type = 'TK_START_EXPR') or (last_type = 'TK_START_BLOCK')
or (last_type = 'TK_END_BLOCK') or (last_type = 'TK_OPERATOR')
or (last_type = 'TK_EQUALS') or (last_type = 'TK_EOF')
or (last_type = 'TK_SEMICOLON') or (last_type = 'TK_COMMENT')))) then
begin // regexp
sep := c;
esc := false;
resulting_string := c;
if (parser_pos < input_length) then
begin
if (sep = '/') then
begin
//
// handle regexp separately...
//
in_char_class := false;
while (esc or in_char_class or (input[parser_pos + 1] <> sep)) do
begin
resulting_string := resulting_string + input[parser_pos + 1];
if (not esc) then
begin
esc := input[parser_pos + 1] = '\';
if (input[parser_pos + 1] = '[') then
begin
in_char_class := true;
end
else if (input[parser_pos + 1] = ']') then
begin
in_char_class := false;
end;
end
else
begin
esc := false;
end;
Inc(parser_pos);
if (parser_pos >= input_length) then
begin
// incomplete string/rexp when end-of-file reached.
// bail out with what had been received so far.
result[0] := resulting_string;
result[1] := 'TK_STRING';
Exit;
end;
end;
end
else
begin
//
// and handle string also separately
//
while (esc or (input[parser_pos + 1] <> sep)) do
begin
resulting_string := resulting_string + input[parser_pos + 1];
if (not esc) then
begin
esc := input[parser_pos + 1] = '\';
end
else
begin
esc := false;
end;
Inc(parser_pos);
if (parser_pos >= input_length) then
begin
// incomplete string/rexp when end-of-file reached.
// bail out with what had been received so far.
result[0] := resulting_string;
result[1] := 'TK_STRING';
Exit;
end;
end;
end;
end;
Inc(parser_pos);
resulting_string := resulting_string + sep;
if (sep = '/') then
begin
// regexps may have modifiers /regexp/MOD , so fetch those, too
while (parser_pos < input_length) and in_array(input[parser_pos + 1], wordchar) do
begin
resulting_string := resulting_string + input[parser_pos + 1];
Inc(parser_pos);
end;
end;
result[0] := resulting_string;
result[1] := 'TK_STRING';
Exit;
end;
if (c = '#') then
begin
// Spidermonkey-specific sharp variables for circular references
// https://developer.mozilla.org/En/Sharp_variables_in_JavaScript
// http://mxr.mozilla.org/mozilla-central/source/js/src/jsscan.cpp around line 1935
sharp := '#';
if (parser_pos < input_length) and in_array(input[parser_pos + 1], digits) then
begin
repeat
c := input[parser_pos + 1];
sharp := sharp + c;
Inc(parser_pos);
until not ((parser_pos < input_length) and (c <> '#') and (c <> '='));
if (c = '#') then
begin
//
end
else if (input[parser_pos + 1] = '[') and (input[parser_pos + 2] = ']') then
begin
sharp := sharp + '[]';
Inc(parser_pos, 2);
end
else if (input[parser_pos + 1] = '{') and (input[parser_pos + 2] = '}') then
begin
sharp := sharp + '{}';
Inc(parser_pos, 2);
end;
result[0] := sharp;
result[1] := 'TK_WORD';
Exit;
end;
end;
if (c = '<') and (Copy(input, parser_pos, 4) = '<!--') then
begin
Inc(parser_pos, 3);
flags.in_html_comment := true;
result[0] := '<!--';
result[1] := 'TK_COMMENT';
Exit;
end;
if (c = '-') and flags.in_html_comment and (Copy(input, parser_pos, 3) = '-->') then
begin
flags.in_html_comment := false;
Inc(parser_pos, 2);
if (wanted_newline) then
begin
print_newline();
end;
result[0] := '-->';
result[1] := 'TK_COMMENT';
Exit;
end;
if (in_array(c, punct)) then
begin
while (parser_pos < input_length) and in_array(c + input[parser_pos + 1], punct) do
begin
c := c + input[parser_pos + 1];
Inc(parser_pos);
if (parser_pos >= input_length) then
begin
break;
end;
end;
if (c = '=') then
begin
result[0] := c;
result[1] := 'TK_EQUALS';
Exit;
end
else
begin
result[0] := c;
result[1] := 'TK_OPERATOR';
Exit;
end;
end;
result[0] := c;
result[1] := 'TK_UNKNOWN';
Exit;
end;
function js_beautify(js_source_text: string;
indent_size: Integer = 4;
indent_char: Char = ' ';
preserve_newlines: Boolean = True;
max_preserve_newlines: Integer = 0;
indent_level: Integer = 0;
space_after_anon_function: Boolean = False;
braces_on_own_line: Boolean = False;
keep_array_indentation: Boolean = False):string;
var jsb:Tjs_beautify;
begin
jsb := Tjs_beautify.Create(
js_source_text,
indent_size,
indent_char,
preserve_newlines,
max_preserve_newlines,
indent_level,
space_after_anon_function,
braces_on_own_line,
keep_array_indentation
);
result:=jsb.getBeauty;
jsb.free;
end;
end.
|
unit unit_pas2c64_symboltable;
{$MODE Delphi}
interface
uses
Classes;
const
cSymClass_None = -1;
cSymClass_Constant = 0;
cSymClass_Variable = 1;
cSymClass_Procedure = 2;
cSymClass_Function = 3;
cSymClass_Interrupt = 4;
cSymClass_AsmProc = 5;
cSymSubClass_None = -1;
cSymSubClass_SInt8 = 0;
cSymSubClass_SInt16 = 1;
cSymSubClass_SInt32 = 2;
cSymSubClass_UInt8 = 3;
cSymSubClass_UInt16 = 4;
cSymSubClass_UInt32 = 5;
cSymSubClass_Float = 6;
cSymSubClass_String = 7;
type
TSymbol = class
SymbolClass: Integer;
SymbolSubClass: Integer;
SymbolName: AnsiString;
SymbolValue: AnsiString;
end;
TPas2C64_SymbolTable = class
private
FSymbolTable: TStringList;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function AddSymbol(const aName,aValue: AnsiString; const aClass,aSubClass: Integer): TSymbol;
function SymbolExists(const aName: AnsiString): Boolean;
function GetSymbol(const aName: AnsiString): TSymbol;
end;
implementation
uses
SysUtils;
constructor TPas2C64_SymbolTable.Create;
begin
inherited Create;
FSymbolTable := TStringList.Create;
FSymbolTable.Sorted := True;
FSymbolTable.Duplicates := dupIgnore;
end;
destructor TPas2C64_SymbolTable.Destroy;
begin
Clear;
FSymbolTable.Free;
inherited Destroy;
end;
procedure TPas2C64_SymbolTable.Clear;
var
i: Integer;
begin
for i := 0 to FSymbolTable.Count - 1 do
TSymbol(FSymbolTable.Objects[i]).Free;
FSymbolTable.Clear;
end;
function TPas2C64_SymbolTable.AddSymbol(const aName,aValue: AnsiString; const aClass,aSubClass: Integer): TSymbol;
var
Index: Integer;
begin
Result := nil;
if FSymbolTable.Find(LowerCase(aName),Index) then
raise Exception.Create('Symbol "'+aName+'" already exists!');
Result := TSymbol.Create;
Result.SymbolName := LowerCase(aName);
Result.SymbolValue := aValue;
Result.SymbolClass := aClass;
Result.SymbolSubClass := aSubClass;
FSymbolTable.AddObject(LowerCase(aName),Result);
end;
function TPas2C64_SymbolTable.SymbolExists(const aName: AnsiString): Boolean;
var
Index: Integer;
begin
Result := FSymbolTable.Find(LowerCase(aName),Index);
end;
function TPas2C64_SymbolTable.GetSymbol(const aName: AnsiString): TSymbol;
var
Index: Integer;
begin
Result := nil;
if not FSymbolTable.Find(LowerCase(aName),Index) then Exit;
Result := TSymbol(FSymbolTable.Objects[Index]);
end;
end.
|
Unit AdvIntegerObjectMatches;
{
Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
MemorySupport, MathSupport, StringSupport,
AdvObjects, AdvItems, AdvFilers;
Type
TAdvIntegerObjectMatchKey = Integer;
TAdvIntegerObjectMatchValue = TAdvObject;
TAdvIntegerObjectMatchItem = Record
Key : TAdvIntegerObjectMatchKey;
Value : TAdvIntegerObjectMatchValue;
End;
PAdvIntegerObjectMatchItem = ^TAdvIntegerObjectMatchItem;
TAdvIntegerObjectMatchItemArray = Array[0..(MaxInt Div SizeOf(TAdvIntegerObjectMatchItem)) - 1] Of TAdvIntegerObjectMatchItem;
PAdvIntegerObjectMatchItemArray = ^TAdvIntegerObjectMatchItemArray;
TAdvIntegerObjectMatch = Class(TAdvItems)
Private
FItemArray : PAdvIntegerObjectMatchItemArray;
FDefaultKey : TAdvIntegerObjectMatchKey;
FDefaultValue : TAdvIntegerObjectMatchValue;
FNominatedValueClass : TAdvObjectClass;
FForced : Boolean;
Function GetKeyByIndex(iIndex: Integer): TAdvIntegerObjectMatchKey;
Procedure SetKeyByIndex(iIndex: Integer; Const aKey : TAdvIntegerObjectMatchKey);
Function GetValueByIndex(iIndex: Integer): TAdvIntegerObjectMatchValue;
Procedure SetValueByIndex(iIndex: Integer; Const aValue: TAdvIntegerObjectMatchValue);
Function GetMatchByIndex(iIndex: Integer): TAdvIntegerObjectMatchItem;
Protected
Function GetItem(iIndex : Integer) : Pointer; Override;
Procedure SetItem(iIndex : Integer; pValue: Pointer); Override;
Procedure SaveItem(oFiler : TAdvFiler; iIndex : Integer); Override;
Procedure LoadItem(oFiler : TAdvFiler; iIndex : Integer); Override;
Procedure AssignItem(oItems : TAdvItems; iIndex : Integer); Override;
Procedure InternalTruncate(iValue : Integer); Override;
Procedure InternalResize(iValue : Integer); Override;
Procedure InternalCopy(iSource, iTarget, iCount : Integer); Override;
Procedure InternalEmpty(iIndex, iLength : Integer); Override;
Procedure InternalInsert(iIndex : Integer); Overload; Override;
Procedure InternalDelete(iIndex : Integer); Overload; Override;
Procedure InternalExchange(iA, iB : Integer); Overload; Override;
Function CompareByKey(pA, pB : Pointer): Integer; Virtual;
Function CompareByValue(pA, pB : Pointer): Integer; Virtual;
Procedure DefaultCompare(Out aCompare : TAdvItemsCompare); Overload; Override;
Function Find(Const aKey : TAdvIntegerObjectMatchKey; Const aValue : TAdvIntegerObjectMatchValue; Out iIndex : Integer; aCompare : TAdvItemsCompare = Nil) : Boolean; Overload;
Function CapacityLimit : Integer; Override;
Function ValidateIndex(Const sMethod: String; iIndex: Integer): Boolean; Overload; Override;
Function ValidateValue(Const sMethod: String; oObject: TAdvObject; Const sObject: String): Boolean; Virtual;
Function ItemClass : TAdvObjectClass;
Public
Constructor Create; Override;
Destructor Destroy; Override;
Function Link : TAdvIntegerObjectMatch;
Function Add(Const aKey : TAdvIntegerObjectMatchKey; Const aValue : TAdvIntegerObjectMatchValue): Integer;
Procedure AddAll(Const oIntegerObjectMatch : TAdvIntegerObjectMatch);
Procedure Insert(iIndex : Integer; Const aKey : TAdvIntegerObjectMatchKey; Const aValue : TAdvIntegerObjectMatchValue);
Function IndexByKey(Const aKey : TAdvIntegerObjectMatchKey) : Integer;
Function IndexByValue(Const aValue : TAdvIntegerObjectMatchValue) : Integer;
Function ExistsByKey(Const aKey : TAdvIntegerObjectMatchKey) : Boolean;
Function ExistsByValue(Const aValue : TAdvIntegerObjectMatchValue) : Boolean;
Procedure SortedByValue;
Procedure SortedByKey;
Function IsSortedByKey : Boolean;
Function IsSortedByValue : Boolean;
Function GetKeyByValue(Const aValue : TAdvIntegerObjectMatchValue) : TAdvIntegerObjectMatchKey;
Function GetValueByKey(Const aKey : TAdvIntegerObjectMatchKey) : TAdvIntegerObjectMatchValue;
Procedure SetValueByKey(Const aKey : TAdvIntegerObjectMatchKey; Const aValue: TAdvIntegerObjectMatchValue);
Procedure DeleteByKey(Const aKey : TAdvIntegerObjectMatchKey);
Procedure DeleteByValue(Const aValue : TAdvIntegerObjectMatchValue);
Property Forced : Boolean Read FForced Write FForced;
Property DefaultKey : TAdvIntegerObjectMatchKey Read FDefaultKey Write FDefaultKey;
Property DefaultValue : TAdvIntegerObjectMatchValue Read FDefaultValue Write FDefaultValue;
Property NominatedValueClass : TAdvObjectClass Read FNominatedValueClass Write FNominatedValueClass;
Property MatchByIndex[iIndex : Integer] : TAdvIntegerObjectMatchItem Read GetMatchByIndex; Default;
Property KeyByIndex[iIndex : Integer] : TAdvIntegerObjectMatchKey Read GetKeyByIndex Write SetKeyByIndex;
Property ValueByIndex[iIndex : Integer] : TAdvIntegerObjectMatchValue Read GetValueByIndex Write SetValueByIndex;
End;
Implementation
Constructor TAdvIntegerObjectMatch.Create;
Begin
Inherited;
FNominatedValueClass := ItemClass;
End;
Destructor TAdvIntegerObjectMatch.Destroy;
Begin
Inherited;
End;
Function TAdvIntegerObjectMatch.Link : TAdvIntegerObjectMatch;
Begin
Result := TAdvIntegerObjectMatch(Inherited Link);
End;
Function TAdvIntegerObjectMatch.CompareByKey(pA, pB: Pointer): Integer;
Begin
Result := IntegerCompare(PAdvIntegerObjectMatchItem(pA)^.Key, PAdvIntegerObjectMatchItem(pB)^.Key);
End;
Function TAdvIntegerObjectMatch.CompareByValue(pA, pB: Pointer): Integer;
Begin
Result := IntegerCompare(Integer(PAdvIntegerObjectMatchItem(pA)^.Value), Integer(PAdvIntegerObjectMatchItem(pB)^.Value));
End;
Procedure TAdvIntegerObjectMatch.SaveItem(oFiler: TAdvFiler; iIndex: Integer);
Begin
oFiler['Match'].DefineBegin;
oFiler['Key'].DefineInteger(FItemArray^[iIndex].Key);
oFiler['Value'].DefineObject(FItemArray^[iIndex].Value);
oFiler['Match'].DefineEnd;
End;
Procedure TAdvIntegerObjectMatch.LoadItem(oFiler: TAdvFiler; iIndex: Integer);
Var
iKey : TAdvIntegerObjectMatchKey;
oValue : TAdvIntegerObjectMatchValue;
Begin
oValue := Nil;
Try
oFiler['Match'].DefineBegin;
oFiler['Key'].DefineInteger(iKey);
oFiler['Value'].DefineObject(oValue);
oFiler['Match'].DefineEnd;
Add(iKey, oValue.Link);
Finally
oValue.Free;
End;
End;
Procedure TAdvIntegerObjectMatch.AssignItem(oItems : TAdvItems; iIndex: Integer);
Begin
Inherited;
FItemArray^[iIndex].Key := TAdvIntegerObjectMatch(oItems).FItemArray^[iIndex].Key;
FItemArray^[iIndex].Value := TAdvIntegerObjectMatch(oItems).FItemArray^[iIndex].Value.Clone;
End;
Procedure TAdvIntegerObjectMatch.InternalEmpty(iIndex, iLength : Integer);
Begin
Inherited;
MemoryZero(Pointer(NativeUInt(FItemArray) + (iIndex * SizeOf(TAdvIntegerObjectMatchItem))), (iLength * SizeOf(TAdvIntegerObjectMatchItem)));
End;
Procedure TAdvIntegerObjectMatch.InternalTruncate(iValue : Integer);
Var
iLoop : Integer;
oValue : TAdvObject;
Begin
Inherited;
For iLoop := iValue To Count - 1 Do
Begin
oValue := FItemArray^[iLoop].Value;
FItemArray^[iLoop].Value := Nil;
oValue.Free;
End;
End;
Procedure TAdvIntegerObjectMatch.InternalResize(iValue : Integer);
Begin
Inherited;
MemoryResize(FItemArray, Capacity * SizeOf(TAdvIntegerObjectMatchItem), iValue * SizeOf(TAdvIntegerObjectMatchItem));
End;
Procedure TAdvIntegerObjectMatch.InternalCopy(iSource, iTarget, iCount: Integer);
Begin
MemoryMove(@FItemArray^[iSource], @FItemArray^[iTarget], iCount * SizeOf(TAdvIntegerObjectMatchItem));
End;
Function TAdvIntegerObjectMatch.IndexByKey(Const aKey : TAdvIntegerObjectMatchKey): Integer;
Begin
If Not Find(aKey, Nil, Result, CompareByKey) Then
Result := -1;
End;
Function TAdvIntegerObjectMatch.IndexByValue(Const aValue : TAdvIntegerObjectMatchValue): Integer;
Begin
If Not Find(0, aValue, Result, CompareByValue) Then
Result := -1;
End;
Function TAdvIntegerObjectMatch.ExistsByKey(Const aKey : TAdvIntegerObjectMatchKey): Boolean;
Begin
Result := ExistsByIndex(IndexByKey(aKey));
End;
Function TAdvIntegerObjectMatch.ExistsByValue(Const aValue : TAdvIntegerObjectMatchValue): Boolean;
Begin
Result := ExistsByIndex(IndexByValue(aValue));
End;
Function TAdvIntegerObjectMatch.Add(Const aKey : TAdvIntegerObjectMatchKey; Const aValue : TAdvIntegerObjectMatchValue) : Integer;
Begin
Assert(ValidateValue('Add', aValue, 'aValue'));
Result := -1;
If Not IsAllowDuplicates And Find(aKey, aValue, Result) Then
Begin
aValue.Free; // free ignored object
If IsPreventDuplicates Then
RaiseError('Add', StringFormat('Item already exists in list (%d=%x)', [aKey, Integer(aValue)]));
// Result is the index of the existing key
End
Else
Begin
If Not IsSorted Then
Result := Count
Else If (Result < 0) Then
Find(aKey, aValue, Result);
Insert(Result, aKey, aValue);
End;
End;
Procedure TAdvIntegerObjectMatch.AddAll(Const oIntegerObjectMatch : TAdvIntegerObjectMatch);
Var
iIntegerObjectMatchIndex : Integer;
Begin
Assert(Invariants('AddAll', oIntegerObjectMatch, TAdvIntegerObjectMatch, 'oIntegerObjectMatch'));
For iIntegerObjectMatchIndex := 0 To oIntegerObjectMatch.Count - 1 Do
Add(oIntegerObjectMatch.KeyByIndex[iIntegerObjectMatchIndex], oIntegerObjectMatch.ValueByIndex[iIntegerObjectMatchIndex].Link);
End;
Procedure TAdvIntegerObjectMatch.Insert(iIndex : Integer; Const aKey : TAdvIntegerObjectMatchKey; Const aValue : TAdvIntegerObjectMatchValue);
Begin
Assert(ValidateValue('Insert', aValue, 'aValue'));
InternalInsert(iIndex);
FItemArray^[iIndex].Key := aKey;
FItemArray^[iIndex].Value := aValue;
End;
Procedure TAdvIntegerObjectMatch.InternalInsert(iIndex : Integer);
Begin
Inherited;
Integer(FItemArray^[iIndex].Key) := 0;
Pointer(FItemArray^[iIndex].Value) := Nil;
End;
Procedure TAdvIntegerObjectMatch.InternalDelete(iIndex : Integer);
Begin
Inherited;
FItemArray^[iIndex].Value.Free;
FItemArray^[iIndex].Value := Nil;
End;
Procedure TAdvIntegerObjectMatch.InternalExchange(iA, iB: Integer);
Var
aTemp : TAdvIntegerObjectMatchItem;
pA : PAdvIntegerObjectMatchItem;
pB : PAdvIntegerObjectMatchItem;
Begin
pA := @FItemArray^[iA];
pB := @FItemArray^[iB];
aTemp := pA^;
pA^ := pB^;
pB^ := aTemp;
End;
Function TAdvIntegerObjectMatch.GetItem(iIndex : Integer) : Pointer;
Begin
Assert(ValidateIndex('GetItem', iIndex));
Result := @FItemArray^[iIndex];
End;
Procedure TAdvIntegerObjectMatch.SetItem(iIndex: Integer; pValue: Pointer);
Begin
Assert(ValidateIndex('SetItem', iIndex));
FItemArray^[iIndex] := PAdvIntegerObjectMatchItem(pValue)^;
End;
Function TAdvIntegerObjectMatch.GetKeyByIndex(iIndex : Integer): TAdvIntegerObjectMatchKey;
Begin
Assert(ValidateIndex('GetKeyByIndex', iIndex));
Result := FItemArray^[iIndex].Key;
End;
Procedure TAdvIntegerObjectMatch.SetKeyByIndex(iIndex : Integer; Const aKey : TAdvIntegerObjectMatchKey);
Begin
Assert(ValidateIndex('SetKeyByIndex', iIndex));
FItemArray^[iIndex].Key := aKey;
End;
Function TAdvIntegerObjectMatch.GetValueByIndex(iIndex : Integer): TAdvIntegerObjectMatchValue;
Begin
Assert(ValidateIndex('GetValueByIndex', iIndex));
Result := FItemArray^[iIndex].Value;
End;
Procedure TAdvIntegerObjectMatch.SetValueByIndex(iIndex : Integer; Const aValue: TAdvIntegerObjectMatchValue);
Begin
Assert(ValidateIndex('SetValueByIndex', iIndex));
Assert(ValidateValue('SetValueByIndex', aValue, 'aValue'));
FItemArray^[iIndex].Value.Free;
FItemArray^[iIndex].Value := aValue;
End;
Function TAdvIntegerObjectMatch.GetKeyByValue(Const aValue: TAdvIntegerObjectMatchValue): TAdvIntegerObjectMatchKey;
Var
iIndex : Integer;
Begin
iIndex := IndexByValue(aValue);
If ExistsByIndex(iIndex) Then
Result := KeyByIndex[iIndex]
Else If Forced Then
Result := DefaultKey
Else
Begin
RaiseError('GetKeyByValue', 'Could not find key by value.');
Result := 0;
End;
End;
Function TAdvIntegerObjectMatch.GetValueByKey(Const aKey : TAdvIntegerObjectMatchKey): TAdvIntegerObjectMatchValue;
Var
iIndex : Integer;
Begin
iIndex := IndexByKey(aKey);
If ExistsByIndex(iIndex) Then
Result := ValueByIndex[iIndex]
Else If FForced Then
Result := DefaultValue
Else
Begin
RaiseError('GetValueByKey', StringFormat('Unable to get the value for the specified key ''%d''.', [aKey]));
Result := Nil;
End;
End;
Procedure TAdvIntegerObjectMatch.SetValueByKey(Const aKey : TAdvIntegerObjectMatchKey; Const aValue : TAdvIntegerObjectMatchValue);
Var
iIndex : Integer;
Begin
Assert(ValidateValue('SetValueByKey', aValue, 'aValue'));
iIndex := IndexByKey(aKey);
If ExistsByIndex(iIndex) Then
ValueByIndex[iIndex] := aValue
Else If FForced Then
Add(aKey, aValue)
Else
RaiseError('SetValueByKey', 'Unable to set the value for the specified key.');
End;
Function TAdvIntegerObjectMatch.CapacityLimit : Integer;
Begin
Result := High(TAdvIntegerObjectMatchItemArray);
End;
Procedure TAdvIntegerObjectMatch.DefaultCompare(Out aCompare: TAdvItemsCompare);
Begin
aCompare := CompareByKey;
End;
Function TAdvIntegerObjectMatch.Find(Const aKey: TAdvIntegerObjectMatchKey; Const aValue: TAdvIntegerObjectMatchValue; Out iIndex: Integer; aCompare: TAdvItemsCompare): Boolean;
Var
aItem : TAdvIntegerObjectMatchItem;
Begin
aItem.Key := aKey;
aItem.Value := aValue;
Result := Inherited Find(@aItem, iIndex, aCompare);
End;
Procedure TAdvIntegerObjectMatch.SortedByKey;
Begin
SortedBy(CompareByKey);
End;
Procedure TAdvIntegerObjectMatch.SortedByValue;
Begin
SortedBy(CompareByValue);
End;
Function TAdvIntegerObjectMatch.ItemClass : TAdvObjectClass;
Begin
Result := TAdvObject;
End;
Function TAdvIntegerObjectMatch.ValidateIndex(Const sMethod : String; iIndex: Integer): Boolean;
Begin
Inherited ValidateIndex(sMethod, iIndex);
ValidateValue(sMethod, FItemArray^[iIndex].Value, 'FItemArray^[' + IntegerToString(iIndex) + '].Value');
Result := True;
End;
Function TAdvIntegerObjectMatch.ValidateValue(Const sMethod : String; oObject : TAdvObject; Const sObject : String) : Boolean;
Begin
If Assigned(oObject) Then
Invariants(sMethod, oObject, FNominatedValueClass, sObject);
Result := True;
End;
Function TAdvIntegerObjectMatch.IsSortedByKey : Boolean;
Begin
Result := IsSortedBy(CompareByKey);
End;
Function TAdvIntegerObjectMatch.IsSortedByValue : Boolean;
Begin
Result := IsSortedBy(CompareByValue);
End;
Procedure TAdvIntegerObjectMatch.DeleteByKey(Const aKey: TAdvIntegerObjectMatchKey);
Begin
DeleteByIndex(IndexByKey(aKey));
End;
Procedure TAdvIntegerObjectMatch.DeleteByValue(Const aValue: TAdvIntegerObjectMatchValue);
Begin
DeleteByIndex(IndexByValue(aValue));
End;
Function TAdvIntegerObjectMatch.GetMatchByIndex(iIndex: Integer): TAdvIntegerObjectMatchItem;
Begin
Assert(ValidateIndex('GetMatchByIndex', iIndex));
Result := FItemArray^[iIndex];
End;
End. // AdvIntegerObjectMatches //
|
unit uNetworkTools;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
uForm, ICSLanguages, Vcl.StdCtrls, DosCommand, XMLIntf, Vcl.ExtCtrls,
System.Actions, Vcl.ActnList,
uClasses, System.ImageList, Vcl.ImgList, PngImageList, Vcl.Buttons,
PngBitBtn, Vcl.ComCtrls;
type
TfrmNetworkTools = class(TfrmForm)
MemoLog: TMemo;
DosCommandPing: TDosCommand;
leHost: TLabeledEdit;
btnStart: TPngBitBtn;
btnStop: TPngBitBtn;
btnClose: TPngBitBtn;
cbContinuously: TCheckBox;
ActionList1: TActionList;
ActionClose: TAction;
ActionStart: TAction;
ActionStop: TAction;
TimerStatus: TTimer;
cbTools: TComboBoxEx;
Label1: TLabel;
PngImageList1: TPngImageList;
PngImageListTool: TPngImageList;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ActionCloseExecute(Sender: TObject);
procedure ActionStartUpdate(Sender: TObject);
procedure ActionStopUpdate(Sender: TObject);
procedure ActionStopExecute(Sender: TObject);
procedure ActionStartExecute(Sender: TObject);
procedure TimerStatusTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure DosCommandPingNewChar(ASender: TObject; ANewChar: Char);
procedure cbToolsChange(Sender: TObject);
private
FXMLNode: IXMLNode;
FNetworkTool: TARNetworkTool;
procedure InitializePing;
procedure SetControlEnables;
public
property XMLNode: IXMLNode read FXMLNode write FXMLNode;
property NetworkTool: TARNetworkTool read FNetworkTool write FNetworkTool;
end;
var
frmNetworkTools: TfrmNetworkTools;
implementation
{$R *.dfm}
uses
uXMLTools;
procedure TfrmNetworkTools.ActionCloseExecute(Sender: TObject);
begin
inherited;
Close;
end;
procedure TfrmNetworkTools.ActionStartExecute(Sender: TObject);
begin
inherited;
InitializePing;
DosCommandPing.Execute;
TimerStatus.Enabled := True;
end;
procedure TfrmNetworkTools.ActionStartUpdate(Sender: TObject);
begin
inherited;
(Sender as TAction).Enabled := (leHost.Text <> '') and not DosCommandPing.IsRunning;
end;
procedure TfrmNetworkTools.ActionStopExecute(Sender: TObject);
begin
inherited;
TimerStatus.Enabled := False;
if DosCommandPing.IsRunning then DosCommandPing.Stop;
end;
procedure TfrmNetworkTools.ActionStopUpdate(Sender: TObject);
begin
inherited;
(Sender as TAction).Enabled := DosCommandPing.IsRunning;
end;
procedure TfrmNetworkTools.cbToolsChange(Sender: TObject);
begin
inherited;
DosCommandPing.Stop;
if cbTools.ItemIndex >= 0 then SetControlEnables;
end;
procedure TfrmNetworkTools.DosCommandPingNewChar(ASender: TObject; ANewChar: Char);
begin
inherited;
if ANewChar <> #10 then MemoLog.Lines.Text := MemoLog.Lines.Text + ANewChar;
end;
procedure TfrmNetworkTools.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
if DosCommandPing.IsRunning then DosCommandPing.Stop;
Action := caFree;
end;
procedure TfrmNetworkTools.FormCreate(Sender: TObject);
begin
inherited;
FXMLNode := nil;
FNetworkTool := ntPing;
end;
procedure TfrmNetworkTools.FormShow(Sender: TObject);
begin
inherited;
leHost.Text := xmlGetItemString(FXMLNode.ChildNodes[ND_HOST], ND_PARAM_VALUE);
cbTools.ItemIndex := Ord(FNetworkTool);
SetControlEnables;
UpdateActions;
if ActionStart.Enabled then ActionStart.Execute;
end;
procedure TfrmNetworkTools.InitializePing;
var CMD: String;
begin
MemoLog.Lines.Clear;
case TARNetworkTool(cbTools.ItemIndex) of
ntPing: begin
CMD := 'ping ';
if cbContinuously.Checked then CMD := CMD + '-t ';
CMD := CMD + leHost.Text;
end;
ntTracert: CMD := 'tracert ' + leHost.Text;
end;
DosCommandPing.CommandLine := CMD;
MemoLog.Lines.Add(ICSLanguages1.CurrentStrings[7] + ' ' + CMD);
end;
procedure TfrmNetworkTools.SetControlEnables;
begin
cbContinuously.Enabled := (TARNetworkTool(cbTools.ItemIndex) in [ntPing]);
end;
procedure TfrmNetworkTools.TimerStatusTimer(Sender: TObject);
begin
inherited;
if DosCommandPing.EndStatus <> esStill_Active then ActionStop.Execute;
end;
end.
|
unit DemoUtils;
interface
uses
Controls, ComCtrls;
function PadChar(const Source: string; Width: Integer; PadCh: Char) : string;
function LPadChar(const Source: string; Width: Integer; PadCh: Char) : string;
function Pad(const Source: string; Width: Integer) : string;
function LPad(const Source: string; Width: Integer) : string;
function Commaize(Value: Integer) : string;
procedure OpenPrim(S: string);
procedure MailTo(const Address, Subject: string);
function FindChildNode(Item: TTreeNode; const CaptionText: string) : TTreeNode;
function FindItemCaption(ListView: TListView; const Caption: string) : TListItem;
function GetFirstItem(ListView: TListView) : TListItem;
procedure SelectFirstItem(ListView: TListView);
procedure ControlColorCheck(Controls: array of TControl);
implementation
uses
Windows, ShellApi, SysUtils, Graphics, Forms;
type
TMyControl = class(TControl);
function PadChar(const Source: string; Width: Integer; PadCh: Char) : string;
begin
if Length(Source) >= Width then
Result := Source
else begin
SetLength(Result, Width);
FillChar(Result[1], Width, PadCh);
Move(Source[1], Result[1], Length(Source));
end;
end;
function LPadChar(const Source: string; Width: Integer; PadCh: Char) : string;
begin
if Length(Source) >= Width then
Result := Source
else begin
SetLength(Result, Width);
FillChar(Result[1], Width, PadCh);
Move(Source[1], Result[Succ(Width)-Length(Source)], Length(Source));
end;
end;
function Pad(const Source: string; Width: Integer) : string;
begin
Result := PadChar(Source, Width, ' ');
end;
function LPad(const Source: string; Width: Integer) : string;
begin
Result := LPadChar(Source, Width, ' ');
end;
function Commaize(Value: Integer) : string;
begin
Result := FormatFloat('#,', Value);
end;
procedure OpenPrim(S: string);
begin
ShellExecute(Application.Handle, nil, PChar(S), nil, nil, SW_SHOWNORMAL);
end;
procedure MailTo(const Address, Subject: string);
begin
OpenPrim('mailto:' + Address + '?subject=' + Subject);
end;
function FindChildNode(Item: TTreeNode; const CaptionText: string) : TTreeNode;
begin
Result := Item.GetFirstChild;
while Assigned(Result) do begin
if CompareStr(Result.Text, CaptionText) = 0 then
Exit;
Result := Result.GetNextChild(Result);
end;
end;
function FindItemCaption(ListView: TListView; const Caption: string) : TListItem;
var
Found: Boolean;
FRefNr, LRefNr, Index: Integer;
begin
Result := nil;
if ListView.Items.Count = 0 then Exit;
Found := False;
Index := 0;
FRefNr := 0;
LRefNr := Pred(ListView.Items.Count);
while (FRefNr <= LRefNr) and not Found do
begin
Index := (FRefNr + LRefNr) div 2;
case AnsiCompareStr(ListView.Items[Index].Caption, Caption) of
-1 : FRefNr := Succ(Index);
1 : LRefNr := Pred(Index);
0 : Found := True;
end;
end;
if Found then
Result := ListView.Items[Index];
end;
function GetFirstItem(ListView: TListView) : TListItem;
begin
Result := ListView.GetNextItem(nil, sdAll, [isNone]);
end;
procedure SelectFirstItem(ListView: TListView);
begin
ListView.Selected := GetFirstItem(ListView);
ListView.ItemFocused := ListView.Selected;
end;
procedure ControlColorCheck(Controls: array of TControl);
var
X: Integer;
begin
for X := Low(Controls) to High(Controls) do begin
if TMyControl(Controls[X]).Enabled then
TMyControl(Controls[X]).Color := clWindow
else
TMyControl(Controls[X]).Color := clBtnFace;
end;
end;
end.
|
{***************************************************************************}
{ }
{ DelphiWebDriver }
{ }
{ Copyright 2017 inpwtepydjuf@gmail.com }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit Commands;
interface
uses
Sessions,
Vcl.Forms,
CommandRegistry,
HttpServerCommand;
type
TUnimplementedCommand = class(TRestCommand)
public
procedure Execute(AOwner: TForm); override;
end;
type
/// <summary>
/// Handles 'GET' '/status'
/// </summary>
TStatusCommand = class(TRESTCommand)
public
procedure Execute(AOwner: TForm); override;
class function GetCommand: String; override;
class function GetRoute: String; override;
end;
type
TGetSessionsCommand = class(TRESTCommand)
public
procedure Execute(AOwner: TForm); override;
class function GetCommand: String; override;
class function GetRoute: String; override;
end;
type
TGetSessionCommand = class(TRESTCommand)
public
procedure Execute(AOwner: TForm); override;
class function GetCommand: String; override;
class function GetRoute: String; override;
end;
type
TGetTitleCommand = class(TRestCommand)
public
procedure Execute(AOwner: TForm); override;
class function GetCommand: String; override;
class function GetRoute: String; override;
end;
type
TSessionTimeoutsCommand = class(TRESTCommand)
public
procedure Execute(AOwner: TForm); override;
class function GetCommand: String; override;
class function GetRoute: String; override;
end;
type
TPostImplicitWaitCommand = class(TRestCommand)
public
procedure Execute(AOwner: TForm); override;
class function GetCommand: String; override;
class function GetRoute: String; override;
end;
type
TGetElementCommand = class(TRestCommand)
public
procedure Execute(AOwner: TForm); override;
class function GetCommand: String; override;
class function GetRoute: String; override;
end;
type
TGetWindowCommand = class(TRestCommand)
public
procedure Execute(AOwner: TForm); override;
class function GetCommand: String; override;
class function GetRoute: String; override;
end;
var
Sessions: TSessions;
implementation
uses
windows,
Vcl.stdctrls,
System.Classes,
System.SysUtils,
vcl.controls,
System.JSON,
System.Types,
System.StrUtils,
System.JSON.Types,
System.JSON.Writers,
System.JSON.Builders,
Utils,
Session;
procedure TStatusCommand.Execute(AOwner: TForm);
begin
try
ResponseJSON(Sessions.GetSessionStatus(self.Params[1]));
except on e: Exception do
Error(404);
end;
end;
class function TStatusCommand.GetCommand: String;
begin
result := 'GET';
end;
class function TStatusCommand.GetRoute: String;
begin
result := '/status';
end;
procedure TSessionTimeoutsCommand.Execute(AOwner: TForm);
var
jsonObj : TJSONObject;
requestType: String;
value: String;
begin
// Set timeout for the session
// Decode the incoming JSON and see what we have
jsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(self.StreamContents),0) as TJSONObject;
try
(jsonObj as TJsonObject).TryGetValue<String>('type', requestType);
(jsonObj as TJsonObject).TryGetValue<String>('ms', value);
finally
jsonObj.Free;
end;
ResponseJSON(Sessions.SetSessionTimeouts(self.Params[1], StrToInt(value)));
end;
procedure TPostImplicitWaitCommand.Execute(AOwner: TForm);
var
jsonObj : TJSONObject;
requestType: String;
value: String;
begin
// Set timeout for the session
// Decode the incoming JSON and see what we have
jsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(self.StreamContents),0) as TJSONObject;
try
(jsonObj as TJsonObject).TryGetValue<String>('type', requestType);
(jsonObj as TJsonObject).TryGetValue<String>('ms', value);
finally
jsonObj.Free;
end;
ResponseJSON(Sessions.SetSessionImplicitTimeouts(self.Params[1], StrToInt(value)));
end;
procedure TGetElementCommand.Execute(AOwner: TForm);
begin
ResponseJSON('{''TGetElementCommand'':'''+ self.Params[1] + '''}');
end;
procedure TGetSessionCommand.Execute(AOwner: TForm);
begin
try
ResponseJSON(Sessions.GetSessionStatus(self.Params[1]));
except on e: Exception do
Error(404);
end;
end;
procedure TGetSessionsCommand.Execute(AOwner: TForm);
begin
// No longer correct, needs to be a json array
ResponseJSON(Sessions.GetSessionStatus(self.Params[1]));
end;
class function TGetSessionsCommand.GetCommand: String;
begin
result := 'GET';
end;
class function TGetSessionsCommand.GetRoute: String;
begin
result := '/sessions';
end;
class function TGetSessionCommand.GetCommand: String;
begin
result := 'GET';
end;
class function TGetSessionCommand.GetRoute: String;
begin
result := '/session/(.*)';
end;
class function TGetElementCommand.GetCommand: String;
begin
result := 'GET';
end;
class function TGetElementCommand.GetRoute: String;
begin
result := '/session/(.*)/element';
end;
procedure TUnimplementedCommand.Execute(AOwner: TForm);
begin
Error(501);
end;
procedure TGetTitleCommand.Execute(AOwner: TForm);
var
caption : String;
begin
// Here we are assuming it is a form
caption := AOwner.Caption; // Never gets a caption for some reason
ResponseJSON(caption);
end;
class function TGetTitleCommand.GetCommand: String;
begin
result := 'GET';
end;
class function TGetTitleCommand.GetRoute: String;
begin
result := '/session/(.*)/title';
end;
procedure TGetWindowCommand.Execute(AOwner: TForm);
var
handle : HWND;
begin
try
handle := AOwner.Handle;
ResponseJSON(intToStr(handle));
except on e: Exception do
Sessions.ErrorResponse ('7', 'no such element', 'An element could not be located on the page using the given search parameteres');
end;
end;
class function TSessionTimeoutsCommand.GetCommand: String;
begin
result := 'POST';
end;
class function TSessionTimeoutsCommand.GetRoute: String;
begin
result := '/session/(.*)/timeouts';
end;
class function TPostImplicitWaitCommand.GetCommand: String;
begin
result := 'POST';
end;
class function TPostImplicitWaitCommand.GetRoute: String;
begin
result := '/session/(.*)/timeouts/implicit_wait';
end;
class function TGetWindowCommand.GetCommand: String;
begin
result := 'GET';
end;
class function TGetWindowCommand.GetRoute: String;
begin
result := '/session/(.*)/window';
end;
initialization
Sessions := TSessions.Create;
finalization
Sessions.Free;
end.
|
{$include kode.inc}
unit kode_sinusoid;
{
desc:sinusoid (approximation)
slider1: 55 < 1, 44100 > freq left - sinusoid
slider2: 55 < 1, 44100 > freq right - sin()
@init
p0 = 0;
p1 = 0;
@slider
r0 = (slider1/srate)*4;
r1 = (slider2/srate);
@sample
// sinusoid
p0+=r0;
p0>2 ? p0-=4;
s0 = p0*(2-abs(p0));
// sin()
p1+=r1;
p1>=1 ? p1-=1;
s1 = sin(p1*($pi*2));
//
spl0 = s0;
spl1 = s1;
}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
type
KSinusoid = class
private
p0 : Single;
r0 : Single;
srate : Single;
public
constructor create;
procedure setSampleRate(rate:Single);
procedure setFrequency(hz:single);
function proces : Single;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
constructor KSinusoid.create;
begin
p0 := 0;
r0 := 0;
srate := 0;
end;
//----------
procedure KSinusoid.setSampleRate(rate:Single);
begin
srate := rate;
end;
//----------
procedure KSinusoid.setFrequency(hz:single);
begin
r0 := (hz/srate)*4;
end;
//----------
function KSinusoid.proces : Single;
begin
p0 += r0;
if p0 > 2 then p0 -= 4;
result := p0*(2-abs(p0));
end;
//----------------------------------------------------------------------
end.
|
unit MBResponseTypes;
{$mode objfpc}{$H+}
interface
uses MBRequestTypes;
type
PMBErrorData = ^TMBErrorData;
TMBErrorData = packed record
FunctionCode : Byte;
ErrorCode : Byte;
end;
PMBErrorHeder = ^TMBErrorHeder;
TMBErrorHeder = packed record
DeviceAddress : Byte;
ErrorData : TMBErrorData;
end;
PMBErrorResponse = ^TMBErrorResponse;
TMBErrorResponse = packed record
Heder : TMBErrorHeder;
CRC : Word;
end;
PMBResponseHeader = ^TMBResponseHeader;
TMBResponseHeader = packed record
DeviceAddress : Byte;
FunctionCode : Byte;
ByteCount : Byte;
end;
PWordRegVlueArray = ^TWordRegVlueArray;
TWordRegVlueArray = array [0..124] of Word;
PWordRegF3Response = ^TWordRegF3Response;
TWordRegF3Response = packed record
ByteCount : Byte;
RegValues : TWordRegVlueArray;
end;
PMBTCPErrorHeder = ^TMBTCPErrorHeder;
TMBTCPErrorHeder = packed record
TransactioID : Word;
ProtocolID : Word;
Length : Word;
DeviceID : Byte;
ErrorData : TMBErrorData;
end;
PEventArray = ^TEventArray;
TEventArray = packed array [0..63] of Byte;
PDataArray = ^TDataArray;
TDataArray = packed array [0..251] of Byte;
TConformityLevel = (cl01 = 1, cl02 = 2, cl03 = 3,
cl81 = $81, cl82 = $82, cl83 = $83);
PObjectData = ^TObjectData;
TObjectData = packed record
ObjectID : TObjectID;
ObjectLen : Byte;
ObjectValue : array [0..244] of Byte;
end;
PObjectList = ^TObjectList;
TObjectList = array of TObjectData;
PMBF72ResponceHeader = ^TMBF72ResponceHeader;
TMBF72ResponceHeader = packed record
DeviceNum : Byte;
FunctionNum : Byte;
ChkRKey : Byte;
StartReg : Word;
Quantity : Byte;
end;
PMBF110ResponceHeader = ^TMBF110ResponceHeader;
TMBF110ResponceHeader = packed record
DeviceNum : Byte;
FunctionNum : Byte;
ChkWKey : Byte;
StartReg : Word;
Quantity : Byte;
end;
implementation
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit Maps;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Permissions,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FMX.Edit,
FMX.Maps;
type
TForm1 = class(TForm)
TopToolBar: TToolBar;
BottomToolBar: TToolBar;
Label1: TLabel;
edLat: TEdit;
edLong: TEdit;
Button1: TButton;
MapView1: TMapView;
Panel1: TPanel;
GridPanelLayout1: TGridPanelLayout;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
TrackBar1: TTrackBar;
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure MapView1MapClick(const Position: TMapCoordinate);
procedure TrackBar1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FPermissionFineLocation: string;
procedure DisplayRationale(Sender: TObject; const APermissions: TArray<string>; const APostRationaleProc: TProc);
procedure LocationPermissionRequestResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
{$IFDEF ANDROID}
Androidapi.Helpers,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.Os,
{$ENDIF}
FMX.DialogService;
{$R *.fmx}
{$R *.LgXhdpiPh.fmx ANDROID}
procedure TForm1.FormCreate(Sender: TObject);
begin
{$IFDEF ANDROID}
FPermissionFineLocation := JStringToString(TJManifest_permission.JavaClass.ACCESS_FINE_LOCATION);
{$ENDIF}
PermissionsService.RequestPermissions([FPermissionFineLocation], LocationPermissionRequestResult, DisplayRationale);
end;
// Optional rationale display routine to display permission requirement rationale to the user
procedure TForm1.DisplayRationale(Sender: TObject; const APermissions: TArray<string>; const APostRationaleProc: TProc);
begin
// Show an explanation to the user *asynchronously* - don't block this thread waiting for the user's response!
// After the user sees the explanation, invoke the post-rationale routine to request the permissions
TDialogService.ShowMessage('The app can show where you are on the map if you give it permission',
procedure(const AResult: TModalResult)
begin
APostRationaleProc;
end)
end;
procedure TForm1.LocationPermissionRequestResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>);
begin
// 2 permissions involved: ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION
if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then
begin
MapView1.ControlOptions := MapView1.ControlOptions + [TMapControlOption.MyLocation];
MapView1.LayerOptions := MapView1.LayerOptions + [TMapLayerOption.UserLocation];
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
MapCenter: TMapCoordinate;
begin
MapCenter := TMapCoordinate.Create(StrToFloat(edLat.Text, TFormatSettings.Invariant), StrToFloat(edLong.Text, TFormatSettings.Invariant));
MapView1.Location := MapCenter;
end;
procedure TForm1.MapView1MapClick(const Position: TMapCoordinate);
var
MyMarker: TMapMarkerDescriptor;
begin
MyMarker := TMapMarkerDescriptor.Create(Position, 'MyMarker');
MyMarker.Draggable := True;
MyMarker.Visible := True;
MapView1.AddMarker(MyMarker);
end;
// -------------------For Normal button -----------------------------------------
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
MapView1.MapType := TMapType.Normal;
TrackBar1.Value := 0.0;
end;
// -------------------For Satellite button---------------------------------------
procedure TForm1.SpeedButton2Click(Sender: TObject);
begin
MapView1.MapType := TMapType.Satellite;
TrackBar1.Value := 0.0;
end;
// --------------------For Hybrid button-----------------------------------------
procedure TForm1.SpeedButton3Click(Sender: TObject);
begin
MapView1.MapType := TMapType.Hybrid;
TrackBar1.Value := 0.0;
end;
procedure TForm1.TrackBar1Change(Sender: TObject);
begin
MapView1.Bearing := TrackBar1.Value;
end;
end.
|
{$R-} {Range checking off}
{$B+} {Boolean complete evaluation on}
{$S+} {Stack checking on}
{$I+} {I/O checking on}
{$N-} {No numeric coprocessor}
{$M 65500,16384,655360} {Turbo 3 default stack and heap}
program memory_display;
{ this program displays the contents of memory onto the ibm pc's screen. }
{ the user may move though the memory by using the page up, page dn, home, }
{ end, left, right, up arrow and down arrow keys. }
{ july 10, 1984. jeff firestone. }
uses
crt;
const
endofmem = $9f88; { top of mem. (640k) less one page (1920) }
monochromescreen = $b00a; { location of monochrome card + 1 line }
colorgraphscreen = $b80a; { location of color graphics card + 1 line }
esc = #27;
var
i,
initial_segment,
initial_offset,
val_error : integer;
screen_segment,
screen_offset : word;
parameter_address : longint;
done : boolean;
top_pntr, scrn, pntr : ^char;
procedure beep;
begin
sound(760);
delay(50);
nosound;
end; {beep}
function hexstring(a:integer) : string;
const
hex = '0123456789ABCDEF';
var
inter,i : byte;
tempstr : string;
begin
tempstr := '';
for i := 1 to 4 do
begin
inter := a shr 12;
a := a shl 4;
tempstr := tempstr + copy(hex,inter+1,1);
end;
hexstring := tempstr;
end;
procedure display_address(segment,offset : word);
var
address : longint;
begin
address := segment;
address := address * 16 + offset;
gotoxy(9,1);
textcolor(lightcyan); write('Address = ');
textcolor(yellow); write(hexstring(segment));
write(':');
write(hexstring(offset));
textcolor(lightcyan); write('(');
textcolor(yellow); write(address:7);
textcolor(lightcyan); write(') "');
textcolor(yellow); write(chr(mem[segment:offset ]));
write(chr(mem[segment:offset+1]));
textcolor(lightcyan); write('" = ');
textcolor(yellow); write(hexstring(mem[segment:offset]*256+mem[segment:offset+1]));
textcolor(lightcyan); write('(');
textcolor(yellow); write(mem[segment:offset ]:3,',');
write(mem[segment:offset+1]:3);
textcolor(lightcyan); write(')');
end;
procedure initialize;
begin
textbackground(black);
textcolor(lightgray);
clrscr;
if lastmode = mono then
screen_segment := monochromescreen
else
screen_segment := colorgraphscreen;
screen_offset := 0;
parameter_address := 0;
val(paramstr(1),parameter_address,val_error);
initial_segment := parameter_address div 16;
initial_offset := parameter_address mod 16;
textbackground(blue);
textcolor(lightred);
gotoxy(1,1);
write(' D-RAM');
clreol;
gotoxy(61,1);
textcolor(lightcyan); write('Display = ');
textcolor(yellow); write(hexstring(screen_segment),':');
write(hexstring(screen_offset));
display_address(initial_segment,initial_offset);
end;
{-------------------------------------------------------------}
procedure normalize(segment_pntr, offset_pntr : integer);
var
segment, offset : integer;
begin
segment := memw[segment_pntr:offset_pntr+2];
offset := memw[segment_pntr:offset_pntr ];
if (offset < 0) then
begin
offset := 15;
segment := segment - 1;
end;
segment := (segment + (offset shr 4));
offset := (offset and 15);
memw[segment_pntr:offset_pntr+2] := segment;
memw[segment_pntr:offset_pntr ] := offset;
end;
{-------------------------------------------------------------}
{-------------------------------------------------------------}
procedure read_keyboard;
const
pagesz = 120; {120 segments = 1920 bytes = 24 lines of chars}
linesz = 5; { 5 segments = 80 bytes = 1 line of chars}
charsz = 1; { 1 char }
var
key : char;
seg_top_pntr,
ofs_top_pntr : word;
begin
seg_top_pntr := memw[seg(top_pntr):ofs(top_pntr)+2];
ofs_top_pntr := memw[seg(top_pntr):ofs(top_pntr) ];
key := readkey;
if key = #0 then
begin
key := readkey;
case key of
'Q' : seg_top_pntr := seg_top_pntr + pagesz; { page dn }
'I' : seg_top_pntr := seg_top_pntr - pagesz; { page up }
'P' : seg_top_pntr := seg_top_pntr + linesz; { down arrow }
'H' : seg_top_pntr := seg_top_pntr - linesz; { up arrow }
'M' : ofs_top_pntr := ofs_top_pntr + charsz; { right arrow }
'K' : ofs_top_pntr := ofs_top_pntr - charsz; { left arrow }
'G' : begin seg_top_pntr := 0; ofs_top_pntr := 0; end; { home }
'O' : begin seg_top_pntr := endofmem; ofs_top_pntr := 0; end; { end }
';' : begin seg_top_pntr := $1000; ofs_top_pntr := 0; end; { F1 }
'<' : begin seg_top_pntr := $2000; ofs_top_pntr := 0; end; { F2 }
'=' : begin seg_top_pntr := $3000; ofs_top_pntr := 0; end; { F3 }
'>' : begin seg_top_pntr := $4000; ofs_top_pntr := 0; end; { F4 }
'?' : begin seg_top_pntr := $5000; ofs_top_pntr := 0; end; { F5 }
'@' : begin seg_top_pntr := $6000; ofs_top_pntr := 0; end; { F6 }
'A' : begin seg_top_pntr := $7000; ofs_top_pntr := 0; end; { F7 }
'B' : begin seg_top_pntr := $8000; ofs_top_pntr := 0; end; { F8 }
'C' : begin seg_top_pntr := $9000; ofs_top_pntr := 0; end; { F9 }
'D' : begin seg_top_pntr := $A000; ofs_top_pntr := 0; end; { F10 }
'T' : begin seg_top_pntr := $B000; ofs_top_pntr := 0; end; { s-F1 }
'U' : begin seg_top_pntr := $C000; ofs_top_pntr := 0; end; { s-F2 }
'V' : begin seg_top_pntr := $D000; ofs_top_pntr := 0; end; { s-F3 }
'W' : begin seg_top_pntr := $E000; ofs_top_pntr := 0; end; { s-F4 }
'X' : begin seg_top_pntr := $F000; ofs_top_pntr := 0; end; { s-F5 }
'Y' : begin seg_top_pntr := $0000; ofs_top_pntr := 0; end; { s-F6 }
else beep;
end;
end
else
if key = esc then
done := true
else
beep;
memw[seg(top_pntr):ofs(top_pntr)+2] := seg_top_pntr;
memw[seg(top_pntr):ofs(top_pntr) ] := ofs_top_pntr;
display_address(seg_top_pntr,ofs_top_pntr);
end; { procedure readcommand }
{-------------------------------------------------------------}
begin
done := false;
initialize;
memw[seg(top_pntr):ofs(top_pntr)+2] := initial_segment;
memw[seg(top_pntr):ofs(top_pntr) ] := initial_offset;
repeat
normalize(seg(top_pntr),ofs(top_pntr));
pntr := top_pntr;
memw[seg(scrn):ofs(scrn)+2] := screen_segment;
memw[seg(scrn):ofs(scrn) ] := screen_offset;
for i := 0 to 1920 do
begin
scrn^ := pntr^;
memw[seg(pntr):ofs(pntr)] := memw[seg(pntr):ofs(pntr)] + 1;
memw[seg(scrn):ofs(scrn)] := memw[seg(scrn):ofs(scrn)] + 2;
end;
read_keyboard;
until done;
textbackground(black);
textcolor(lightgray);
clrscr;
textbackground(blue);
textcolor(lightred);
gotoxy(1,1);
write(' D-RAM');
clreol;
textcolor(lightcyan);
gotoxy(10,1);
write('Jonathan Gilmore 1988');
writeln;
end.
|
unit Logger;
interface
uses SysUtils, Windows, StringUtils;
procedure ShowLoggerWindow();
procedure HideLoggerWindow();
procedure LogToFile(const filePath:String);
procedure log(const s: String);
procedure elog(const s: Variant);
procedure wlog(const s: Variant);
procedure ilog(const s: Variant);
implementation
uses DebugWindow;
var debugWin: TDebugWindow;
logFilePath: String = '';
procedure LogToFile(const filePath:String);
begin
logFilePath := filePath;
DeleteFile(PAnsiChar(logFilePath));
end;
procedure ShowLoggerWindow();
begin
if debugWin = nil then debugWin := TDebugWindow.Create(nil);
debugWin.Left := 20;
debugWin.Top := 20;
debugWin.Visible := true;
end;
procedure HideLoggerWindow();
begin
if debugWin = nil then Exit;
debugWin.Visible := false;
end;
procedure log(const s: String);
var f: TextFile;
begin
if debugWin <> nil then debugWin.log(s);
if logFilePath <> '' then begin
AssignFile(f, logFilePath);
try
if not FileExists(logFilePath) then Rewrite(f);
Append(f);
WriteLn(f, s);
finally
CloseFile(f);
end;
end;
end;
procedure elog(const s: Variant);
begin
if (debugWin = nil) and (logFilePath = '') then Exit;
log('[Error ' + TimeToStr(Now) + '] ' + StringConv(s));
end;
procedure wlog(const s: Variant);
begin
if (debugWin = nil) and (logFilePath = '') then Exit;
log('[Warning ' + TimeToStr(Now) + '] ' + StringConv(s));
end;
procedure ilog(const s: Variant);
begin
if (debugWin = nil) and (logFilePath = '') then Exit;
log('[Info ' + TimeToStr(Now) + '] ' + StringConv(s));
end;
end.
|
unit UnitXML; // Copyright (C) 2006-2017, Benjamin Rosseaux - License: zlib
{$ifdef fpc}
{$mode delphi}
{$ifdef cpui386}
{$define cpu386}
{$endif}
{$ifdef cpu386}
{$asmmode intel}
{$endif}
{$ifdef cpuamd64}
{$asmmode intel}
{$endif}
{$ifdef fpc_little_endian}
{$define little_endian}
{$else}
{$ifdef fpc_big_endian}
{$define big_endian}
{$endif}
{$endif}
{$ifdef fpc_has_internal_sar}
{$define HasSAR}
{$endif}
{-$pic off}
{$define caninline}
{$ifdef FPC_HAS_TYPE_EXTENDED}
{$define HAS_TYPE_EXTENDED}
{$else}
{$undef HAS_TYPE_EXTENDED}
{$endif}
{$ifdef FPC_HAS_TYPE_DOUBLE}
{$define HAS_TYPE_DOUBLE}
{$else}
{$undef HAS_TYPE_DOUBLE}
{$endif}
{$ifdef FPC_HAS_TYPE_SINGLE}
{$define HAS_TYPE_SINGLE}
{$else}
{$undef HAS_TYPE_SINGLE}
{$endif}
{$else}
{$realcompatibility off}
{$localsymbols on}
{$define little_endian}
{$ifndef cpu64}
{$define cpu32}
{$endif}
{$define delphi}
{$undef HasSAR}
{$define UseDIV}
{$define HAS_TYPE_EXTENDED}
{$define HAS_TYPE_DOUBLE}
{$define HAS_TYPE_SINGLE}
{$endif}
{$ifdef cpu386}
{$define cpux86}
{$endif}
{$ifdef cpuamd64}
{$define cpux86}
{$endif}
{$ifdef win32}
{$define windows}
{$endif}
{$ifdef win64}
{$define windows}
{$endif}
{$ifdef wince}
{$define windows}
{$endif}
{$ifdef windows}
{$define win}
{$endif}
{$ifdef sdl20}
{$define sdl}
{$endif}
{$rangechecks off}
{$extendedsyntax on}
{$writeableconst on}
{$hints off}
{$booleval off}
{$typedaddress off}
{$stackframes off}
{$varstringchecks on}
{$typeinfo on}
{$overflowchecks off}
{$longstrings on}
{$openstrings on}
{$ifndef HAS_TYPE_DOUBLE}
{$error No double floating point precision}
{$endif}
{$ifdef fpc}
{$define caninline}
{$else}
{$undef caninline}
{$ifdef ver180}
{$define caninline}
{$else}
{$ifdef conditionalexpressions}
{$if compilerversion>=18}
{$define caninline}
{$ifend}
{$endif}
{$endif}
{$endif}
interface
uses SysUtils,Classes;
type TXMLClass=class
public
Previous,Next:TXMLClass;
Core:pointer;
constructor Create; overload; virtual;
destructor Destroy; override;
end;
const MaxListSize=2147483647 div SizeOf(TXMLClass);
type PEngineListClasses=^TXMLClasses;
TXMLClasses=array[0..MaxListSize-1] of TXMLClass;
TXMLClassList=class(TXMLClass)
private
InternalList:PEngineListClasses;
InternalCount,InternalCapacity:longint;
function GetItem(Index:longint):TXMLClass;
procedure SetItem(Index:longint;Value:TXMLClass);
function GetItemPointer(Index:longint):TXMLClass;
public
ClearWithContentDestroying:boolean;
CapacityMinimium:longint;
constructor Create; override;
destructor Destroy; override;
procedure Clear;
procedure ClearNoFree;
procedure ClearWithFree;
function Add(Item:TXMLClass):longint;
function Append(Item:TXMLClass):longint;
function AddList(List:TXMLClassList):longint;
function AppendList(List:TXMLClassList):longint;
function NewClass:TXMLClass;
procedure Insert(Index:longint;Item:TXMLClass);
procedure Delete(Index:longint);
procedure DeleteClass(Index:longint);
function Remove(Item:TXMLClass):longint;
function RemoveClass(Item:TXMLClass):longint;
function Find(Item:TXMLClass):longint;
function IndexOf(Item:TXMLClass):longint;
procedure Exchange(Index1,Index2:longint);
procedure SetCapacity(NewCapacity:longint);
procedure SetOptimalCapacity(TargetCapacity:longint);
procedure SetCount(NewCount:longint);
function Push(Item:TXMLClass):longint;
function Pop(var Item:TXMLClass):boolean; overload;
function Pop:TXMLClass; overload;
function Last:TXMLClass;
property Count:longint read InternalCount;
property Capacity:longint read InternalCapacity write SetCapacity;
property Item[Index:longint]:TXMLClass read GetItem write SetItem; default;
property Items[Index:longint]:TXMLClass read GetItem write SetItem;
property PItems[Index:longint]:TXMLClass read GetItemPointer;
end;
TXMLClassLinkedList=class(TXMLClass)
public
ClearWithContentDestroying:boolean;
First,Last:TXMLClass;
constructor Create; override;
destructor Destroy; override;
procedure Clear;
procedure ClearNoFree;
procedure ClearWithFree;
procedure Add(Item:TXMLClass);
procedure Append(Item:TXMLClass);
procedure AddLinkedList(List:TXMLClassLinkedList);
procedure AppendLinkedList(List:TXMLClassLinkedList);
procedure Remove(Item:TXMLClass);
procedure RemoveClass(Item:TXMLClass);
procedure Push(Item:TXMLClass);
function Pop(var Item:TXMLClass):boolean; overload;
function Pop:TXMLClass; overload;
function Count:longint;
end;
TXMLPtrInt={$if defined(fpc)}PtrInt{$elseif declared(NativeInt)}NativeInt{$elseif defined(cpu64)}Int64{$else}longint{$ifend};
TXMLStringTreeData=TXMLPtrInt;
PXMLStringTreeNode=^TXMLStringTreeNode;
TXMLStringTreeNode=record
TheChar:ansichar;
Data:TXMLStringTreeData;
DataExist:boolean;
Prevoius,Next,Up,Down:PXMLStringTreeNode;
end;
TXMLStringTree=class
private
Root:PXMLStringTreeNode;
function CreateStringTreeNode(AChar:ansichar):PXMLStringTreeNode;
procedure DestroyStringTreeNode(Node:PXMLStringTreeNode);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure DumpTree;
procedure DumpList;
procedure AppendTo(DestStringTree:TXMLStringTree);
procedure Optimize(DestStringTree:TXMLStringTree);
function Add(Content:ansistring;Data:TXMLStringTreeData;Replace:boolean=false):boolean;
function Delete(Content:ansistring):boolean;
function Find(Content:ansistring;var Data:TXMLStringTreeData):boolean;
function FindEx(Content:ansistring;var Data:TXMLStringTreeData;var Len:longint):boolean;
end;
TXMLString={$ifdef UNICODE}widestring{$else}ansistring{$endif};
TXMLChar={$ifdef UNICODE}widechar{$else}ansichar{$endif};
TXMLParameter=class(TXMLClass)
public
Name:ansistring;
Value:TXMLString;
constructor Create; override;
destructor Destroy; override;
procedure Assign(From:TXMLParameter); virtual;
end;
TXMLItemList=class;
TXMLTag=class;
TXMLItem=class(TXMLClass)
public
Items:TXMLItemList;
constructor Create; override;
destructor Destroy; override;
procedure Clear; virtual;
procedure Add(Item:TXMLItem);
procedure Assign(From:TXMLItem); virtual;
function FindTag(const TagName:ansistring):TXMLTag;
end;
TXMLItemList=class(TXMLClassList)
private
function GetItem(Index:longint):TXMLItem;
procedure SetItem(Index:longint;Value:TXMLItem);
public
constructor Create; override;
destructor Destroy; override;
function NewClass:TXMLItem;
function FindTag(const TagName:ansistring):TXMLTag;
property Item[Index:longint]:TXMLItem read GetItem write SetItem; default;
property Items[Index:longint]:TXMLItem read GetItem write SetItem;
end;
TXMLText=class(TXMLItem)
public
Text:TXMLString;
constructor Create; override;
destructor Destroy; override;
procedure Assign(From:TXMLItem); override;
procedure SetText(AText:ansistring);
end;
TXMLCommentTag=class(TXMLItem)
public
Text:ansistring;
constructor Create; override;
destructor Destroy; override;
procedure Assign(From:TXMLItem); override;
procedure SetText(AText:ansistring);
end;
TXMLTag=class(TXMLItem)
public
Name:ansistring;
Parameter:array of TXMLParameter;
IsAloneTag:boolean;
constructor Create; override;
destructor Destroy; override;
procedure Clear; override;
procedure Assign(From:TXMLItem); override;
function FindParameter(ParameterName:ansistring):TXMLParameter;
function GetParameter(ParameterName:ansistring;default:ansistring=''):ansistring;
function AddParameter(AParameter:TXMLParameter):boolean; overload;
function AddParameter(Name:ansistring;Value:TXMLString):boolean; overload;
function RemoveParameter(AParameter:TXMLParameter):boolean; overload;
function RemoveParameter(ParameterName:ansistring):boolean; overload;
end;
TXMLProcessTag=class(TXMLTag)
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(From:TXMLItem); override;
end;
TXMLScriptTag=class(TXMLItem)
public
Text:ansistring;
constructor Create; override;
destructor Destroy; override;
procedure Assign(From:TXMLItem); override;
procedure SetText(AText:ansistring);
end;
TXMLCDataTag=class(TXMLItem)
public
Text:ansistring;
constructor Create; override;
destructor Destroy; override;
procedure Assign(From:TXMLItem); override;
procedure SetText(AText:ansistring);
end;
TXMLDOCTYPETag=class(TXMLItem)
public
Text:ansistring;
constructor Create; override;
destructor Destroy; override;
procedure Assign(From:TXMLItem); override;
procedure SetText(AText:ansistring);
end;
TXMLExtraTag=class(TXMLItem)
public
Text:ansistring;
constructor Create; override;
destructor Destroy; override;
procedure Assign(From:TXMLItem); override;
procedure SetText(AText:ansistring);
end;
TXML=class(TXMLClass)
private
function ReadXMLText:ansistring;
procedure WriteXMLText(Text:ansistring);
public
Root:TXMLItem;
AutomaticAloneTagDetection:boolean;
FormatIndent:boolean;
FormatIndentText:boolean;
constructor Create; override;
destructor Destroy; override;
procedure Assign(From:TXML);
function Parse(Stream:TStream):boolean;
function Read(Stream:TStream):boolean;
function Write(Stream:TStream;IdentSize:longint=2):boolean;
property Text:ansistring read ReadXMLText write WriteXMLText;
end;
implementation
function UTF32CharToUTF8(CharValue:longword):ansistring;
var Data:array[0..{$ifdef strictutf8}3{$else}5{$endif}] of ansichar;
ResultLen:longint;
begin
if CharValue=0 then begin
result:=#0;
end else begin
if CharValue<=$7f then begin
Data[0]:=ansichar(byte(CharValue));
ResultLen:=1;
end else if CharValue<=$7ff then begin
Data[0]:=ansichar(byte($c0 or ((CharValue shr 6) and $1f)));
Data[1]:=ansichar(byte($80 or (CharValue and $3f)));
ResultLen:=2;
{$ifdef strictutf8}
end else if CharValue<=$d7ff then begin
Data[0]:=ansichar(byte($e0 or ((CharValue shr 12) and $0f)));
Data[1]:=ansichar(byte($80 or ((CharValue shr 6) and $3f)));
Data[2]:=ansichar(byte($80 or (CharValue and $3f)));
ResultLen:=3;
end else if CharValue<=$dfff then begin
Data[0]:=#$ef; // $fffd
Data[1]:=#$bf;
Data[2]:=#$bd;
ResultLen:=3;
{$endif}
end else if CharValue<=$ffff then begin
Data[0]:=ansichar(byte($e0 or ((CharValue shr 12) and $0f)));
Data[1]:=ansichar(byte($80 or ((CharValue shr 6) and $3f)));
Data[2]:=ansichar(byte($80 or (CharValue and $3f)));
ResultLen:=3;
end else if CharValue<=$1fffff then begin
Data[0]:=ansichar(byte($f0 or ((CharValue shr 18) and $07)));
Data[1]:=ansichar(byte($80 or ((CharValue shr 12) and $3f)));
Data[2]:=ansichar(byte($80 or ((CharValue shr 6) and $3f)));
Data[3]:=ansichar(byte($80 or (CharValue and $3f)));
ResultLen:=4;
{$ifndef strictutf8}
end else if CharValue<=$3ffffff then begin
Data[0]:=ansichar(byte($f8 or ((CharValue shr 24) and $03)));
Data[1]:=ansichar(byte($80 or ((CharValue shr 18) and $3f)));
Data[2]:=ansichar(byte($80 or ((CharValue shr 12) and $3f)));
Data[3]:=ansichar(byte($80 or ((CharValue shr 6) and $3f)));
Data[4]:=ansichar(byte($80 or (CharValue and $3f)));
ResultLen:=5;
end else if CharValue<=$7fffffff then begin
Data[0]:=ansichar(byte($fc or ((CharValue shr 30) and $01)));
Data[1]:=ansichar(byte($80 or ((CharValue shr 24) and $3f)));
Data[2]:=ansichar(byte($80 or ((CharValue shr 18) and $3f)));
Data[3]:=ansichar(byte($80 or ((CharValue shr 12) and $3f)));
Data[4]:=ansichar(byte($80 or ((CharValue shr 6) and $3f)));
Data[5]:=ansichar(byte($80 or (CharValue and $3f)));
ResultLen:=6;
{$endif}
end else begin
Data[0]:=#$ef; // $fffd
Data[1]:=#$bf;
Data[2]:=#$bd;
ResultLen:=3;
end;
SetString(result,pansichar(@Data[0]),ResultLen);
end;
end;
function NextPowerOfTwo(Value:longint;const MinThreshold:longint=0):longint;
begin
result:=(Value or MinThreshold)-1;
result:=result or (result shr 1);
result:=result or (result shr 2);
result:=result or (result shr 4);
result:=result or (result shr 8);
result:=result or (result shr 16);
inc(result);
end;
const EntityChars:array[1..102,1..2] of TXMLString=(('"',#34),('&',#38),(''',''''),
('<',#60),('>',#62),('€',#128),(' ',#160),('¡',#161),
('¢',#162),('£',#163),('¤',#164),('¥',#165),
('¦',#166),('§',#167),('¨',#168),('©',#169),
('ª',#170),('«',#171),('¬',#172),('­',#173),
('®',#174),('¯',#175),('°',#176),('±',#177),
('²',#178),('³',#179),('´',#180),('µ',#181),
('¶',#182),('·',#183),('¸',#184),('¹',#185),
('º',#186),('»',#187),('¼',#188),('½',#189),
('¾',#190),('¿',#191),('À',#192),('Á',#193),
('Â',#194),('Ã',#195),('Ä',#196),('Å',#197),
('Æ',#198),('Ç',#199),('È',#200),('É',#201),
('Ê',#202),('Ë',#203),('Ì',#204),('Í',#205),
('Î',#206),('Ï',#207),('Ð',#208),('Ñ',#209),
('Ò',#210),('Ó',#211),('Ô',#212),('Õ',#213),
('Ö',#214),('×',#215),('Ø',#216),('Ù',#217),
('Ú',#218),('Û',#219),('Ü',#220),('Ý',#221),
('Þ',#222),('ß',#223),('à',#224),('á',#225),
('â',#226),('ã',#227),('ä',#228),('å',#229),
('æ',#230),('ç',#231),('è',#232),('é',#233),
('ê',#234),('ë',#235),('ì',#236),('í',#237),
('î',#238),('ï',#239),('ð',#240),('ñ',#241),
('ò',#242),('ó',#243),('ô',#244),('õ',#245),
('ö',#246),('÷',#247),('ø',#248),('ù',#249),
('ú',#250),('û',#251),('ü',#252),('ý',#253),
('þ',#254),('ÿ',#255));
type TEntitiesCharLookUpItem=record
IsEntity:boolean;
Entity:ansistring;
end;
TEntitiesCharLookUpTable=array[0..{$ifdef UNICODE}65535{$else}255{$endif}] of TEntitiesCharLookUpItem;
var EntitiesCharLookUp:TEntitiesCharLookUpTable;
EntityStringTree:TXMLStringTree;
const EntityInitialized:boolean=false;
procedure InitializeEntites;
var EntityCounter:longint;
begin
if not EntityInitialized then begin
EntityInitialized:=true;
EntityStringTree:=TXMLStringTree.Create;
FillChar(EntitiesCharLookUp,SizeOf(TEntitiesCharLookUpTable),#0);
for EntityCounter:=low(EntityChars) to high(EntityChars) do begin
EntityStringTree.Add(EntityChars[EntityCounter,1],EntityCounter,true);
with EntitiesCharLookUp[ord(EntityChars[EntityCounter,2][1])] do begin
IsEntity:=true;
Entity:=EntityChars[EntityCounter,1];
end;
end;
end;
end;
procedure FinalizeEntites;
begin
if assigned(EntityStringTree) then begin
EntityStringTree.Destroy;
EntityStringTree:=nil;
end;
EntityInitialized:=false;
end;
function ConvertToEntities(AString:TXMLString;IdentLevel:longint=0):ansistring;
var Counter,IdentCounter:longint;
c:TXMLChar;
begin
result:='';
for Counter:=1 to length(AString) do begin
c:=AString[Counter];
if c=#13 then begin
if ((Counter+1)<=length(AString)) and (AString[Counter+1]=#10) then begin
continue;
end;
c:=#10;
end;
if EntitiesCharLookUp[ord(c)].IsEntity then begin
result:=result+EntitiesCharLookUp[ord(c)].Entity;
end else if (c=#9) or (c=#10) or (c=#13) or ((c>=#32) and (c<=#127)) then begin
result:=result+c;
if c=#10 then begin
for IdentCounter:=1 to IdentLevel do begin
result:=result+' ';
end;
end;
end else begin
{$ifdef UNICODE}
if c<#255 then begin
result:=result+'&#'+INTTOSTR(ord(c))+';';
end else begin
result:=result+'&#x'+IntToHex(ord(c),4)+';';
end;
{$else}
result:=result+'&#'+INTTOSTR(byte(c))+';';
{$endif}
end;
end;
end;
constructor TXMLClass.Create;
begin
inherited Create;
Previous:=nil;
Next:=nil;
Core:=nil;
end;
destructor TXMLClass.Destroy;
begin
inherited Destroy;
end;
constructor TXMLClassList.Create;
begin
inherited Create;
ClearWithContentDestroying:=false;
InternalCount:=0;
InternalCapacity:=0;
InternalList:=nil;
CapacityMinimium:=0;
Clear;
end;
destructor TXMLClassList.Destroy;
begin
Clear;
if assigned(InternalList) and (InternalCapacity<>0) then begin
FreeMem(InternalList);
end;
inherited Destroy;
end;
procedure TXMLClassList.Clear;
begin
if ClearWithContentDestroying then begin
ClearWithFree;
end else begin
ClearNoFree;
end;
end;
procedure TXMLClassList.ClearNoFree;
begin
SetCount(0);
end;
procedure TXMLClassList.ClearWithFree;
var Counter:longint;
begin
for Counter:=0 to InternalCount-1 do begin
if assigned(InternalList^[Counter]) then begin
try
InternalList^[Counter].Destroy;
except
end;
end;
end;
SetCount(0);
end;
procedure TXMLClassList.SetCapacity(NewCapacity:longint);
begin
if (InternalCapacity<>NewCapacity) and
((NewCapacity>=0) and (NewCapacity<MaxListSize)) then begin
ReallocMem(InternalList,NewCapacity*SizeOf(TXMLClass));
if InternalCapacity<NewCapacity then begin
FillChar(InternalList^[InternalCapacity],(NewCapacity-InternalCapacity)*SizeOf(TXMLClass),#0);
end;
InternalCapacity:=NewCapacity;
end;
end;
procedure TXMLClassList.SetOptimalCapacity(TargetCapacity:longint);
var CapacityMask:longint;
begin
if (TargetCapacity>=0) and (TargetCapacity<MaxListSize) then begin
if TargetCapacity<256 then begin
CapacityMask:=15;
end else if TargetCapacity<1024 then begin
CapacityMask:=255;
end else if TargetCapacity<4096 then begin
CapacityMask:=1023;
end else if TargetCapacity<16384 then begin
CapacityMask:=4095;
end else if TargetCapacity<65536 then begin
CapacityMask:=16383;
end else begin
CapacityMask:=65535;
end;
SetCapacity((TargetCapacity+CapacityMask+CapacityMinimium) and not CapacityMask);
end;
end;
procedure TXMLClassList.SetCount(NewCount:longint);
begin
if (NewCount>=0) and (NewCount<MaxListSize) then begin
SetOptimalCapacity(NewCount);
if InternalCount<NewCount then begin
FillChar(InternalList^[InternalCount],(NewCount-InternalCount)*SizeOf(TXMLClass),#0);
end;
InternalCount:=NewCount;
end;
end;
function TXMLClassList.Add(Item:TXMLClass):longint;
begin
result:=InternalCount;
SetCount(result+1);
InternalList^[result]:=Item;
end;
function TXMLClassList.Append(Item:TXMLClass):longint;
begin
result:=Add(Item);
end;
function TXMLClassList.AddList(List:TXMLClassList):longint;
var Counter,Index:longint;
begin
result:=-1;
for Counter:=0 to List.Count-1 do begin
Index:=Add(List[Counter]);
if Counter=0 then begin
result:=Index;
end;
end;
end;
function TXMLClassList.AppendList(List:TXMLClassList):longint;
begin
result:=AddList(List);
end;
function TXMLClassList.NewClass:TXMLClass;
var Item:TXMLClass;
begin
Item:=TXMLClass.Create;
Add(Item);
result:=Item;
end;
procedure TXMLClassList.Insert(Index:longint;Item:TXMLClass);
var Counter:longint;
begin
if (Index>=0) and (Index<InternalCount) then begin
SetCount(InternalCount+1);
for Counter:=InternalCount-1 downto Index do begin
InternalList^[Counter+1]:=InternalList^[Counter];
end;
InternalList^[Index]:=Item;
end else if Index=InternalCount then begin
Add(Item);
end else if Index>InternalCount then begin
SetCount(Index);
Add(Item);
end;
end;
procedure TXMLClassList.Delete(Index:longint);
var i,j:longint;
begin
if (Index>=0) and (Index<InternalCount) then begin
j:=InternalCount-1;
i:=Index;
Move(InternalList^[i+1],InternalList^[i],(j-i)*SizeOf(TXMLClass));
SetCount(j);
end;
end;
procedure TXMLClassList.DeleteClass(Index:longint);
var i,j:longint;
begin
if (Index>=0) and (Index<InternalCount) then begin
j:=InternalCount-1;
i:=Index;
if assigned(InternalList^[i]) then begin
InternalList^[i].Free;
InternalList^[i]:=nil;
end;
Move(InternalList^[i+1],InternalList^[i],(j-i)*SizeOf(TXMLClass));
SetCount(j);
end;
end;
function TXMLClassList.Remove(Item:TXMLClass):longint;
var i,j,k:longint;
begin
result:=-1;
k:=InternalCount;
j:=-1;
for i:=0 to k-1 do begin
if InternalList^[i]=Item then begin
j:=i;
break;
end;
end;
if j>=0 then begin
dec(k);
Move(InternalList^[j+1],InternalList^[j],(k-j)*SizeOf(TXMLClass));
SetCount(k);
result:=j;
end;
end;
function TXMLClassList.RemoveClass(Item:TXMLClass):longint;
var i,j,k:longint;
begin
result:=-1;
k:=InternalCount;
j:=-1;
for i:=0 to k-1 do begin
if InternalList^[i]=Item then begin
j:=i;
break;
end;
end;
if j>=0 then begin
dec(k);
Move(InternalList^[j+1],InternalList^[j],(k-j)*SizeOf(TXMLClass));
SetCount(k);
Item.Free;
result:=j;
end;
end;
function TXMLClassList.Find(Item:TXMLClass):longint;
var i:longint;
begin
result:=-1;
for i:=0 to InternalCount-1 do begin
if InternalList^[i]=Item then begin
result:=i;
exit;
end;
end;
end;
function TXMLClassList.IndexOf(Item:TXMLClass):longint;
var i:longint;
begin
result:=-1;
for i:=0 to InternalCount-1 do begin
if InternalList^[i]=Item then begin
result:=i;
exit;
end;
end;
end;
procedure TXMLClassList.Exchange(Index1,Index2:longint);
var TempPointer:TXMLClass;
begin
if (Index1>=0) and (Index1<InternalCount) and (Index2>=0) and (Index2<InternalCount) then begin
TempPointer:=InternalList^[Index1];
InternalList^[Index1]:=InternalList^[Index2];
InternalList^[Index2]:=TempPointer;
end;
end;
function TXMLClassList.Push(Item:TXMLClass):longint;
begin
result:=Add(Item);
end;
function TXMLClassList.Pop(var Item:TXMLClass):boolean;
begin
result:=InternalCount>0;
if result then begin
Item:=InternalList^[InternalCount-1];
Delete(InternalCount-1);
end;
end;
function TXMLClassList.Pop:TXMLClass;
begin
if InternalCount>0 then begin
result:=InternalList^[InternalCount-1];
Delete(InternalCount-1);
end else begin
result:=nil;
end;
end;
function TXMLClassList.Last:TXMLClass;
begin
if InternalCount>0 then begin
result:=InternalList^[InternalCount-1];
end else begin
result:=nil;
end;
end;
function TXMLClassList.GetItem(Index:longint):TXMLClass;
begin
if (Index>=0) and (Index<InternalCount) then begin
result:=InternalList^[Index];
end else begin
result:=nil;
end;
end;
procedure TXMLClassList.SetItem(Index:longint;Value:TXMLClass);
begin
if (Index>=0) and (Index<InternalCount) then begin
InternalList^[Index]:=Value;
end;
end;
function TXMLClassList.GetItemPointer(Index:longint):TXMLClass;
begin
if (Index>=0) and (Index<InternalCount) then begin
result:=@InternalList^[Index];
end else begin
result:=nil;
end;
end;
constructor TXMLClassLinkedList.Create;
begin
inherited Create;
ClearWithContentDestroying:=false;
ClearNoFree;
end;
destructor TXMLClassLinkedList.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TXMLClassLinkedList.Clear;
begin
if ClearWithContentDestroying then begin
ClearWithFree;
end else begin
ClearNoFree;
end;
end;
procedure TXMLClassLinkedList.ClearNoFree;
var Current,Next:TXMLClass;
begin
Current:=First;
while assigned(Current) do begin
Next:=Current.Next;
Remove(Current);
Current:=Next;
end;
First:=nil;
Last:=nil;
end;
procedure TXMLClassLinkedList.ClearWithFree;
var Current,Next:TXMLClass;
begin
Current:=First;
while assigned(Current) do begin
Next:=Current.Next;
RemoveClass(Current);
Current:=Next;
end;
First:=nil;
Last:=nil;
end;
procedure TXMLClassLinkedList.Add(Item:TXMLClass);
begin
Item.Next:=nil;
if assigned(Last) then begin
Last.Next:=Item;
Item.Previous:=Last;
end else begin
Item.Previous:=nil;
First:=Item;
end;
Last:=Item;
end;
procedure TXMLClassLinkedList.Append(Item:TXMLClass);
begin
Add(Item);
end;
procedure TXMLClassLinkedList.AddLinkedList(List:TXMLClassLinkedList);
begin
Last.Next:=List.First;
if assigned(List.First) then begin
List.First.Previous:=Last;
end;
Last:=List.Last;
List.First:=nil;
List.Last:=nil;
end;
procedure TXMLClassLinkedList.AppendLinkedList(List:TXMLClassLinkedList);
begin
AddLinkedList(List);
end;
procedure TXMLClassLinkedList.Remove(Item:TXMLClass);
begin
if assigned(Item) then begin
if assigned(Item.Next) then begin
Item.Next.Previous:=Item.Previous;
end else if Last=Item then begin
Last:=Item.Previous;
end;
if assigned(Item.Previous) then begin
Item.Previous.Next:=Item.Next;
end else if First=Item then begin
First:=Item.Next;
end;
Item.Previous:=nil;
Item.Next:=nil;
end;
end;
procedure TXMLClassLinkedList.RemoveClass(Item:TXMLClass);
begin
if assigned(Item) then begin
Remove(Item);
Item.Destroy;
end;
end;
procedure TXMLClassLinkedList.Push(Item:TXMLClass);
begin
Add(Item);
end;
function TXMLClassLinkedList.Pop(var Item:TXMLClass):boolean;
begin
result:=assigned(Last);
if result then begin
Item:=Last;
Remove(Last);
end;
end;
function TXMLClassLinkedList.Pop:TXMLClass;
begin
result:=Last;
if assigned(Last) then begin
Remove(Last);
end;
end;
function TXMLClassLinkedList.Count:longint;
var Current:TXMLClass;
begin
result:=0;
Current:=First;
while assigned(Current) do begin
inc(result);
Current:=Current.Next;
end;
end;
constructor TXMLStringTree.Create;
begin
inherited Create;
Root:=nil;
Clear;
end;
destructor TXMLStringTree.Destroy;
begin
Clear;
inherited Destroy;
end;
function TXMLStringTree.CreateStringTreeNode(AChar:ansichar):PXMLStringTreeNode;
begin
GetMem(result,SizeOf(TXMLStringTreeNode));
result^.TheChar:=AChar;
result^.Data:=0;
result^.DataExist:=false;
result^.Prevoius:=nil;
result^.Next:=nil;
result^.Up:=nil;
result^.Down:=nil;
end;
procedure TXMLStringTree.DestroyStringTreeNode(Node:PXMLStringTreeNode);
begin
if assigned(Node) then begin
DestroyStringTreeNode(Node^.Next);
DestroyStringTreeNode(Node^.Down);
FreeMem(Node);
end;
end;
procedure TXMLStringTree.Clear;
begin
DestroyStringTreeNode(Root);
Root:=nil;
end;
procedure TXMLStringTree.DumpTree;
var Ident:longint;
procedure DumpNode(Node:PXMLStringTreeNode);
var SubNode:PXMLStringTreeNode;
IdentCounter,IdentOld:longint;
begin
for IdentCounter:=1 to Ident do begin
write(' ');
end;
write(Node^.TheChar);
IdentOld:=Ident;
SubNode:=Node^.Next;
while assigned(SubNode) do begin
write(SubNode.TheChar);
if not assigned(SubNode^.Next) then begin
break;
end;
inc(Ident);
SubNode:=SubNode^.Next;
end;
writeln;
inc(Ident);
while assigned(SubNode) and (SubNode<>Node) do begin
if assigned(SubNode^.Down) then begin
DumpNode(SubNode^.Down);
end;
SubNode:=SubNode^.Prevoius;
dec(Ident);
end;
Ident:=IdentOld;
if assigned(Node^.Down) then begin
DumpNode(Node^.Down);
end;
end;
begin
Ident:=0;
DumpNode(Root);
end;
procedure TXMLStringTree.DumpList;
procedure DumpNode(Node:PXMLStringTreeNode;ParentStr:ansistring);
begin
if assigned(Node) then begin
ParentStr:=ParentStr;
if Node^.DataExist then begin
writeln(ParentStr+Node^.TheChar);
end;
if assigned(Node^.Next) then begin
DumpNode(Node^.Next,ParentStr+Node^.TheChar);
end;
if assigned(Node^.Down) then begin
DumpNode(Node^.Down,ParentStr);
end;
end;
end;
begin
if assigned(Root) then begin
DumpNode(Root,'');
end;
end;
procedure TXMLStringTree.AppendTo(DestStringTree:TXMLStringTree);
procedure DumpNode(Node:PXMLStringTreeNode;ParentStr:ansistring);
begin
if assigned(Node) then begin
ParentStr:=ParentStr;
if Node^.DataExist then begin
DestStringTree.Add(ParentStr+Node^.TheChar,Node^.Data);
end;
if assigned(Node^.Next) then begin
DumpNode(Node^.Next,ParentStr+Node^.TheChar);
end;
if assigned(Node^.Down) then begin
DumpNode(Node^.Down,ParentStr);
end;
end;
end;
begin
if assigned(DestStringTree) and assigned(Root) then begin
DumpNode(Root,'');
end;
end;
procedure TXMLStringTree.Optimize(DestStringTree:TXMLStringTree);
procedure DumpNode(Node:PXMLStringTreeNode;ParentStr:ansistring);
begin
if assigned(Node) then begin
ParentStr:=ParentStr;
if Node^.DataExist then begin
DestStringTree.Add(ParentStr+Node^.TheChar,Node^.Data);
end;
if assigned(Node^.Next) then begin
DumpNode(Node^.Next,ParentStr+Node^.TheChar);
end;
if assigned(Node^.Down) then begin
DumpNode(Node^.Down,ParentStr);
end;
end;
end;
begin
if assigned(DestStringTree) then begin
DestStringTree.Clear;
if assigned(Root) then begin
DumpNode(Root,'');
end;
end;
end;
function TXMLStringTree.Add(Content:ansistring;Data:TXMLStringTreeData;Replace:boolean=false):boolean;
var StringLength,Position,PositionCounter:longint;
NewNode,LastNode,Node:PXMLStringTreeNode;
StringChar,NodeChar:ansichar;
begin
result:=false;
StringLength:=length(Content);
if StringLength>0 then begin
LastNode:=nil;
Node:=Root;
for Position:=1 to StringLength do begin
StringChar:=Content[Position];
if assigned(Node) then begin
NodeChar:=Node^.TheChar;
if NodeChar=StringChar then begin
LastNode:=Node;
Node:=Node^.Next;
end else begin
while (NodeChar<StringChar) and assigned(Node^.Down) do begin
Node:=Node^.Down;
NodeChar:=Node^.TheChar;
end;
if NodeChar=StringChar then begin
LastNode:=Node;
Node:=Node^.Next;
end else begin
NewNode:=CreateStringTreeNode(StringChar);
if NodeChar<StringChar then begin
NewNode^.Down:=Node^.Down;
NewNode^.Up:=Node;
if assigned(NewNode^.Down) then begin
NewNode^.Down^.Up:=NewNode;
end;
NewNode^.Prevoius:=Node^.Prevoius;
Node^.Down:=NewNode;
end else if NodeChar>StringChar then begin
NewNode^.Down:=Node;
NewNode^.Up:=Node^.Up;
if assigned(NewNode^.Up) then begin
NewNode^.Up^.Down:=NewNode;
end;
NewNode^.Prevoius:=Node^.Prevoius;
if not assigned(NewNode^.Up) then begin
if assigned(NewNode^.Prevoius) then begin
NewNode^.Prevoius^.Next:=NewNode;
end else begin
Root:=NewNode;
end;
end;
Node^.Up:=NewNode;
end;
LastNode:=NewNode;
Node:=LastNode^.Next;
end;
end;
end else begin
for PositionCounter:=Position to StringLength do begin
NewNode:=CreateStringTreeNode(Content[PositionCounter]);
if assigned(LastNode) then begin
NewNode^.Prevoius:=LastNode;
LastNode^.Next:=NewNode;
LastNode:=LastNode^.Next;
end else begin
if not assigned(Root) then begin
Root:=NewNode;
LastNode:=Root;
end;
end;
end;
break;
end;
end;
if assigned(LastNode) then begin
if Replace or not LastNode^.DataExist then begin
LastNode^.Data:=Data;
LastNode^.DataExist:=true;
result:=true;
end;
end;
end;
end;
function TXMLStringTree.Delete(Content:ansistring):boolean;
var StringLength,Position:longint;
Node:PXMLStringTreeNode;
StringChar,NodeChar:ansichar;
begin
result:=false;
StringLength:=length(Content);
if StringLength>0 then begin
Node:=Root;
for Position:=1 to StringLength do begin
StringChar:=Content[Position];
if assigned(Node) then begin
NodeChar:=Node^.TheChar;
while (NodeChar<>StringChar) and assigned(Node^.Down) do begin
Node:=Node^.Down;
NodeChar:=Node^.TheChar;
end;
if NodeChar=StringChar then begin
if (Position=StringLength) and Node^.DataExist then begin
Node^.DataExist:=false;
result:=true;
exit;
end;
Node:=Node^.Next;
end else begin
break;
end;
end else begin
break;
end;
end;
end;
end;
function TXMLStringTree.Find(Content:ansistring;var Data:TXMLStringTreeData):boolean;
var StringLength,Position:longint;
Node:PXMLStringTreeNode;
StringChar,NodeChar:ansichar;
begin
result:=false;
StringLength:=length(Content);
if StringLength>0 then begin
Node:=Root;
for Position:=1 to StringLength do begin
StringChar:=Content[Position];
if assigned(Node) then begin
NodeChar:=Node^.TheChar;
while (NodeChar<>StringChar) and assigned(Node^.Down) do begin
Node:=Node^.Down;
NodeChar:=Node^.TheChar;
end;
if NodeChar=StringChar then begin
if (Position=StringLength) and Node^.DataExist then begin
Data:=Node^.Data;
result:=true;
exit;
end;
Node:=Node^.Next;
end else begin
break;
end;
end else begin
break;
end;
end;
end;
end;
function TXMLStringTree.FindEx(Content:ansistring;var Data:TXMLStringTreeData;var Len:longint):boolean;
var StringLength,Position:longint;
Node:PXMLStringTreeNode;
StringChar,NodeChar:ansichar;
begin
result:=false;
Len:=0;
StringLength:=length(Content);
if StringLength>0 then begin
Node:=Root;
for Position:=1 to StringLength do begin
StringChar:=Content[Position];
if assigned(Node) then begin
NodeChar:=Node^.TheChar;
while (NodeChar<>StringChar) and assigned(Node^.Down) do begin
Node:=Node^.Down;
NodeChar:=Node^.TheChar;
end;
if NodeChar=StringChar then begin
if Node^.DataExist then begin
Len:=Position;
Data:=Node^.Data;
result:=true;
end;
Node:=Node^.Next;
end else begin
break;
end;
end else begin
break;
end;
end;
end;
end;
constructor TXMLItem.Create;
begin
inherited Create;
Items:=TXMLItemList.Create;
end;
destructor TXMLItem.Destroy;
begin
Items.Destroy;
inherited Destroy;
end;
procedure TXMLItem.Clear;
begin
Items.Clear;
end;
procedure TXMLItem.Add(Item:TXMLItem);
begin
Items.Add(Item);
end;
procedure TXMLItem.Assign(From:TXMLItem);
var i:longint;
NewItem:TXMLItem;
begin
Items.ClearWithFree;
NewItem:=nil;
for i:=0 to Items.Count-1 do begin
if Items[i] is TXMLTag then begin
NewItem:=TXMLTag.Create;
end else if Items[i] is TXMLCommentTag then begin
NewItem:=TXMLCommentTag.Create;
end else if Items[i] is TXMLScriptTag then begin
NewItem:=TXMLScriptTag.Create;
end else if Items[i] is TXMLProcessTag then begin
NewItem:=TXMLProcessTag.Create;
end else if Items[i] is TXMLCDATATag then begin
NewItem:=TXMLCDATATag.Create;
end else if Items[i] is TXMLDOCTYPETag then begin
NewItem:=TXMLDOCTYPETag.Create;
end else if Items[i] is TXMLExtraTag then begin
NewItem:=TXMLExtraTag.Create;
end else if Items[i] is TXMLText then begin
NewItem:=TXMLText.Create;
end else if Items[i] is TXMLItem then begin
NewItem:=Items[i].Create;
end else begin
continue;
end;
NewItem.Assign(Items[i]);
Items.Add(NewItem);
end;
end;
function TXMLItem.FindTag(const TagName:ansistring):TXMLTag;
begin
result:=Items.FindTag(TagName);
end;
constructor TXMLItemList.Create;
begin
inherited Create;
ClearWithContentDestroying:=true;
//CapacityMask:=$f;
CapacityMinimium:=0;
end;
destructor TXMLItemList.Destroy;
begin
ClearWithFree;
inherited Destroy;
end;
function TXMLItemList.NewClass:TXMLItem;
begin
result:=TXMLItem.Create;
Add(result);
end;
function TXMLItemList.GetItem(Index:longint):TXMLItem;
begin
result:=TXMLItem(inherited Items[Index]);
end;
procedure TXMLItemList.SetItem(Index:longint;Value:TXMLItem);
begin
inherited Items[Index]:=Value;
end;
function TXMLItemList.FindTag(const TagName:ansistring):TXMLTag;
var i:longint;
Item:TXMLItem;
begin
result:=nil;
for i:=0 to Count-1 do begin
Item:=TXMLItem(inherited Items[i]);
if (assigned(Item) and (Item is TXMLTag)) and (TXMLTag(Item).Name=TagName) then begin
result:=TXMLTag(Item);
break;
end;
end;
end;
constructor TXMLParameter.Create;
begin
inherited Create;
Name:='';
Value:='';
end;
destructor TXMLParameter.Destroy;
begin
Name:='';
Value:='';
inherited Destroy;
end;
procedure TXMLParameter.Assign(From:TXMLParameter);
begin
Name:=From.Name;
Value:=From.Value;
end;
constructor TXMLText.Create;
begin
inherited Create;
Text:='';
end;
destructor TXMLText.Destroy;
begin
Text:='';
inherited Destroy;
end;
procedure TXMLText.Assign(From:TXMLItem);
begin
inherited Assign(From);
if From is TXMLText then begin
Text:=TXMLText(From).Text;
end;
end;
procedure TXMLText.SetText(AText:ansistring);
begin
Text:=AText;
end;
constructor TXMLCommentTag.Create;
begin
inherited Create;
Text:='';
end;
destructor TXMLCommentTag.Destroy;
begin
Text:='';
inherited Destroy;
end;
procedure TXMLCommentTag.Assign(From:TXMLItem);
begin
inherited Assign(From);
if From is TXMLCommentTag then begin
Text:=TXMLCommentTag(From).Text;
end;
end;
procedure TXMLCommentTag.SetText(AText:ansistring);
begin
Text:=AText;
end;
constructor TXMLTag.Create;
begin
inherited Create;
Name:='';
Parameter:=nil;
end;
destructor TXMLTag.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TXMLTag.Clear;
var Counter:longint;
begin
inherited Clear;
for Counter:=0 to length(Parameter)-1 do begin
Parameter[Counter].Free;
end;
SetLength(Parameter,0);
Name:='';
end;
procedure TXMLTag.Assign(From:TXMLItem);
var Counter:longint;
begin
inherited Assign(From);
if From is TXMLTag then begin
for Counter:=0 to length(Parameter)-1 do begin
Parameter[Counter].Free;
end;
SetLength(Parameter,0);
Name:=TXMLTag(From).Name;
for Counter:=0 to length(TXMLTag(From).Parameter)-1 do begin
AddParameter(TXMLTag(From).Parameter[Counter].Name,TXMLTag(From).Parameter[Counter].Value);
end;
end;
end;
function TXMLTag.FindParameter(ParameterName:ansistring):TXMLParameter;
var i:longint;
begin
for i:=0 to length(Parameter)-1 do begin
if Parameter[i].Name=ParameterName then begin
result:=Parameter[i];
exit;
end;
end;
result:=nil;
end;
function TXMLTag.GetParameter(ParameterName:ansistring;default:ansistring=''):ansistring;
var i:longint;
begin
for i:=0 to length(Parameter)-1 do begin
if Parameter[i].Name=ParameterName then begin
result:=Parameter[i].Value;
exit;
end;
end;
result:=default;
end;
function TXMLTag.AddParameter(AParameter:TXMLParameter):boolean;
var Index:longint;
begin
try
Index:=length(Parameter);
SetLength(Parameter,Index+1);
Parameter[Index]:=AParameter;
result:=true;
except
result:=false;
end;
end;
function TXMLTag.AddParameter(Name:ansistring;Value:TXMLString):boolean;
var AParameter:TXMLParameter;
begin
AParameter:=TXMLParameter.Create;
AParameter.Name:=Name;
AParameter.Value:=Value;
result:=AddParameter(AParameter);
end;
function TXMLTag.RemoveParameter(AParameter:TXMLParameter):boolean;
var Found,Counter:longint;
begin
result:=false;
try
Found:=-1;
for Counter:=0 to length(Parameter)-1 do begin
if Parameter[Counter]=AParameter then begin
Found:=Counter;
break;
end;
end;
if Found>=0 then begin
for Counter:=Found to length(Parameter)-2 do begin
Parameter[Counter]:=Parameter[Counter+1];
end;
SetLength(Parameter,length(Parameter)-1);
AParameter.Destroy;
result:=true;
end;
except
end;
end;
function TXMLTag.RemoveParameter(ParameterName:ansistring):boolean;
begin
result:=RemoveParameter(FindParameter(ParameterName));
end;
constructor TXMLProcessTag.Create;
begin
inherited Create;
end;
destructor TXMLProcessTag.Destroy;
begin
inherited Destroy;
end;
procedure TXMLProcessTag.Assign(From:TXMLItem);
begin
inherited Assign(From);
end;
constructor TXMLScriptTag.Create;
begin
inherited Create;
Text:='';
end;
destructor TXMLScriptTag.Destroy;
begin
Text:='';
inherited Destroy;
end;
procedure TXMLScriptTag.Assign(From:TXMLItem);
begin
inherited Assign(From);
if From is TXMLScriptTag then begin
Text:=TXMLScriptTag(From).Text;
end;
end;
procedure TXMLScriptTag.SetText(AText:ansistring);
begin
Text:=AText;
end;
constructor TXMLCDataTag.Create;
begin
inherited Create;
Text:='';
end;
destructor TXMLCDataTag.Destroy;
begin
Text:='';
inherited Destroy;
end;
procedure TXMLCDataTag.Assign(From:TXMLItem);
begin
inherited Assign(From);
if From is TXMLCDataTag then begin
Text:=TXMLCDataTag(From).Text;
end;
end;
procedure TXMLCDataTag.SetText(AText:ansistring);
begin
Text:=AText;
end;
constructor TXMLDOCTYPETag.Create;
begin
inherited Create;
Text:='';
end;
destructor TXMLDOCTYPETag.Destroy;
begin
Text:='';
inherited Destroy;
end;
procedure TXMLDOCTYPETag.Assign(From:TXMLItem);
begin
inherited Assign(From);
if From is TXMLDOCTYPETag then begin
Text:=TXMLDOCTYPETag(From).Text;
end;
end;
procedure TXMLDOCTYPETag.SetText(AText:ansistring);
begin
Text:=AText;
end;
constructor TXMLExtraTag.Create;
begin
inherited Create;
Text:='';
end;
destructor TXMLExtraTag.Destroy;
begin
Text:='';
inherited Destroy;
end;
procedure TXMLExtraTag.Assign(From:TXMLItem);
begin
inherited Assign(From);
if From is TXMLExtraTag then begin
Text:=TXMLExtraTag(From).Text;
end;
end;
procedure TXMLExtraTag.SetText(AText:ansistring);
begin
Text:=AText;
end;
constructor TXML.Create;
begin
inherited Create;
InitializeEntites;
Root:=TXMLItem.Create;
AutomaticAloneTagDetection:=true;
FormatIndent:=true;
FormatIndentText:=false;
end;
destructor TXML.Destroy;
begin
Root.Free;
inherited Destroy;
end;
procedure TXML.Assign(From:TXML);
begin
Root.Assign(From.Root);
AutomaticAloneTagDetection:=From.AutomaticAloneTagDetection;
FormatIndent:=From.FormatIndent;
FormatIndentText:=From.FormatIndentText;
end;
function TXML.Parse(Stream:TStream):boolean;
const NameCanBeginWithCharSet:set of ansichar=['A'..'Z','a'..'z','_'];
NameCanContainCharSet:set of ansichar=['A'..'Z','a'..'z','0'..'9','.',':','_','-'];
BlankCharSet:set of ansichar=[#0..#$20];//[#$9,#$A,#$D,#$20];
type TEncoding=(etASCII,etUTF8,etUTF16);
var Errors:boolean;
CurrentChar:ansichar;
StreamEOF:boolean;
Encoding:TEncoding;
function IsEOF:boolean;
begin
result:=StreamEOF or (Stream.Position>Stream.Size);
end;
function IsEOFOrErrors:boolean;
begin
result:=IsEOF or Errors;
end;
function NextChar:ansichar;
begin
if Stream.Read(CurrentChar,SizeOf(ansichar))<>SizeOf(ansichar) then begin
StreamEOF:=true;
CurrentChar:=#0;
end;
result:=CurrentChar;
//system.Write(result);
end;
procedure SkipBlank;
begin
while (CurrentChar in BlankCharSet) and not IsEOFOrErrors do begin
NextChar;
end;
end;
function GetName:ansistring;
var i:longint;
begin
result:='';
i:=0;
if (CurrentChar in NameCanBeginWithCharSet) and not IsEOFOrErrors then begin
while (CurrentChar in NameCanContainCharSet) and not IsEOFOrErrors do begin
inc(i);
if (i+1)>length(result) then begin
SetLength(result,NextPowerOfTwo(i+1));
end;
result[i]:=CurrentChar;
NextChar;
end;
end;
SetLength(result,i);
end;
function ExpectToken(const S:ansistring):boolean; overload;
var i:longint;
begin
result:=true;
for i:=1 to length(S) do begin
if S[i]<>CurrentChar then begin
result:=false;
break;
end;
NextChar;
end;
end;
function ExpectToken(const c:ansichar):boolean; overload;
begin
result:=false;
if c=CurrentChar then begin
result:=true;
NextChar;
end;
end;
function GetUntil(var Content:ansistring;const TerminateToken:ansistring):boolean;
var i,j,OldPosition:longint;
OldEOF:boolean;
OldChar:ansichar;
begin
result:=false;
j:=0;
Content:='';
while not IsEOFOrErrors do begin
if (length(TerminateToken)>0) and (TerminateToken[1]=CurrentChar) and (((Stream.Size-Stream.Position)+1)>=length(TerminateToken)) then begin
OldPosition:=Stream.Position;
OldEOF:=StreamEOF;
OldChar:=CurrentChar;
for i:=1 to length(TerminateToken) do begin
if TerminateToken[i]=CurrentChar then begin
if i=length(TerminateToken) then begin
NextChar;
SetLength(Content,j);
result:=true;
exit;
end;
end else begin
break;
end;
NextChar;
end;
Stream.Seek(OldPosition,soFromBeginning);
StreamEOF:=OldEOF;
CurrentChar:=OldChar;
end;
inc(j);
if (j+1)>length(Content) then begin
SetLength(Content,NextPowerOfTwo(j+1));
end;
Content[j]:=CurrentChar;
NextChar;
end;
SetLength(Content,j);
end;
function GetDecimalValue:longint;
var Negitive:boolean;
begin
Negitive:=CurrentChar='-';
if Negitive then begin
NextChar;
end else if CurrentChar='+' then begin
NextChar;
end;
result:=0;
while (CurrentChar in ['0'..'9']) and not IsEOFOrErrors do begin
result:=(result*10)+(ord(CurrentChar)-ord('0'));
NextChar;
end;
if Negitive then begin
result:=-result;
end;
end;
function GetHeximalValue:longint;
var Negitive:boolean;
Value:longint;
begin
Negitive:=CurrentChar='-';
if Negitive then begin
NextChar;
end else if CurrentChar='+' then begin
NextChar;
end;
result:=0;
Value:=0;
while not IsEOFOrErrors do begin
case CurrentChar of
'0'..'9':begin
Value:=byte(CurrentChar)-ord('0');
end;
'A'..'F':begin
Value:=byte(CurrentChar)-ord('A')+$a;
end;
'a'..'f':begin
Value:=byte(CurrentChar)-ord('a')+$a;
end;
else begin
break;
end;
end;
result:=(result*16)+Value;
NextChar;
end;
if Negitive then begin
result:=-result;
end;
end;
function GetEntity:TXMLString;
var Value:longint;
Entity:ansistring;
c:TXMLChar;
EntityLink:TXMLStringTreeData;
begin
result:='';
if CurrentChar='&' then begin
NextChar;
if not IsEOF then begin
if CurrentChar='#' then begin
NextChar;
if IsEOF then begin
Errors:=true;
end else begin
if CurrentChar='x' then begin
NextChar;
Value:=GetHeximalValue;
end else begin
Value:=GetDecimalValue;
end;
if CurrentChar=';' then begin
NextChar;
{$ifdef UNICODE}
c:=widechar(word(Value));
{$else}
c:=ansichar(byte(Value));
{$endif}
result:=c;
end else begin
Errors:=true;
end;
end;
end else begin
Entity:='&';
while (CurrentChar in ['a'..'z','A'..'Z','0'..'9','_']) and not IsEOFOrErrors do begin
Entity:=Entity+CurrentChar;
NextChar;
end;
if CurrentChar=';' then begin
Entity:=Entity+CurrentChar;
NextChar;
if EntityStringTree.Find(Entity,EntityLink) then begin
result:=EntityChars[EntityLink,2];
end else begin
result:=Entity;
end;
end else begin
Errors:=true;
end;
end;
end;
end;
end;
function ParseTagParameterValue(TerminateChar:ansichar):TXMLString;
var i,wc,c:longint;
begin
result:='';
SkipBlank;
i:=0;
while (CurrentChar<>TerminateChar) and not IsEOFOrErrors do begin
if (Encoding=etUTF8) and (ord(CurrentChar)>=$80) then begin
wc:=ord(CurrentChar) and $3f;
if (wc and $20)<>0 then begin
NextChar;
c:=ord(CurrentChar);
if (c and $c0)<>$80 then begin
break;
end;
wc:=(wc shl 6) or (c and $3f);
end;
NextChar;
c:=ord(CurrentChar);
if (c and $c0)<>$80 then begin
break;
end;
wc:=(wc shl 6) or (c and $3f);
NextChar;
inc(i);
if (i+1)>length(result) then begin
SetLength(result,NextPowerOfTwo(i+1));
end;
{$ifdef UNICODE}
result[i]:=widechar(wc);
{$else}
result[i]:=ansichar(wc);
{$endif}
end else if CurrentChar='&' then begin
SetLength(result,i);
result:=result+GetEntity;
i:=length(result);
end else begin
inc(i);
if (i+1)>length(result) then begin
SetLength(result,NextPowerOfTwo(i+1));
end;
{$ifdef UNICODE}
result[i]:=widechar(word(byte(CurrentChar)+0));
{$else}
result[i]:=CurrentChar;
{$endif}
NextChar;
end;
end;
SetLength(result,i);
NextChar;
end;
procedure ParseTagParameter(XMLTag:TXMLTag);
var ParameterName,ParameterValue:ansistring;
TerminateChar:ansichar;
begin
SkipBlank;
while (CurrentChar in NameCanBeginWithCharSet) and not IsEOFOrErrors do begin
ParameterName:=GetName;
SkipBlank;
if CurrentChar='=' then begin
NextChar;
if IsEOFOrErrors then begin
Errors:=true;
break;
end;
end else begin
Errors:=true;
break;
end;
SkipBlank;
if CurrentChar in ['''','"'] then begin
TerminateChar:=CurrentChar;
NextChar;
if IsEOFOrErrors then begin
Errors:=true;
break;
end;
ParameterValue:=ParseTagParameterValue(TerminateChar);
if Errors then begin
break;
end else begin
XMLTag.AddParameter(ParameterName,ParameterValue);
SkipBlank;
end;
end else begin
Errors:=true;
break;
end;
end;
end;
procedure Process(ParentItem:TXMLItem;Closed:boolean);
var FinishLevel:boolean;
procedure ParseText;
var Text:TXMLString;
XMLText:TXMLText;
i,wc,c:longint;
{$ifndef UNICODE}
w:ansistring;
{$endif}
begin
SkipBlank;
if CurrentChar='<' then begin
exit;
end;
i:=0;
Text:='';
SetLength(Text,16);
while (CurrentChar<>'<') and not IsEOFOrErrors do begin
if (Encoding=etUTF8) and (ord(CurrentChar)>=$80) then begin
wc:=ord(CurrentChar) and $3f;
if (wc and $20)<>0 then begin
NextChar;
c:=ord(CurrentChar);
if (c and $c0)<>$80 then begin
break;
end;
wc:=(wc shl 6) or (c and $3f);
end;
NextChar;
c:=ord(CurrentChar);
if (c and $c0)<>$80 then begin
break;
end;
wc:=(wc shl 6) or (c and $3f);
NextChar;
{$ifdef UNICODE}
if wc<=$d7ff then begin
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=widechar(word(wc));
end else if wc<=$dfff then begin
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=#$fffd;
end else if wc<=$fffd then begin
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=widechar(word(wc));
end else if wc<=$ffff then begin
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=#$fffd;
end else if wc<=$10ffff then begin
dec(wc,$10000);
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=widechar(word((wc shr 10) or $d800));
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=widechar(word((wc and $3ff) or $dc00));
end else begin
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=#$fffd;
end;
{$else}
if wc<$80 then begin
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=ansichar(byte(wc));
end else begin
w:=UTF32CharToUTF8(wc);
if length(w)>0 then begin
inc(i);
if (i+length(w)+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+length(w)+1));
end;
Move(w[1],Text[i],length(w));
inc(i,length(w)-1);
end;
end;
{$endif}
end else if CurrentChar='&' then begin
SetLength(Text,i);
Text:=Text+GetEntity;
i:=length(Text);
end else if CurrentChar in BlankCharSet then begin
{$ifdef UNICODE}
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=widechar(word(byte(CurrentChar)+0));
{$else}
wc:=ord(CurrentChar);
if wc<$80 then begin
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=ansichar(byte(wc));
end else begin
w:=UTF32CharToUTF8(wc);
if length(w)>0 then begin
inc(i);
if (i+length(w)+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+length(w)+1));
end;
Move(w[1],Text[i],length(w));
inc(i,length(w)-1);
end;
end;
{$endif}
SkipBlank;
end else begin
{$ifdef UNICODE}
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=widechar(word(byte(CurrentChar)+0));
{$else}
wc:=ord(CurrentChar);
if wc<$80 then begin
inc(i);
if (i+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+1));
end;
Text[i]:=ansichar(byte(wc));
end else begin
w:=UTF32CharToUTF8(wc);
if length(w)>0 then begin
inc(i);
if (i+length(w)+1)>length(Text) then begin
SetLength(Text,NextPowerOfTwo(i+length(w)+1));
end;
Move(w[1],Text[i],length(w));
inc(i,length(w)-1);
end;
end;
{$endif}
NextChar;
end;
end;
SetLength(Text,i);
if length(Text)<>0 then begin
XMLText:=TXMLText.Create;
XMLText.Text:=Text;
ParentItem.Add(XMLText);
end;
end;
procedure ParseProcessTag;
var TagName,EncodingName:ansistring;
XMLProcessTag:TXMLProcessTag;
begin
if not ExpectToken('?') then begin
Errors:=true;
exit;
end;
TagName:=GetName;
if IsEOF or Errors then begin
Errors:=true;
exit;
end;
XMLProcessTag:=TXMLProcessTag.Create;
XMLProcessTag.Name:=TagName;
ParentItem.Add(XMLProcessTag);
ParseTagParameter(XMLProcessTag);
if not ExpectToken('?>') then begin
Errors:=true;
exit;
end;
if XMLProcessTag.Name='xml' then begin
EncodingName:=UPPERCASE(XMLProcessTag.GetParameter('encoding','ascii'));
if EncodingName='UTF-8' then begin
Encoding:=etUTF8;
end else if EncodingName='UTF-16' then begin
Encoding:=etUTF16;
end else begin
Encoding:=etASCII;
end;
end;
end;
procedure ParseScriptTag;
var XMLScriptTag:TXMLScriptTag;
begin
if not ExpectToken('%') then begin
Errors:=true;
exit;
end;
if IsEOFOrErrors then begin
Errors:=true;
exit;
end;
XMLScriptTag:=TXMLScriptTag.Create;
ParentItem.Add(XMLScriptTag);
if not GetUntil(XMLScriptTag.Text,'%>') then begin
Errors:=true;
end;
end;
procedure ParseCommentTag;
var XMLCommentTag:TXMLCommentTag;
begin
if not ExpectToken('--') then begin
Errors:=true;
exit;
end;
if IsEOFOrErrors then begin
Errors:=true;
exit;
end;
XMLCommentTag:=TXMLCommentTag.Create;
ParentItem.Add(XMLCommentTag);
if not GetUntil(XMLCommentTag.Text,'-->') then begin
Errors:=true;
end;
end;
procedure ParseCDATATag;
var XMLCDataTag:TXMLCDataTag;
begin
if not ExpectToken('[CDATA[') then begin
Errors:=true;
exit;
end;
if IsEOFOrErrors then begin
Errors:=true;
exit;
end;
XMLCDataTag:=TXMLCDataTag.Create;
ParentItem.Add(XMLCDataTag);
if not GetUntil(XMLCDataTag.Text,']]>') then begin
Errors:=true;
end;
end;
procedure ParseDOCTYPEOrExtraTag;
var Content:ansistring;
XMLDOCTYPETag:TXMLDOCTYPETag;
XMLExtraTag:TXMLExtraTag;
begin
Content:='';
if not GetUntil(Content,'>') then begin
Errors:=true;
exit;
end;
if POS('DOCTYPE',Content)=1 then begin
XMLDOCTYPETag:=TXMLDOCTYPETag.Create;
ParentItem.Add(XMLDOCTYPETag);
XMLDOCTYPETag.Text:=TRIMLEFT(COPY(Content,8,length(Content)-7));
end else begin
XMLExtraTag:=TXMLExtraTag.Create;
ParentItem.Add(XMLExtraTag);
XMLExtraTag.Text:=Content;
end;
end;
procedure ParseTag;
var TagName:ansistring;
XMLTag:TXMLTag;
IsAloneTag:boolean;
begin
if CurrentChar='/' then begin
NextChar;
if IsEOFOrErrors then begin
Errors:=true;
exit;
end;
TagName:='/'+GetName;
end else begin
TagName:=GetName;
end;
if IsEOFOrErrors then begin
Errors:=true;
exit;
end;
XMLTag:=TXMLTag.Create;
XMLTag.Name:=TagName;
ParseTagParameter(XMLTag);
IsAloneTag:=CurrentChar='/';
if IsAloneTag then begin
NextChar;
if IsEOFOrErrors then begin
Errors:=true;
exit;
end;
end;
if CurrentChar<>'>' then begin
Errors:=true;
exit;
end;
NextChar;
if (ParentItem<>Root) and (ParentItem is TXMLTag) and (XMLTag.Name='/'+TXMLTag(ParentItem).Name) then begin
XMLTag.Destroy;
FinishLevel:=true;
Closed:=true;
end else begin
ParentItem.Add(XMLTag);
if not IsAloneTag then begin
Process(XMLTag,false);
end;
end;
// IsAloneTag:=false;
end;
begin
FinishLevel:=false;
while not (IsEOFOrErrors or FinishLevel) do begin
ParseText;
if CurrentChar='<' then begin
NextChar;
if not IsEOFOrErrors then begin
if CurrentChar='/' then begin
ParseTag;
end else if CurrentChar='?' then begin
ParseProcessTag;
end else if CurrentChar='%' then begin
ParseScriptTag;
end else if CurrentChar='!' then begin
NextChar;
if not IsEOFOrErrors then begin
if CurrentChar='-' then begin
ParseCommentTag;
end else if CurrentChar='[' then begin
ParseCDATATag;
end else begin
ParseDOCTYPEOrExtraTag;
end;
end;
end else begin
ParseTag;
end;
end;
end;
end;
if not Closed then begin
Errors:=true;
end;
end;
begin
Encoding:=etASCII;
Errors:=false;
CurrentChar:=#0;
Root.Clear;
StreamEOF:=false;
Stream.Seek(0,soFromBeginning);
NextChar;
Process(Root,true);
if Errors then begin
Root.Clear;
end;
result:=not Errors;
end;
function TXML.Read(Stream:TStream):boolean;
begin
result:=Parse(Stream);
end;
function TXML.Write(Stream:TStream;IdentSize:longint=2):boolean;
var IdentLevel:longint;
Errors:boolean;
procedure Process(Item:TXMLItem;DoIndent:boolean);
var Line:ansistring;
Counter:longint;
TagWithSingleLineText,ItemsText:boolean;
procedure WriteLineEx(Line:ansistring);
begin
if length(Line)>0 then begin
if Stream.Write(Line[1],length(Line))<>length(Line) then begin
Errors:=true;
end;
end;
end;
procedure WriteLine(Line:ansistring);
begin
if FormatIndent and DoIndent then begin
Line:=Line+#10;
end;
if length(Line)>0 then begin
if Stream.Write(Line[1],length(Line))<>length(Line) then begin
Errors:=true;
end;
end;
end;
begin
if not Errors then begin
if assigned(Item) then begin
inc(IdentLevel,IdentSize);
Line:='';
if FormatIndent and DoIndent then begin
for Counter:=1 to IdentLevel do begin
Line:=Line+' ';
end;
end;
if Item is TXMLText then begin
if FormatIndentText then begin
Line:=Line+ConvertToEntities(TXMLText(Item).Text,IdentLevel);
end else begin
Line:=ConvertToEntities(TXMLText(Item).Text);
end;
WriteLine(Line);
for Counter:=0 to Item.Items.Count-1 do begin
Process(Item.Items[Counter],DoIndent);
end;
end else if Item is TXMLCommentTag then begin
Line:=Line+'<!--'+TXMLCommentTag(Item).Text+'-->';
WriteLine(Line);
for Counter:=0 to Item.Items.Count-1 do begin
Process(Item.Items[Counter],DoIndent);
end;
end else if Item is TXMLProcessTag then begin
Line:=Line+'<?'+TXMLProcessTag(Item).Name;
for Counter:=0 to length(TXMLProcessTag(Item).Parameter)-1 do begin
if assigned(TXMLProcessTag(Item).Parameter[Counter]) then begin
Line:=Line+' '+TXMLProcessTag(Item).Parameter[Counter].Name+'="'+ConvertToEntities(TXMLProcessTag(Item).Parameter[Counter].Value)+'"';
end;
end;
Line:=Line+'?>';
WriteLine(Line);
for Counter:=0 to Item.Items.Count-1 do begin
Process(Item.Items[Counter],DoIndent);
end;
end else if Item is TXMLScriptTag then begin
Line:=Line+'<%'+TXMLScriptTag(Item).Text+'%>';
WriteLine(Line);
for Counter:=0 to Item.Items.Count-1 do begin
Process(Item.Items[Counter],DoIndent);
end;
end else if Item is TXMLCDataTag then begin
Line:=Line+'<![CDATA['+TXMLCDataTag(Item).Text+']]>';
WriteLine(Line);
for Counter:=0 to Item.Items.Count-1 do begin
Process(Item.Items[Counter],DoIndent);
end;
end else if Item is TXMLDOCTYPETag then begin
Line:=Line+'<!DOCTYPE '+TXMLDOCTYPETag(Item).Text+'>';
WriteLine(Line);
for Counter:=0 to Item.Items.Count-1 do begin
Process(Item.Items[Counter],DoIndent);
end;
end else if Item is TXMLExtraTag then begin
Line:=Line+'<!'+TXMLExtraTag(Item).Text+'>';
WriteLine(Line);
for Counter:=0 to Item.Items.Count-1 do begin
Process(Item.Items[Counter],DoIndent);
end;
end else if Item is TXMLTag then begin
if AutomaticAloneTagDetection then begin
TXMLTag(Item).IsAloneTag:=TXMLTag(Item).Items.Count=0;
end;
Line:=Line+'<'+TXMLTag(Item).Name;
for Counter:=0 to length(TXMLTag(Item).Parameter)-1 do begin
if assigned(TXMLTag(Item).Parameter[Counter]) then begin
Line:=Line+' '+TXMLTag(Item).Parameter[Counter].Name+'="'+ConvertToEntities(TXMLTag(Item).Parameter[Counter].Value)+'"';
end;
end;
if TXMLTag(Item).IsAloneTag then begin
Line:=Line+' />';
WriteLine(Line);
end else begin
TagWithSingleLineText:=false;
if Item.Items.Count=1 then begin
if assigned(Item.Items[0]) then begin
if Item.Items[0] is TXMLText then begin
if ((POS(#13,TXMLText(Item.Items[0]).Text)=0) and
(POS(#10,TXMLText(Item.Items[0]).Text)=0)) or not FormatIndentText then begin
TagWithSingleLineText:=true;
end;
end;
end;
end;
ItemsText:=false;
for Counter:=0 to Item.Items.Count-1 do begin
if assigned(Item.Items[Counter]) then begin
if Item.Items[Counter] is TXMLText then begin
ItemsText:=true;
end;
end;
end;
if TagWithSingleLineText then begin
Line:=Line+'>'+ConvertToEntities(TXMLText(Item.Items[0]).Text)+'</'+TXMLTag(Item).Name+'>';
WriteLine(Line);
end else if Item.Items.Count<>0 then begin
Line:=Line+'>';
if assigned(Item.Items[0]) and (Item.Items[0] is TXMLText) and not FormatIndentText then begin
WriteLineEx(Line);
end else begin
WriteLine(Line);
end;
for Counter:=0 to Item.Items.Count-1 do begin
Process(Item.Items[Counter],DoIndent and ((not ItemsText) or (FormatIndent and FormatIndentText)));
end;
Line:='';
if DoIndent and ((not ItemsText) or (FormatIndent and FormatIndentText)) then begin
for Counter:=1 to IdentLevel do begin
Line:=Line+' ';
end;
end;
Line:=Line+'</'+TXMLTag(Item).Name+'>';
WriteLine(Line);
end else begin
Line:=Line+'></'+TXMLTag(Item).Name+'>';
WriteLine(Line);
end;
end;
end else begin
for Counter:=0 to Item.Items.Count-1 do begin
Process(Item.Items[Counter],DoIndent);
end;
end;
dec(IdentLevel,IdentSize);
end;
end;
end;
begin
IdentLevel:=-(2*IdentSize);
if Stream is TMemoryStream then begin
TMemoryStream(Stream).Clear;
end;
Errors:=false;
Process(Root,FormatIndent);
result:=not Errors;
end;
function TXML.ReadXMLText:ansistring;
var Stream:TMemoryStream;
begin
Stream:=TMemoryStream.Create;
Write(Stream);
if Stream.Size>0 then begin
SetLength(result,Stream.Size);
Stream.Seek(0,soFromBeginning);
Stream.Read(result[1],Stream.Size);
end else begin
result:='';
end;
Stream.Destroy;
end;
procedure TXML.WriteXMLText(Text:ansistring);
var Stream:TMemoryStream;
begin
Stream:=TMemoryStream.Create;
if length(Text)>0 then begin
Stream.Write(Text[1],length(Text));
Stream.Seek(0,soFromBeginning);
end;
Parse(Stream);
Stream.Destroy;
end;
function ParseText(ParentItem:TXMLItem):ansistring;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
begin
result:='';
if assigned(ParentItem) then begin
for XMLItemIndex:=0 to ParentItem.Items.Count-1 do begin
XMLItem:=ParentItem.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLText then begin
result:=result+TXMLText(XMLItem).Text;
end else if XMLItem is TXMLTag then begin
if TXMLTag(XMLItem).Name='br' then begin
result:=result+#13#10;
end;
result:=result+ParseText(XMLItem)+' ';
end;
end;
end;
end;
end;
end.
|
unit xe_CUT;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.StrUtils,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, clipbrd,
cxLookAndFeelPainters, dxSkinsCore, dxSkinscxPCPainter,
dxBarBuiltInMenu, cxContainer, cxEdit, Vcl.Menus, Vcl.ComCtrls, dxCore,
cxDateUtils, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage,
cxNavigator, Data.DB, cxDBData, cxLabel, cxCurrencyEdit, cxCheckBox, System.Math,
cxDropDownEdit, cxImageComboBox, cxTL, cxTLdxBarBuiltInMenu, AdvProgressBar,
Vcl.OleCtrls, SHDocVw, Vcl.StdCtrls, cxCheckComboBox, cxGridBandedTableView,
cxSplitter, cxInplaceContainer, cxMemo, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid,
cxTextEdit, cxRadioGroup, cxMaskEdit, cxCalendar, cxButtons, cxGroupBox, Registry,
IniFiles, MSXML2_TLB, Vcl.ExtCtrls, cxPC, DateUtils, ComObj, cxScrollBox,
dxDateRanges, dxSkinOffice2010Silver, dxSkinSharp, dxSkinMetropolisDark, dxSkinOffice2007Silver,
dxScrollbarAnnotations;
Type
TCuData = record
CuName : string;
CuMemo : string;
CuArea : string;
CuStart1: string;
CuStart2: string;
CuStart3: string;
CuAreaDetail: string;
CuXval: string;
CuYVal: string;
CuTelList: string;
end;
Type
TMileData = record
mType : string;
mGubun : string;
mCash : string;
mPost : string;
mCard : string;
mMile : string;
mReceipNo : string;
mFirstAdd : string;
mOverAdd : string;
end;
type
TFrm_CUT = class(TForm)
Pop_Ymd: TPopupMenu;
MenuItem33: TMenuItem;
MenuItem34: TMenuItem;
MenuItem35: TMenuItem;
MenuItem36: TMenuItem;
MenuItem37: TMenuItem;
pm_Date: TPopupMenu;
N_Today: TMenuItem;
N_Yesterday: TMenuItem;
N_Week: TMenuItem;
N_Month: TMenuItem;
N_1Start31End: TMenuItem;
pmCustMgr: TPopupMenu;
mniN9: TMenuItem;
mniN10: TMenuItem;
mniN8: TMenuItem;
cxStyleCustLevel: TcxStyleRepository;
stlCustLevelColor: TcxStyle;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
PopupMenu1: TPopupMenu;
MenuItem1: TMenuItem;
MenuItem6: TMenuItem;
MenuItem7: TMenuItem;
cxStyleRepository2: TcxStyleRepository;
cxStyle2: TcxStyle;
PopupMenu6: TPopupMenu;
MenuItem53: TMenuItem;
MenuItem54: TMenuItem;
MenuItem55: TMenuItem;
pmDetail: TPopupMenu;
mniDetailCustLevel: TMenuItem;
MenuItem71: TMenuItem;
cxPageControl1: TcxPageControl;
cxTabSheet1: TcxTabSheet;
pnl_CUTA1: TPanel;
Shape15: TShape;
cxGroupBox1: TcxGroupBox;
lbCustCompany01: TcxLabel;
btn_1_2: TcxButton;
btn_1_7: TcxButton;
btn_1_5: TcxButton;
btn_1_6: TcxButton;
btn_1_1: TcxButton;
cxGroupBox4: TcxGroupBox;
cbBCustList: TcxComboBox;
cbGubun1_1: TcxComboBox;
cbKeynumber01: TcxComboBox;
cbLevel01: TcxComboBox;
cbSmsUse01: TcxComboBox;
chkBubinName: TcxCheckBox;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
cxLabel24: TcxLabel;
cxLabel3: TcxLabel;
edCustName01: TcxTextEdit;
edCustTel01: TcxTextEdit;
chkBubinCust: TcxCheckBox;
chkNmlPhoneOut01: TcxCheckBox;
lbCount01: TcxLabel;
btn_1_3: TcxButton;
cxLabel8: TcxLabel;
cbOutBound1: TcxComboBox;
cxGroupBox6: TcxGroupBox;
cbBCustListCd: TcxComboBox;
chkSearchAdd: TcxCheckBox;
btn_Date1_6: TcxButton;
btn_1_8: TcxButton;
cxCheckBox4: TcxCheckBox;
de_4stDate: TcxDateEdit;
de_4edDate: TcxDateEdit;
de_5stDate: TcxDateEdit;
de_5edDate: TcxDateEdit;
cxLabel26: TcxLabel;
cxLabel27: TcxLabel;
cxLabel28: TcxLabel;
edUseCnt01: TcxTextEdit;
edUseCnt02: TcxTextEdit;
btn_Date1_5: TcxButton;
rbFirstUseDate01: TcxRadioButton;
rbUseCnt01: TcxRadioButton;
rbUseDate01: TcxRadioButton;
cxGrid1: TcxGrid;
CustView1: TcxGridDBTableView;
CustView1Column1: TcxGridDBColumn;
CustView1Column2: TcxGridDBColumn;
CustView1Column3: TcxGridDBColumn;
CustView1Column4: TcxGridDBColumn;
CustView1Column5: TcxGridDBColumn;
CustView1Column6: TcxGridDBColumn;
CustView1Column23: TcxGridDBColumn;
CustView1Column24: TcxGridDBColumn;
CustView1Column7: TcxGridDBColumn;
CustView1Column8: TcxGridDBColumn;
CustView1Column9: TcxGridDBColumn;
CustView1Column10: TcxGridDBColumn;
CustView1Column11: TcxGridDBColumn;
CustView1Column12: TcxGridDBColumn;
CustView1Column13: TcxGridDBColumn;
CustView1Column14: TcxGridDBColumn;
CustView1Column15: TcxGridDBColumn;
CustView1Column16: TcxGridDBColumn;
CustView1Column17: TcxGridDBColumn;
CustView1Column18: TcxGridDBColumn;
CustView1Column19: TcxGridDBColumn;
CustView1Column20: TcxGridDBColumn;
CustView1Column21: TcxGridDBColumn;
CustView1Column22: TcxGridDBColumn;
CustView1Column25: TcxGridDBColumn;
CustView1Column26: TcxGridDBColumn;
CustView1Column27: TcxGridDBColumn;
CustView1Column28: TcxGridDBColumn;
cxGrid1Level1: TcxGridLevel;
pnl_Chang_select: TPanel;
cxGroupBox8: TcxGroupBox;
mmoMilelistError: TcxMemo;
btnAll6: TcxButton;
cxCurrencyEdit5: TcxCurrencyEdit;
cxCurrencyEdit7: TcxCurrencyEdit;
cxlbl7: TcxLabel;
cxTextEdit16: TcxTextEdit;
cxLabel5: TcxLabel;
cxLabel6: TcxLabel;
cxLabel7: TcxLabel;
cxGroupBox9: TcxGroupBox;
chkNMCNG1: TcxRadioButton;
chkNMCNG2: TcxRadioButton;
cxGroupBox10: TcxGroupBox;
cxRMileM: TcxRadioButton;
cxRMileP: TcxRadioButton;
cxRMileS: TcxRadioButton;
btnAll7: TcxButton;
cxTabSheet2: TcxTabSheet;
pnl_CUTA2: TPanel;
Shape19: TShape;
cxGrid2: TcxGrid;
CustView2: TcxGridDBTableView;
CustView2Column1: TcxGridDBColumn;
CustView2Column22: TcxGridDBColumn;
CustView2Column2: TcxGridDBColumn;
CustView2Column3: TcxGridDBColumn;
CustView2Column4: TcxGridDBColumn;
CustView2Column5: TcxGridDBColumn;
CustView2Column6: TcxGridDBColumn;
CustView2Column7: TcxGridDBColumn;
CustView2Column8: TcxGridDBColumn;
CustView2Column9: TcxGridDBColumn;
CustView2Column10: TcxGridDBColumn;
CustView2Column11: TcxGridDBColumn;
CustView2Column12: TcxGridDBColumn;
CustView2Column13: TcxGridDBColumn;
CustView2Column14: TcxGridDBColumn;
CustView2Column15: TcxGridDBColumn;
CustView2Column16: TcxGridDBColumn;
CustView2Column17: TcxGridDBColumn;
CustView2Column18: TcxGridDBColumn;
CustView2Column19: TcxGridDBColumn;
CustView2Column20: TcxGridDBColumn;
CustView2Column21: TcxGridDBColumn;
CustView2Column23: TcxGridDBColumn;
CustView2Column24: TcxGridDBColumn;
cxGrid2Level1: TcxGridLevel;
cxGrdCuList: TcxGrid;
sg_notsms_list: TcxGridDBTableView;
cxGrdCol1: TcxGridDBColumn;
cxGrdCol2: TcxGridDBColumn;
cxGrdCol3: TcxGridDBColumn;
cxGrdCuListLevel1: TcxGridLevel;
lb_Status: TListBox;
cxGroupBox11: TcxGroupBox;
lbCustCompany02: TcxLabel;
cxGroupBox12: TcxGroupBox;
rg_SType: TPanel;
rbAll01: TcxRadioButton;
rbNew01: TcxRadioButton;
rbUseList01: TcxRadioButton;
cxLabel9: TcxLabel;
cbKeynumber02: TcxComboBox;
cxLabel10: TcxLabel;
cxLabel11: TcxLabel;
edCustName02: TcxTextEdit;
cbGubun2_1: TcxComboBox;
GroupBox4: TcxGroupBox;
rrb_st_all: TcxRadioButton;
rrb_st_comp: TcxRadioButton;
rrb_st_cancel: TcxRadioButton;
rrb_st_req: TcxRadioButton;
chk_Before: TcxCheckBox;
chk_Before_Finish: TcxCheckBox;
chk_Before_New: TcxCheckBox;
lbCount02: TcxLabel;
cxLabel13: TcxLabel;
cbOutBound2: TcxComboBox;
cxGroupBox13: TcxGroupBox;
cxLabel12: TcxLabel;
btn_Date2_1: TcxButton;
cxDate2_1S: TcxDateEdit;
cxDate2_1E: TcxDateEdit;
cxLabel60: TcxLabel;
cxLabel61: TcxLabel;
cxLabel14: TcxLabel;
cxLabel15: TcxLabel;
cxLabel16: TcxLabel;
cb_Sms_Gubun: TcxComboBox;
edCustMemo01: TcxTextEdit;
edCustTel02: TcxTextEdit;
cxLabel17: TcxLabel;
cxLabel18: TcxLabel;
cxLabel19: TcxLabel;
cb_S_Cnt1: TcxTextEdit;
cb_S_CCnt1: TcxTextEdit;
cb_S_Grad: TcxComboBox;
cxLabel20: TcxLabel;
cxLabel53: TcxLabel;
cb_S_Cnt2: TcxTextEdit;
cb_S_CCnt2: TcxTextEdit;
cxLabel21: TcxLabel;
cb_st_city: TcxComboBox;
cxLabel22: TcxLabel;
cb_st_ward: TcxComboBox;
cxGroupBox14: TcxGroupBox;
btn_2_5: TcxButton;
chk_All_Select: TcxCheckBox;
chkCust02Type04: TcxCheckBox;
chkNmlPhoneOut02: TcxCheckBox;
btn_2_3: TcxButton;
btn_2_2: TcxButton;
btn_2_4: TcxButton;
btn_2_1: TcxButton;
cxLabel210: TcxLabel;
cxGroupBox15: TcxGroupBox;
cxLabel39: TcxLabel;
cxTabSheet3: TcxTabSheet;
pnl_CUTA3: TPanel;
Shape35: TShape;
cxGroupBox17: TcxGroupBox;
lbCustCompany03: TcxLabel;
cxGroupBox18: TcxGroupBox;
Pnl_A3Chk3: TPanel;
Label1: TLabel;
de_A33stDate: TcxDateEdit;
de_A33edDate: TcxDateEdit;
btn_Date3_3: TcxButton;
Pnl_A3Chk2: TPanel;
Label2: TLabel;
de_A32stDate: TcxDateEdit;
de_A32edDate: TcxDateEdit;
btn_Date3_4: TcxButton;
Pnl_A3Chk1: TPanel;
Label4: TLabel;
de_A31stDate: TcxDateEdit;
de_A31edDate: TcxDateEdit;
btn_Date3_2: TcxButton;
chkCust03Type02: TcxCheckBox;
chkCust03Type01: TcxCheckBox;
chkCust03Type03: TcxCheckBox;
cxGroupBox19: TcxGroupBox;
rbCust03Type05: TcxRadioButton;
rbCust03Type07: TcxRadioButton;
rbCust03Type06: TcxRadioButton;
cxGroupBox20: TcxGroupBox;
Shape40: TShape;
cxLabel29: TcxLabel;
cxLabel30: TcxLabel;
cxLabel31: TcxLabel;
lbCount03: TcxLabel;
cbKeynumber03: TcxComboBox;
cbGubun3_1: TcxComboBox;
cbSmsUse03: TcxComboBox;
btn_3_1: TcxButton;
cxLabel33: TcxLabel;
cbOutBound3: TcxComboBox;
cxGroupBox21: TcxGroupBox;
rbCust03Type01: TcxRadioButton;
rbCust03Type02: TcxRadioButton;
btn_Date3_1: TcxButton;
cxDate3_1S: TcxDateEdit;
cxDate3_1E: TcxDateEdit;
cxLabel70: TcxLabel;
cxLabel72: TcxLabel;
cxGroupBox22: TcxGroupBox;
cbCustLastNumber: TcxComboBox;
cxLabel74: TcxLabel;
cxLabel75: TcxLabel;
cxLabel76: TcxLabel;
cxLabel77: TcxLabel;
cxLabel78: TcxLabel;
cxLabel79: TcxLabel;
edMlgCount01: TcxTextEdit;
edMlgCount02: TcxTextEdit;
edMlgScore01: TcxTextEdit;
edMlgScore02: TcxTextEdit;
rbCust03Type03: TcxRadioButton;
rbCust03Type04: TcxRadioButton;
btn_3_2: TcxButton;
btn_3_4: TcxButton;
btn_3_5: TcxButton;
btn_3_3: TcxButton;
chkCust03Type04: TcxCheckBox;
chkCust03Type06: TcxCheckBox;
chkCust03Type05: TcxCheckBox;
chkCust03Type07: TcxCheckBox;
cxGrid3: TcxGrid;
CustView3: TcxGridDBTableView;
CustView3Column1: TcxGridDBColumn;
CustView3Column2: TcxGridDBColumn;
CustView3Column3: TcxGridDBColumn;
CustView3Column4: TcxGridDBColumn;
CustView3Column5: TcxGridDBColumn;
CustView3Column6: TcxGridDBColumn;
CustView3Column7: TcxGridDBColumn;
CustView3Column8: TcxGridDBColumn;
CustView3Column9: TcxGridDBColumn;
CustView3Column10: TcxGridDBColumn;
CustView3Column11: TcxGridDBColumn;
CustView3Column12: TcxGridDBColumn;
CustView3Column13: TcxGridDBColumn;
CustView3Column14: TcxGridDBColumn;
CustView3Column15: TcxGridDBColumn;
CustView3Column16: TcxGridDBColumn;
CustView3Column17: TcxGridDBColumn;
CustView3Column18: TcxGridDBColumn;
cxGrid3Level1: TcxGridLevel;
cxTabSheet4: TcxTabSheet;
pnl_CUTA4: TPanel;
Shape45: TShape;
cxGroupBox16: TcxGroupBox;
lbCustCompany04: TcxLabel;
btn_4_3: TcxButton;
btn_4_5: TcxButton;
btn_4_6: TcxButton;
btn_4_4: TcxButton;
chkCust04Type08: TcxCheckBox;
chkCust04Type11: TcxCheckBox;
chkCust04Type12: TcxCheckBox;
cxGroupBox23: TcxGroupBox;
Shape50: TShape;
Shape52: TShape;
cxLabel36: TcxLabel;
cxLabel37: TcxLabel;
cxLabel38: TcxLabel;
cxLabel40: TcxLabel;
cbSmsUse04: TcxComboBox;
cbGubun4_1: TcxComboBox;
cbLevel04: TcxComboBox;
cbKeynumber04: TcxComboBox;
edtCuEmail: TcxTextEdit;
chkCust04Type06: TcxCheckBox;
chkCust04Type10: TcxCheckBox;
lbCount04: TcxLabel;
cxLabel41: TcxLabel;
cbOutBound4: TcxComboBox;
cxGroupBox24: TcxGroupBox;
Shape56: TShape;
chkCust04Type01: TcxCheckBox;
cxDate4_1S: TcxDateEdit;
cxLabel82: TcxLabel;
cxDate4_1E: TcxDateEdit;
chkCust04Type03: TcxCheckBox;
cbArea03: TcxComboBox;
cbArea04: TcxComboBox;
cbBCustList4: TcxComboBox;
chkCust04Type07: TcxCheckBox;
btn_4_1: TcxButton;
btn_Date4_1: TcxButton;
chkCust04Type02: TcxCheckBox;
cxDate4_2S: TcxDateEdit;
cxDate4_2E: TcxDateEdit;
btn_Date4_2: TcxButton;
cxlbl1: TcxLabel;
chkCust04Type09: TcxCheckBox;
cxDate4_3S: TcxDateEdit;
cxlbl2: TcxLabel;
cxDate4_3E: TcxDateEdit;
btn_Date4_3: TcxButton;
chkCust04Type04: TcxCheckBox;
chkCust04Type05: TcxCheckBox;
edCust04Type01: TcxTextEdit;
cxLabel85: TcxLabel;
edCust04Type02: TcxTextEdit;
edCust04Type03: TcxTextEdit;
cxLabel86: TcxLabel;
edCust04Type04: TcxTextEdit;
cxLabel84: TcxLabel;
cbCustLastNumber4: TcxComboBox;
btn_4_2: TcxButton;
cbBCustList4Cd: TcxComboBox;
rbCust04Type01: TcxRadioButton;
rbCust04Type02: TcxRadioButton;
cxGrid4: TcxGrid;
CustView4: TcxGridDBTableView;
CustView4Column1: TcxGridDBColumn;
CustView4Column2: TcxGridDBColumn;
CustView4Column3: TcxGridDBColumn;
CustView4Column4: TcxGridDBColumn;
CustView4Column5: TcxGridDBColumn;
CustView4Column6: TcxGridDBColumn;
CustView4Column7: TcxGridDBColumn;
CustView4Column8: TcxGridDBColumn;
CustView4Column9: TcxGridDBColumn;
CustView4Column10: TcxGridDBColumn;
CustView4Column11: TcxGridDBColumn;
CustView4Column12: TcxGridDBColumn;
CustView4Column13: TcxGridDBColumn;
CustView4Column14: TcxGridDBColumn;
CustView4Column15: TcxGridDBColumn;
CustView4Column16: TcxGridDBColumn;
CustView4Column17: TcxGridDBColumn;
CustView4Column18: TcxGridDBColumn;
CustView4Column19: TcxGridDBColumn;
CustView4Column20: TcxGridDBColumn;
CustView4Column21: TcxGridDBColumn;
cxGrid4Level1: TcxGridLevel;
cxTabSheet5: TcxTabSheet;
pnl_CUTA5: TPanel;
Shape60: TShape;
cxGroupBox25: TcxGroupBox;
lbCustCompany05: TcxLabel;
cxGroupBox26: TcxGroupBox;
cxLabel44: TcxLabel;
cxLabel45: TcxLabel;
cxLabel46: TcxLabel;
cbKeynumber05: TcxComboBox;
cxTextEdit18: TcxTextEdit;
cxTextEdit19: TcxTextEdit;
btn_5_1: TcxButton;
btn_5_2: TcxButton;
btn_5_3: TcxButton;
btn_5_4: TcxButton;
cxGroupBox27: TcxGroupBox;
pnl4: TPanel;
cxGridBrOrder: TcxGrid;
cxVirtureList: TcxGridDBTableView;
CustView1ViewNoticeListVirtureColumn1: TcxGridDBColumn;
CustView1ViewNoticeListVirtureColumn3: TcxGridDBColumn;
CustView1VirtureListColumn1: TcxGridDBColumn;
cxGrid19: TcxGridLevel;
pnl2: TPanel;
cxLabel242: TcxLabel;
cxLabel243: TcxLabel;
cxLabel244: TcxLabel;
cxLabel245: TcxLabel;
cxLabel246: TcxLabel;
cxLabel247: TcxLabel;
cxLabel248: TcxLabel;
cxTextEdit20: TcxTextEdit;
cxLabel249: TcxLabel;
cxLabel250: TcxLabel;
btn_5_5: TcxButton;
btn_5_7: TcxButton;
btn_5_6: TcxButton;
pnl5: TPanel;
cxLabel252: TcxLabel;
cxLabel253: TcxLabel;
cxLabel254: TcxLabel;
cxLabel240: TcxLabel;
cxLabel251: TcxLabel;
cxGrid14: TcxGrid;
cxGridDBTableView1: TcxGridDBTableView;
cxGridDBColumn1: TcxGridDBColumn;
cxGridDBColumn2: TcxGridDBColumn;
cxGridDBColumn3: TcxGridDBColumn;
cxGridDBColumn4: TcxGridDBColumn;
cxGridDBColumn5: TcxGridDBColumn;
cxGridDBColumn6: TcxGridDBColumn;
cxGridDBColumn7: TcxGridDBColumn;
cxGridDBColumn8: TcxGridDBColumn;
CustView1GridDBTableView1Column1: TcxGridDBColumn;
CustView1GridDBTableView1Column2: TcxGridDBColumn;
CustView1GridDBTableView1Column3: TcxGridDBColumn;
CustView1GridDBTableView1Column4: TcxGridDBColumn;
cxGridLevel7: TcxGridLevel;
cxTabSheet6: TcxTabSheet;
pnl_CUTA6: TPanel;
Shape70: TShape;
cxGrid5: TcxGrid;
CustView6: TcxGridDBTableView;
cxGridDBColumn12: TcxGridDBColumn;
cxGridDBColumn13: TcxGridDBColumn;
cxGridDBColumn14: TcxGridDBColumn;
cxGridDBColumn15: TcxGridDBColumn;
cxGridDBColumn16: TcxGridDBColumn;
cxGridDBColumn17: TcxGridDBColumn;
cxGridDBColumn18: TcxGridDBColumn;
cxGridDBColumn19: TcxGridDBColumn;
cxGridDBColumn20: TcxGridDBColumn;
cxGridDBColumn21: TcxGridDBColumn;
cxGridDBColumn22: TcxGridDBColumn;
cxGridDBColumn23: TcxGridDBColumn;
cxGridDBColumn26: TcxGridDBColumn;
cxGridDBColumn27: TcxGridDBColumn;
cxGridDBColumn28: TcxGridDBColumn;
CustView6Column1: TcxGridDBColumn;
CustView6Column2: TcxGridDBColumn;
cxGridLevel5: TcxGridLevel;
cxGroupBox28: TcxGroupBox;
lbCustCompany06: TcxLabel;
cxGroupBox29: TcxGroupBox;
Shape75: TShape;
cxLabel49: TcxLabel;
cxLabel50: TcxLabel;
cxLabel51: TcxLabel;
cbGubun6_1: TcxComboBox;
cbKeynumber06: TcxComboBox;
cbLevel06: TcxComboBox;
cbSmsUse06: TcxComboBox;
chkCust06Type02: TcxCheckBox;
chkCust06Type06: TcxCheckBox;
lbCount06: TcxLabel;
rbCust06Type01: TcxRadioButton;
cxDate6_1: TcxDateEdit;
cxLabel88: TcxLabel;
btn_6_1: TcxButton;
btn_6_2: TcxButton;
btn_6_3: TcxButton;
btn_6_4: TcxButton;
btn_6_5: TcxButton;
chkCust06Type01: TcxCheckBox;
rbCust06Type02: TcxRadioButton;
cxDate14: TcxDateEdit;
cxDate15: TcxDateEdit;
cxLabel91: TcxLabel;
cxLabel229: TcxLabel;
btn_6_6: TcxButton;
btn_6_8: TcxButton;
btn_6_9: TcxButton;
btn_6_7: TcxButton;
chkCust06Type03: TcxCheckBox;
chkCust06Type05: TcxCheckBox;
chkCust06Type04: TcxCheckBox;
cxTabSheet7: TcxTabSheet;
cxTabSheet8: TcxTabSheet;
cxTabSheet9: TcxTabSheet;
cxTabSheet10: TcxTabSheet;
cxTabSheet11: TcxTabSheet;
pnl_CUTA7: TPanel;
Shape87: TShape;
Panel22: TPanel;
Shape88: TShape;
cxGroupBox33: TcxGroupBox;
btn_7_2: TcxButton;
btn_7_3: TcxButton;
btn_7_4: TcxButton;
btn_7_5: TcxButton;
cxGridCustGroup: TcxGrid;
cxGridBandedTableView3: TcxGridBandedTableView;
cxViewCustGroup: TcxGridTableView;
cxColCGGroupName: TcxGridColumn;
cxColCGSortNo: TcxGridColumn;
cxColCGLevelName: TcxGridColumn;
cxColCGMileage: TcxGridColumn;
cxColCGColor: TcxGridColumn;
cxColCGLevelUpDesc: TcxGridColumn;
cxColCGGroupSeq: TcxGridColumn;
cxColCGLevelSeq: TcxGridColumn;
cxColCGDefaultYN: TcxGridColumn;
cxLevelCustGroup: TcxGridLevel;
cxGroupBox34: TcxGroupBox;
cxGridCustLevel: TcxGrid;
cxGridBandedTableView2: TcxGridBandedTableView;
cxViewCustLevel: TcxGridTableView;
cxColCLBranchTel: TcxGridColumn;
cxColCLGroup: TcxGridColumn;
cxColCLAutoUp: TcxGridColumn;
cxColCLGroupSeq: TcxGridColumn;
cxLevelCustLevel: TcxGridLevel;
cxGridGroupLevel: TcxGrid;
cxGridBandedTableView1: TcxGridBandedTableView;
cxViewGroupLevel: TcxGridTableView;
cxColGLSortNo: TcxGridColumn;
cxColGLLevelName: TcxGridColumn;
cxColGLMileage: TcxGridColumn;
cxColGLColor: TcxGridColumn;
cxColGLLevelUpDesc: TcxGridColumn;
cxColGLDefaultYN: TcxGridColumn;
cxLevelGroupLevel: TcxGridLevel;
cxGroupBox35: TcxGroupBox;
lbCustCompany07: TcxLabel;
btn_7_1: TcxButton;
pnl_CUTA8: TPanel;
cxGroupBox36: TcxGroupBox;
lbCustCompany08: TcxLabel;
pnl_CUTA10: TPanel;
Shape76: TShape;
cxGroupBox30: TcxGroupBox;
lbCustCompany10: TcxLabel;
cxGroupBox31: TcxGroupBox;
Shape81: TShape;
Shape82: TShape;
Shape83: TShape;
cxLabel56: TcxLabel;
cxLabel57: TcxLabel;
cxLabel58: TcxLabel;
cbGubun10_1: TcxComboBox;
cbKeynumber10: TcxComboBox;
lbCount10: TcxLabel;
edCustName03: TcxTextEdit;
chkCust10Type02: TcxCheckBox;
btn_Date10_1: TcxButton;
cxDate10_1S: TcxDateEdit;
cxDate10_1E: TcxDateEdit;
rbCust10Type01: TcxRadioButton;
rbCust10Type02: TcxRadioButton;
rbCust10Type03: TcxRadioButton;
cxLabel59: TcxLabel;
edCustTel03: TcxTextEdit;
cxLabel139: TcxLabel;
cxCbMileGubun: TcxComboBox;
cxLabel140: TcxLabel;
cxLabel141: TcxLabel;
btn_10_2: TcxButton;
btn_10_1: TcxButton;
cxedCuSEQ: TcxTextEdit;
cxGrid8: TcxGrid;
CustView10: TcxGridDBTableView;
cxGridDBColumn45: TcxGridDBColumn;
cxGridDBColumn46: TcxGridDBColumn;
cxGridDBColumn47: TcxGridDBColumn;
cxGridDBColumn48: TcxGridDBColumn;
cxGridDBColumn49: TcxGridDBColumn;
cxGridDBColumn50: TcxGridDBColumn;
cxGridDBColumn51: TcxGridDBColumn;
cxGridDBColumn52: TcxGridDBColumn;
cxGridDBColumn53: TcxGridDBColumn;
cxGridDBColumn54: TcxGridDBColumn;
cxGridDBColumn55: TcxGridDBColumn;
cxGridDBColumn56: TcxGridDBColumn;
cxGridDBColumn57: TcxGridDBColumn;
cxGridDBColumn58: TcxGridDBColumn;
cxGridDBColumn59: TcxGridDBColumn;
CustView10Column1: TcxGridDBColumn;
CustView10Column2: TcxGridDBColumn;
cxGridLevel6: TcxGridLevel;
pnl_CUTA11: TPanel;
Shape86: TShape;
cxGroupBox32: TcxGroupBox;
lbCustCompany11: TcxLabel;
cxGroupBox40: TcxGroupBox;
btn_Date11_1: TcxButton;
dtOKCStDate: TcxDateEdit;
dtOKCEdDate: TcxDateEdit;
cxLabel144: TcxLabel;
cxLabel145: TcxLabel;
btn_11_2: TcxButton;
btn_11_1: TcxButton;
cxGridOKC: TcxGrid;
cxViewOKC: TcxGridDBTableView;
cxColViewKeyColumn1: TcxGridDBColumn;
cxColViewKeyColumn2: TcxGridDBColumn;
cxColViewOKCColumn1: TcxGridDBColumn;
cxColViewKeyColumn3: TcxGridDBColumn;
cxColViewKeyColumn4: TcxGridDBColumn;
cxColViewKeyColumn5: TcxGridDBColumn;
cxColViewKeyColumn6: TcxGridDBColumn;
cxColViewKeyColumn7: TcxGridDBColumn;
cxColViewKeyColumn8: TcxGridDBColumn;
cxColViewKeyColumn9: TcxGridDBColumn;
cxColViewKeyColumn10: TcxGridDBColumn;
cxColViewKeyColumn11: TcxGridDBColumn;
cxColViewKeyColumn12: TcxGridDBColumn;
cxLevelOKC: TcxGridLevel;
pnl_CUTA9: TPanel;
Shape129: TShape;
cxGroupBox37: TcxGroupBox;
lbCustCompany09: TcxLabel;
cxGroupBox38: TcxGroupBox;
Shape134: TShape;
cxLabel105: TcxLabel;
cxLabel106: TcxLabel;
cxLabel107: TcxLabel;
cbGubun9_1: TcxComboBox;
cbKeynumber09: TcxComboBox;
lbCount09: TcxLabel;
edCustName09: TcxTextEdit;
btn_9_3: TcxButton;
cxGroupBox39: TcxGroupBox;
Shape135: TShape;
cxLabel119: TcxLabel;
cxLabel180: TcxLabel;
chkCust09Type02: TcxCheckBox;
cxDate9_1S: TcxDateEdit;
cxDate9_1E: TcxDateEdit;
btn_Date9_1: TcxButton;
btn_9_1: TcxButton;
cxLabel181: TcxLabel;
cxLabel182: TcxLabel;
cxLabel183: TcxLabel;
cxLabel184: TcxLabel;
edMileage01: TcxCurrencyEdit;
edSupplyEnd01: TcxCurrencyEdit;
cxLabel257: TcxLabel;
edCouponM01: TcxCurrencyEdit;
cxLabel259: TcxLabel;
cxLabel120: TcxLabel;
edEvent01: TcxCurrencyEdit;
chkCust09Type01: TcxCheckBox;
btn_9_2: TcxButton;
cxGrid6: TcxGrid;
CustView9: TcxGridDBTableView;
CustView9Column1: TcxGridDBColumn;
CustView9Column15: TcxGridDBColumn;
CustView9Column16: TcxGridDBColumn;
CustView9Column2: TcxGridDBColumn;
CustView9Column3: TcxGridDBColumn;
CustView9Column4: TcxGridDBColumn;
CustView9Column5: TcxGridDBColumn;
CustView9Column6: TcxGridDBColumn;
CustView9Column7: TcxGridDBColumn;
CustView9Column8: TcxGridDBColumn;
CustView9Column9: TcxGridDBColumn;
CustView9Column10: TcxGridDBColumn;
CustView9Column11: TcxGridDBColumn;
CustView9Column12: TcxGridDBColumn;
CustView9Column13: TcxGridDBColumn;
CustView9Column17: TcxGridDBColumn;
CustView9Column18: TcxGridDBColumn;
CustView9Column14: TcxGridDBColumn;
CustView9Column19: TcxGridDBColumn;
CustView9Column20: TcxGridDBColumn;
CustView9Column21: TcxGridDBColumn;
cxGrid6Level1: TcxGridLevel;
cxBrNo1: TcxTextEdit;
cxHdNo1: TcxTextEdit;
cxHdNo2: TcxTextEdit;
cxBrNo2: TcxTextEdit;
cxBrNo3: TcxTextEdit;
cxHdNo3: TcxTextEdit;
cxBrNo4: TcxTextEdit;
cxHdNo4: TcxTextEdit;
cxBrNo5: TcxTextEdit;
cxHdNo5: TcxTextEdit;
cxBrNo6: TcxTextEdit;
cxHdNo6: TcxTextEdit;
cxBrNo8: TcxTextEdit;
cxHdNo8: TcxTextEdit;
cxBrNo9: TcxTextEdit;
cxHdNo9: TcxTextEdit;
cxHdNo10: TcxTextEdit;
cxBrNo10: TcxTextEdit;
cxBrNo11: TcxTextEdit;
cxHdNo11: TcxTextEdit;
pm_excel8_1: TPopupMenu;
MenuItem4: TMenuItem;
pm_excel8_2: TPopupMenu;
MenuItem5: TMenuItem;
pm_excel8_3: TPopupMenu;
MenuItem8: TMenuItem;
btn_1_4: TcxButton;
cxLabel4: TcxLabel;
cxCheckBox9: TcxCheckBox;
btn_Date1_1: TcxButton;
de_6stDate: TcxDateEdit;
de_6edDate: TcxDateEdit;
cxLabel237: TcxLabel;
cxTextEdit17: TcxTextEdit;
cxGroupBox2: TcxGroupBox;
Pnl_Chk3: TPanel;
Label6: TLabel;
de_3stDate: TcxDateEdit;
de_3edDate: TcxDateEdit;
btn_Date1_3: TcxButton;
Pnl_Chk2: TPanel;
Label3: TLabel;
de_2stDate: TcxDateEdit;
de_2edDate: TcxDateEdit;
btn_Date1_4: TcxButton;
Pnl_Chk1: TPanel;
Label13: TLabel;
de_1stDate: TcxDateEdit;
de_1edDate: TcxDateEdit;
btn_Date1_2: TcxButton;
Cb_DelDate: TcxCheckBox;
CB_SetDate: TcxCheckBox;
CB_UseDate: TcxCheckBox;
cxGroupBox3: TcxGroupBox;
Rb_SetupA: TcxRadioButton;
Rb_SetupN: TcxRadioButton;
Rb_SetupY: TcxRadioButton;
cxScrollBox1: TcxScrollBox;
Shape91: TShape;
Shape92: TShape;
Shape93: TShape;
Shape94: TShape;
Shape95: TShape;
Shape96: TShape;
Shape97: TShape;
Shape98: TShape;
Shape99: TShape;
Shape100: TShape;
Shape101: TShape;
Shape102: TShape;
Shape103: TShape;
Shape104: TShape;
Shape105: TShape;
Shape106: TShape;
Shape107: TShape;
Shape108: TShape;
Shape109: TShape;
Shape110: TShape;
Shape111: TShape;
Shape112: TShape;
Shape113: TShape;
Shape114: TShape;
Shape115: TShape;
Shape116: TShape;
Shape117: TShape;
Shape118: TShape;
Shape119: TShape;
Shape120: TShape;
Shape121: TShape;
Shape122: TShape;
Shape123: TShape;
Shape124: TShape;
cxLabel93: TcxLabel;
cxLabel96: TcxLabel;
cxLabel97: TcxLabel;
cxLabel98: TcxLabel;
cxLabel99: TcxLabel;
cxLabel100: TcxLabel;
cxLabel101: TcxLabel;
cxLabel102: TcxLabel;
chkCust08Type01: TcxCheckBox;
cxLabel109: TcxLabel;
cxTextEdit3: TcxTextEdit;
cxLabel110: TcxLabel;
cxLabel111: TcxLabel;
cxLabel112: TcxLabel;
cxLabel113: TcxLabel;
cxLabel114: TcxLabel;
cxLabel115: TcxLabel;
cxLabel116: TcxLabel;
cxLabel117: TcxLabel;
cxLabel118: TcxLabel;
cxLabel129: TcxLabel;
cxTextEdit6: TcxTextEdit;
cxLabel130: TcxLabel;
cxLabel131: TcxLabel;
cxLabel132: TcxLabel;
cxLabel133: TcxLabel;
cxLabel134: TcxLabel;
cxLabel135: TcxLabel;
cxLabel136: TcxLabel;
cxLabel137: TcxLabel;
cxLabel138: TcxLabel;
cxLabel149: TcxLabel;
cxTextEdit9: TcxTextEdit;
cxLabel150: TcxLabel;
cxLabel151: TcxLabel;
cxLabel152: TcxLabel;
cxLabel153: TcxLabel;
cxLabel154: TcxLabel;
cxLabel155: TcxLabel;
cxLabel156: TcxLabel;
cxLabel157: TcxLabel;
cxLabel158: TcxLabel;
cxLabel169: TcxLabel;
cxTextEdit12: TcxTextEdit;
cxLabel170: TcxLabel;
cxLabel171: TcxLabel;
cxLabel172: TcxLabel;
cxLabel173: TcxLabel;
cxTextEdit2: TcxCurrencyEdit;
cxTextEdit5: TcxCurrencyEdit;
cxTextEdit8: TcxCurrencyEdit;
cxTextEdit11: TcxCurrencyEdit;
chkBRNoMile: TcxCheckBox;
chkCDNoMile: TcxCheckBox;
chkLTNoMile: TcxCheckBox;
cxLabel234: TcxLabel;
chkReceipNoMile: TcxCheckBox;
Panel10: TPanel;
Shape125: TShape;
cxCheckBox5: TcxCheckBox;
cxCurrencyEdit1: TcxCurrencyEdit;
cxLabel260: TcxLabel;
cxLabel92: TcxLabel;
cxlbl4: TcxLabel;
cxTextEdit1: TcxCurrencyEdit;
Panel11: TPanel;
cxRadioButton10: TcxRadioButton;
cxRadioButton11: TcxRadioButton;
cxRadioButton12: TcxRadioButton;
CEMiOver1: TcxCurrencyEdit;
cxLabel65: TcxLabel;
cxLabel66: TcxLabel;
cxLabel67: TcxLabel;
Panel12: TPanel;
Shape126: TShape;
cxCheckBox6: TcxCheckBox;
cxCurrencyEdit2: TcxCurrencyEdit;
cxLabel128: TcxLabel;
cxlbl3: TcxLabel;
cxTextEdit4: TcxCurrencyEdit;
Panel13: TPanel;
cxRadioButton13: TcxRadioButton;
cxRadioButton14: TcxRadioButton;
cxRadioButton15: TcxRadioButton;
CEMiOver2: TcxCurrencyEdit;
cxLabel68: TcxLabel;
cxLabel69: TcxLabel;
cxLabel71: TcxLabel;
Panel14: TPanel;
Shape127: TShape;
cxCheckBox7: TcxCheckBox;
cxCurrencyEdit3: TcxCurrencyEdit;
cxLabel148: TcxLabel;
cxlbl5: TcxLabel;
cxTextEdit7: TcxCurrencyEdit;
Panel15: TPanel;
cxRadioButton16: TcxRadioButton;
cxRadioButton17: TcxRadioButton;
cxRadioButton18: TcxRadioButton;
CEMiOver3: TcxCurrencyEdit;
cxLabel73: TcxLabel;
cxLabel80: TcxLabel;
cxLabel81: TcxLabel;
Panel16: TPanel;
Shape128: TShape;
cxCheckBox8: TcxCheckBox;
cxCurrencyEdit4: TcxCurrencyEdit;
cxLabel168: TcxLabel;
cxlbl6: TcxLabel;
cxTextEdit10: TcxCurrencyEdit;
Panel17: TPanel;
cxRadioButton19: TcxRadioButton;
cxRadioButton20: TcxRadioButton;
cxRadioButton21: TcxRadioButton;
CEMiOver4: TcxCurrencyEdit;
cxLabel83: TcxLabel;
Panel18: TPanel;
rbPEventY: TcxRadioButton;
rbPEventN: TcxRadioButton;
cxLabel87: TcxLabel;
cxLabel89: TcxLabel;
Panel19: TPanel;
rbUEventY: TcxRadioButton;
rbUEventN: TcxRadioButton;
cxLabel90: TcxLabel;
cxLabel94: TcxLabel;
Panel20: TPanel;
rbBEventY: TcxRadioButton;
rbBEventN: TcxRadioButton;
cxLabel95: TcxLabel;
btn_8_3: TcxButton;
btn_8_4: TcxButton;
btn_8_5: TcxButton;
rb_Straight: TcxRadioButton;
rb_Declining: TcxRadioButton;
cxLabel190: TcxLabel;
cxCheckBox3: TcxCheckBox;
cxCheckBox2: TcxCheckBox;
cxCheckBox10: TcxCheckBox;
cxCheckBox11: TcxCheckBox;
cxLabel191: TcxLabel;
cxCurrencyEdit6: TcxCurrencyEdit;
cxLabel192: TcxLabel;
Shape226: TShape;
cxLabel193: TcxLabel;
cxLabel217: TcxLabel;
cxLabel225: TcxLabel;
Shape227: TShape;
cxLabel226: TcxLabel;
cxLabel227: TcxLabel;
chkCallBell: TcxCheckBox;
menuCallBell: TMenuItem;
CustView1Column29: TcxGridDBColumn;
CustView1Column30: TcxGridDBColumn;
lbCustCounselTitle: TListBox;
N1: TMenuItem;
CustView1Column31: TcxGridDBColumn;
Label26: TcxLabel;
Label5: TcxLabel;
Label7: TcxLabel;
CustView9Column22: TcxGridDBColumn;
btn_9_4: TcxButton;
CustView9Column23: TcxGridDBColumn;
CustView9Column24: TcxGridDBColumn;
cxLabel236: TcxLabel;
lbMileLostMonth: TcxLabel;
menuUpsoPee: TMenuItem;
gbUpsoPee: TcxGroupBox;
btn_UpsoPee_Save: TcxButton;
btn_UpsoPee_Close: TcxButton;
cxLabel228: TcxLabel;
cxLabel230: TcxLabel;
cxLabel231: TcxLabel;
cxLabel232: TcxLabel;
rb_Straight_Upso: TcxRadioButton;
rb_Declining_Upso: TcxRadioButton;
cxLabel233: TcxLabel;
edtCalValue: TcxCurrencyEdit;
cxLabel235: TcxLabel;
cxGroupBox5: TcxGroupBox;
cxLabel255: TcxLabel;
edCuMilet01: TcxCurrencyEdit;
cxLabel256: TcxLabel;
cxLabel258: TcxLabel;
edCuMilet02: TcxCurrencyEdit;
cxLabel261: TcxLabel;
CustView1Column32: TcxGridDBColumn;
CustView1Column33: TcxGridDBColumn;
cxLabel238: TcxLabel;
cxLabel239: TcxLabel;
cxLabel241: TcxLabel;
edMlgLost01: TcxTextEdit;
edMlgLost02: TcxTextEdit;
CustView3Column19: TcxGridDBColumn;
CustView3Column20: TcxGridDBColumn;
cxLabel270: TcxLabel;
cxLabel272: TcxLabel;
edMileageLost01: TcxCurrencyEdit;
Shape231: TShape;
cxLabel273: TcxLabel;
chkCust09Type03: TcxCheckBox;
cxDate9_2S: TcxDateEdit;
cxDate9_2E: TcxDateEdit;
btn_Date9_2: TcxButton;
CustView9Column25: TcxGridDBColumn;
CustView9Column26: TcxGridDBColumn;
Label18: TcxLabel;
CustView1Column34: TcxGridDBColumn;
CustView1Column35: TcxGridDBColumn;
CustView1Column36: TcxGridDBColumn;
CustView1Column37: TcxGridDBColumn;
chkMileSaveMile: TcxCheckBox;
cxLabel23: TcxLabel;
chkMileSaveCash: TcxCheckBox;
cxButton1: TcxButton;
cxLabel32: TcxLabel;
cxLabel34: TcxLabel;
cxLabel42: TcxLabel;
cxLabel47: TcxLabel;
cxLabel52: TcxLabel;
cxLabel63: TcxLabel;
cxLabel103: TcxLabel;
cxLabel108: TcxLabel;
cxLabel54: TcxLabel;
cxLabel121: TcxLabel;
cxLabel122: TcxLabel;
cxLabel123: TcxLabel;
cxLabel124: TcxLabel;
cxLabel125: TcxLabel;
cxLabel126: TcxLabel;
cxLabel127: TcxLabel;
cxLabel142: TcxLabel;
cxLabel146: TcxLabel;
cxLabel147: TcxLabel;
cxLabel25: TcxLabel;
cxPageControl2: TcxPageControl;
cxTabSheet81: TcxTabSheet;
cxTabSheet82: TcxTabSheet;
btn_8_1: TcxButton;
btn_8_2: TcxButton;
cxScrollBox2: TcxScrollBox;
cxLabel159: TcxLabel;
cxLabel160: TcxLabel;
edtCashValue0: TcxCurrencyEdit;
lblCashUnit0: TcxLabel;
cbCashType0: TcxComboBox;
cxLabel163: TcxLabel;
edtPostValue0: TcxCurrencyEdit;
lblPostUnit0: TcxLabel;
cbPostType0: TcxComboBox;
cxLabel165: TcxLabel;
edtCardValue0: TcxCurrencyEdit;
lblCardUnit0: TcxLabel;
cbCardType0: TcxComboBox;
cxLabel167: TcxLabel;
edtMileValue0: TcxCurrencyEdit;
lblMileUnit0: TcxLabel;
cbMileType0: TcxComboBox;
cxLabel176: TcxLabel;
cxLabel161: TcxLabel;
edtFirstAdd0: TcxCurrencyEdit;
cxLabel177: TcxLabel;
edtOverAdd0: TcxCurrencyEdit;
cxLabel179: TcxLabel;
cxLabel185: TcxLabel;
cxLabel186: TcxLabel;
cxLabel187: TcxLabel;
chkReceipNoMile0: TcxCheckBox;
cxLabel175: TcxLabel;
cxLabel197: TcxLabel;
btnMultiSch: TcxButton;
btnMultiSave: TcxButton;
grpExcel_OPT: TcxGroupBox;
btnAll1: TcxButton;
btnAll2: TcxButton;
RdExcel1: TcxRadioButton;
RdExcel2: TcxRadioButton;
cxLabel199: TcxLabel;
edtCashValue1: TcxCurrencyEdit;
lblCashUnit1: TcxLabel;
cbCashType1: TcxComboBox;
cxLabel201: TcxLabel;
edtPostValue1: TcxCurrencyEdit;
lblPostUnit1: TcxLabel;
cbPostType1: TcxComboBox;
cxLabel203: TcxLabel;
edtCardValue1: TcxCurrencyEdit;
lblCardUnit1: TcxLabel;
cbCardType1: TcxComboBox;
cxLabel205: TcxLabel;
edtMileValue1: TcxCurrencyEdit;
lblMileUnit1: TcxLabel;
cbMileType1: TcxComboBox;
cxLabel207: TcxLabel;
cxLabel208: TcxLabel;
edtFirstAdd1: TcxCurrencyEdit;
cxLabel209: TcxLabel;
edtOverAdd1: TcxCurrencyEdit;
cxLabel211: TcxLabel;
cxCheckBox12: TcxCheckBox;
cxLabel216: TcxLabel;
cxLabel219: TcxLabel;
edtCashValue3: TcxCurrencyEdit;
lblCashUnit3: TcxLabel;
cbCashType3: TcxComboBox;
cxLabel221: TcxLabel;
edtPostValue3: TcxCurrencyEdit;
lblPostUnit3: TcxLabel;
cbPostType3: TcxComboBox;
cxLabel223: TcxLabel;
edtCardValue3: TcxCurrencyEdit;
lblCardUnit3: TcxLabel;
cbCardType3: TcxComboBox;
cxLabel262: TcxLabel;
edtMileValue3: TcxCurrencyEdit;
lblMileUnit3: TcxLabel;
cbMileType3: TcxComboBox;
cxLabel264: TcxLabel;
cxLabel265: TcxLabel;
edtFirstAdd3: TcxCurrencyEdit;
cxLabel266: TcxLabel;
edtOverAdd3: TcxCurrencyEdit;
cxLabel267: TcxLabel;
cxCheckBox13: TcxCheckBox;
cxLabel275: TcxLabel;
cxLabel281: TcxLabel;
cxLabel282: TcxLabel;
chkReceipNoMile1: TcxCheckBox;
chkReceipNoMile3: TcxCheckBox;
cxLabel283: TcxLabel;
cxLabel284: TcxLabel;
cxLabel285: TcxLabel;
edtCashValue0A: TcxCurrencyEdit;
lblCashUnit0A: TcxLabel;
cbCashType0A: TcxComboBox;
cxLabel287: TcxLabel;
edtPostValue0A: TcxCurrencyEdit;
lblPostUnit0A: TcxLabel;
cbPostType0A: TcxComboBox;
cxLabel289: TcxLabel;
edtCardValue0A: TcxCurrencyEdit;
lblCardUnit0A: TcxLabel;
cbCardType0A: TcxComboBox;
cxLabel291: TcxLabel;
edtMileValue0A: TcxCurrencyEdit;
lblMileUnit0A: TcxLabel;
cbMileType0A: TcxComboBox;
cxLabel293: TcxLabel;
cxLabel294: TcxLabel;
edtFirstAdd0A: TcxCurrencyEdit;
cxLabel295: TcxLabel;
edtOverAdd0A: TcxCurrencyEdit;
cxLabel296: TcxLabel;
cxLabel297: TcxLabel;
cxLabel298: TcxLabel;
cxLabel299: TcxLabel;
chkReceipNoMile0A: TcxCheckBox;
cxLabel304: TcxLabel;
cxLabel306: TcxLabel;
edtCashValue1A: TcxCurrencyEdit;
lblCashUnit1A: TcxLabel;
cbCashType1A: TcxComboBox;
cxLabel308: TcxLabel;
edtPostValue1A: TcxCurrencyEdit;
lblPostUnit1A: TcxLabel;
cbPostType1A: TcxComboBox;
cxLabel310: TcxLabel;
edtCardValue1A: TcxCurrencyEdit;
lblCardUnit1A: TcxLabel;
cbCardType1A: TcxComboBox;
cxLabel312: TcxLabel;
edtMileValue1A: TcxCurrencyEdit;
lblMileUnit1A: TcxLabel;
cbMileType1A: TcxComboBox;
cxLabel314: TcxLabel;
cxLabel315: TcxLabel;
edtFirstAdd1A: TcxCurrencyEdit;
cxLabel316: TcxLabel;
edtOverAdd1A: TcxCurrencyEdit;
cxLabel317: TcxLabel;
cxCheckBox17: TcxCheckBox;
cxLabel322: TcxLabel;
cxLabel324: TcxLabel;
edtCashValue3A: TcxCurrencyEdit;
lblCashUnit3A: TcxLabel;
cbCashType3A: TcxComboBox;
cxLabel326: TcxLabel;
edtPostValue3A: TcxCurrencyEdit;
lblPostUnit3A: TcxLabel;
cbPostType3A: TcxComboBox;
cxLabel328: TcxLabel;
edtCardValue3A: TcxCurrencyEdit;
lblCardUnit3A: TcxLabel;
cbCardType3A: TcxComboBox;
cxLabel330: TcxLabel;
edtMileValue3A: TcxCurrencyEdit;
lblMileUnit3A: TcxLabel;
cbMileType3A: TcxComboBox;
cxLabel332: TcxLabel;
cxLabel333: TcxLabel;
edtFirstAdd3A: TcxCurrencyEdit;
cxLabel334: TcxLabel;
edtOverAdd3A: TcxCurrencyEdit;
cxLabel335: TcxLabel;
cxCheckBox18: TcxCheckBox;
cxLabel340: TcxLabel;
cxLabel346: TcxLabel;
cxLabel347: TcxLabel;
chkReceipNoMile1A: TcxCheckBox;
chkReceipNoMile3A: TcxCheckBox;
cxLabel348: TcxLabel;
cxLabel349: TcxLabel;
cxLabel162: TcxLabel;
cxLabel164: TcxLabel;
cxLabel166: TcxLabel;
cxLabel174: TcxLabel;
cxLabel188: TcxLabel;
cxLabel189: TcxLabel;
cxLabel194: TcxLabel;
cxLabel195: TcxLabel;
cxTabSheet12: TcxTabSheet;
pnl_CUTA12: TPanel;
pnl_CUTA121: TPanel;
cxLabel35: TcxLabel;
cxLabel43: TcxLabel;
cxLabel48: TcxLabel;
cxLabel62: TcxLabel;
cxLabel64: TcxLabel;
cxLabel104: TcxLabel;
cxLabel55: TcxLabel;
cxLabel143: TcxLabel;
cxGroupBox7: TcxGroupBox;
lbCustCompany12: TcxLabel;
cxGroupBox41: TcxGroupBox;
btn_12_2: TcxButton;
btn_12_1: TcxButton;
cxLabel200: TcxLabel;
cbKeynumber12: TcxComboBox;
cxLabel196: TcxLabel;
cxLabel198: TcxLabel;
edCustTel12: TcxTextEdit;
cxLabel202: TcxLabel;
edReCmdCode: TcxTextEdit;
cxRCMD: TcxGrid;
cxViewRCMD: TcxGridDBTableView;
cxGridDBColumn9: TcxGridDBColumn;
cxGridDBColumn10: TcxGridDBColumn;
cxGridDBColumn11: TcxGridDBColumn;
cxGridDBColumn24: TcxGridDBColumn;
cxGridDBColumn25: TcxGridDBColumn;
cxGridDBColumn29: TcxGridDBColumn;
cxGridLevel1: TcxGridLevel;
Shape1: TShape;
cxGroupBox42: TcxGroupBox;
cxGroupBox43: TcxGroupBox;
Shape2: TShape;
cxRCMD_D: TcxGrid;
cxViewRCMD_D: TcxGridDBTableView;
cxGridDBColumn30: TcxGridDBColumn;
cxGridDBColumn31: TcxGridDBColumn;
cxGridDBColumn32: TcxGridDBColumn;
cxGridDBColumn33: TcxGridDBColumn;
cxGridDBColumn34: TcxGridDBColumn;
cxGridDBColumn35: TcxGridDBColumn;
cxGridLevel2: TcxGridLevel;
cxRBA: TcxRadioButton;
cxRBB: TcxRadioButton;
cxDate12_1S: TcxDateEdit;
Label8: TLabel;
cxDate12_1E: TcxDateEdit;
btn_Date12_1: TcxButton;
cxLabel204: TcxLabel;
lblRCMD: TcxLabel;
cxViewRCMD_DColumn1: TcxGridDBColumn;
cxViewRCMD_DColumn2: TcxGridDBColumn;
cxViewRCMD_DColumn3: TcxGridDBColumn;
cxSplitter1: TcxSplitter;
btn_12_3: TcxButton;
btn_12_4: TcxButton;
btn_12_5: TcxButton;
CustView1Column38: TcxGridDBColumn;
CustView2Column25: TcxGridDBColumn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure rbFirstUseDate01Click(Sender: TObject);
procedure edCustName01KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure _retenTel01KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cbGubun1_1Click(Sender: TObject);
procedure cbLevel01MouseEnter(Sender: TObject);
procedure chkBubinNameClick(Sender: TObject);
procedure cxTextEdit17KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cxCheckBox9Click(Sender: TObject);
procedure btn_1_4Click(Sender: TObject);
procedure CB_SetDateClick(Sender: TObject);
procedure Cb_DelDateClick(Sender: TObject);
procedure CB_UseDateClick(Sender: TObject);
procedure MenuItem33Click(Sender: TObject);
procedure MenuItem34Click(Sender: TObject);
procedure MenuItem35Click(Sender: TObject);
procedure MenuItem36Click(Sender: TObject);
procedure MenuItem37Click(Sender: TObject);
procedure cxCheckBox4Click(Sender: TObject);
procedure btn_1_8Click(Sender: TObject);
procedure RbButton1MouseDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btn_1_5Click(Sender: TObject);
procedure btn_1_6Click(Sender: TObject);
procedure btn_1_7Click(Sender: TObject);
procedure btn_1_1Click(Sender: TObject);
procedure btn_1_2Click(Sender: TObject);
procedure btnAll2Click(Sender: TObject);
procedure btnAll6Click(Sender: TObject);
procedure btnAll7Click(Sender: TObject);
procedure CustView1CellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure CustView1ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
procedure CustView1DataControllerSortingChanged(Sender: TObject);
procedure CustView1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CustView1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CustView1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure mniN9Click(Sender: TObject);
procedure MenuItem6Click(Sender: TObject);
procedure rbAll01Click(Sender: TObject);
procedure cb_st_cityPropertiesChange(Sender: TObject);
procedure btn_2_2Click(Sender: TObject);
procedure chk_BeforeClick(Sender: TObject);
procedure chk_Before_FinishClick(Sender: TObject);
procedure chk_Before_NewClick(Sender: TObject);
procedure btn_Date2_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cb_S_Cnt1PropertiesChange(Sender: TObject);
procedure btn_2_3Click(Sender: TObject);
procedure btn_2_4Click(Sender: TObject);
procedure btn_2_5Click(Sender: TObject);
procedure chk_All_SelectClick(Sender: TObject);
procedure btn_2_1Click(Sender: TObject);
procedure rbCust03Type01Click(Sender: TObject);
procedure rbCust03Type02Click(Sender: TObject);
procedure btn_Date3_1Click(Sender: TObject);
procedure rbCust03Type03Click(Sender: TObject);
procedure rbCust03Type04Click(Sender: TObject);
procedure N_YesterdayClick(Sender: TObject);
procedure N_WeekClick(Sender: TObject);
procedure N_MonthClick(Sender: TObject);
procedure N_1Start31EndClick(Sender: TObject);
procedure btn_3_2Click(Sender: TObject);
procedure btn_3_3Click(Sender: TObject);
procedure btn_3_4Click(Sender: TObject);
procedure btn_3_5Click(Sender: TObject);
procedure chkCust03Type07Click(Sender: TObject);
procedure CustView3ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
procedure CustView3KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CustView3MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure CustView2KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CustView2KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CustView2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cbKeynumber01PropertiesChange(Sender: TObject);
procedure btn_4_3Click(Sender: TObject);
procedure btn_4_2Click(Sender: TObject);
procedure mniDetailCustLevelClick(Sender: TObject);
procedure chkCust04Type01Click(Sender: TObject);
procedure chkCust04Type02Click(Sender: TObject);
procedure chkCust04Type09Click(Sender: TObject);
procedure chkCust04Type03Click(Sender: TObject);
procedure chkCust04Type07Click(Sender: TObject);
procedure btn_4_1Click(Sender: TObject);
procedure chkCust04Type04Click(Sender: TObject);
procedure chkCust04Type05Click(Sender: TObject);
procedure chkCust04Type12Click(Sender: TObject);
procedure btn_5_1Click(Sender: TObject);
procedure btn_5_2Click(Sender: TObject);
procedure btn_5_3Click(Sender: TObject);
procedure btn_5_5Click(Sender: TObject);
procedure btn_5_6Click(Sender: TObject);
procedure btn_5_7Click(Sender: TObject);
procedure cxGridDBTableView1CellClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure cxGridDBTableView1CellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure cxGridDBTableView1ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
procedure btn_5_4Click(Sender: TObject);
procedure btn_6_6Click(Sender: TObject);
procedure btn_6_7Click(Sender: TObject);
procedure btn_6_9Click(Sender: TObject);
procedure btn_6_1Click(Sender: TObject);
procedure N_TodayClick(Sender: TObject);
procedure btn_1_3Click(Sender: TObject);
procedure cb_S_GradClick(Sender: TObject);
procedure btn_3_1Click(Sender: TObject);
procedure btn_Date3_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_Date3_2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cbGubun4_1Click(Sender: TObject);
procedure cbGubun6_1Click(Sender: TObject);
procedure rbCust06Type01Click(Sender: TObject);
procedure rbCust06Type02Click(Sender: TObject);
procedure CustView6ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
procedure CustView6KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CustView6MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_7_1Click(Sender: TObject);
procedure btn_7_2Click(Sender: TObject);
procedure btn_7_3Click(Sender: TObject);
procedure btn_7_4Click(Sender: TObject);
procedure btn_7_5Click(Sender: TObject);
procedure cxViewCustGroupCellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure cxViewCustLevelFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure cxViewCustLevelCanSelectRecord(Sender: TcxCustomGridTableView;
ARecord: TcxCustomGridRecord; var AAllow: Boolean);
procedure cxRadioButton10Click(Sender: TObject);
procedure btn_8_3Click(Sender: TObject);
procedure cxRadioButton19Click(Sender: TObject);
procedure chkBRNoMileClick(Sender: TObject);
procedure cxRadioButton13Click(Sender: TObject);
procedure cxRadioButton16Click(Sender: TObject);
procedure chkCust09Type02Click(Sender: TObject);
procedure btn_Date9_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_9_1Click(Sender: TObject);
procedure btn_9_2Click(Sender: TObject);
procedure btn_9_3Click(Sender: TObject);
procedure CustView9CellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure CustView9ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
procedure CustView9KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CustView9MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure chkCust09Type01Click(Sender: TObject);
procedure btn_Date10_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_10_1Click(Sender: TObject);
procedure btn_10_2Click(Sender: TObject);
procedure chkCust10Type02Click(Sender: TObject);
procedure CustView10ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
procedure CustView10KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CustView10MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_Date11_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_11_1Click(Sender: TObject);
procedure btn_8_1Click(Sender: TObject);
procedure btn_Date14_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_Date16_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cbKeynumber01Click(Sender: TObject);
procedure cbKeynumber02PropertiesChange(Sender: TObject);
procedure cbKeynumber04PropertiesChange(Sender: TObject);
procedure cbKeynumber06PropertiesChange(Sender: TObject);
procedure btn_8_2Click(Sender: TObject);
procedure cxPageControl1Change(Sender: TObject);
procedure btnAll1Click(Sender: TObject);
procedure btn_4_6Click(Sender: TObject);
procedure chkCust06Type04Click(Sender: TObject);
procedure cxColGLColorStylesGetContentStyle(Sender: TcxCustomGridTableView;
ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem;
var AStyle: TcxStyle);
procedure cxColCGColorStylesGetContentStyle(Sender: TcxCustomGridTableView;
ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem;
var AStyle: TcxStyle);
procedure cxColGLLevelNameStylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; var AStyle: TcxStyle);
procedure cxColCGLevelNameStylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; var AStyle: TcxStyle);
procedure Label7Click(Sender: TObject);
procedure btn_Date1_2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_Date1_3MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_Date1_4MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_Date1_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_Date1_5MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_Date1_6MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure chkCust03Type01Click(Sender: TObject);
procedure chkCust03Type02Click(Sender: TObject);
procedure chkCust03Type03Click(Sender: TObject);
procedure btn_Date4_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_Date13_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_4_5Click(Sender: TObject);
procedure btn_6_8Click(Sender: TObject);
procedure btn_11_2Click(Sender: TObject);
procedure cxTextEdit17KeyPress(Sender: TObject; var Key: Char);
procedure cxTextEdit18KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cxTextEdit19KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure rb_StraightClick(Sender: TObject);
procedure cxCheckBox3Click(Sender: TObject);
procedure chkCust08Type01Click(Sender: TObject);
procedure chkLTNoMileClick(Sender: TObject);
procedure cbGubun1_1PropertiesChange(Sender: TObject);
procedure pmCustMgrPopup(Sender: TObject);
procedure menuCallBellClick(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure CustView1ColumnPosChanged(Sender: TcxGridTableView; AColumn: TcxGridColumn);
procedure btn_9_4Click(Sender: TObject);
procedure menuUpsoPeeClick(Sender: TObject);
procedure btn_UpsoPee_SaveClick(Sender: TObject);
procedure btn_UpsoPee_CloseClick(Sender: TObject);
procedure chkCust09Type03Click(Sender: TObject);
procedure CustView1StylesGetContentStyle(Sender: TcxCustomGridTableView;
ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem;
var AStyle: TcxStyle);
procedure edCustName09KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cxButton1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbCashType0PropertiesChange(Sender: TObject);
procedure cbCardType0PropertiesChange(Sender: TObject);
procedure cbPostType0PropertiesChange(Sender: TObject);
procedure cbMileType0PropertiesChange(Sender: TObject);
procedure cbCashType1PropertiesChange(Sender: TObject);
procedure cbCashType3PropertiesChange(Sender: TObject);
procedure cbCashType0APropertiesChange(Sender: TObject);
procedure cbCashType1APropertiesChange(Sender: TObject);
procedure cbCardType1APropertiesChange(Sender: TObject);
procedure cbCashType3APropertiesChange(Sender: TObject);
procedure cbCardType1PropertiesChange(Sender: TObject);
procedure cbCardType3PropertiesChange(Sender: TObject);
procedure cbCardType0APropertiesChange(Sender: TObject);
procedure cbCardType3APropertiesChange(Sender: TObject);
procedure cbPostType1PropertiesChange(Sender: TObject);
procedure cbPostType3PropertiesChange(Sender: TObject);
procedure cbPostType0APropertiesChange(Sender: TObject);
procedure cbPostType1APropertiesChange(Sender: TObject);
procedure cbPostType3APropertiesChange(Sender: TObject);
procedure cbMileType1PropertiesChange(Sender: TObject);
procedure cbMileType3PropertiesChange(Sender: TObject);
procedure cbMileType0APropertiesChange(Sender: TObject);
procedure cbMileType1APropertiesChange(Sender: TObject);
procedure cbMileType3APropertiesChange(Sender: TObject);
procedure btnMultiSchClick(Sender: TObject);
procedure btnMultiSaveClick(Sender: TObject);
procedure cxRBAClick(Sender: TObject);
procedure btn_Date12_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure btn_12_1Click(Sender: TObject);
procedure btn_12_3Click(Sender: TObject);
procedure cxViewRCMDDataControllerSortingChanged(Sender: TObject);
procedure edCustTel12KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cxViewRCMDCellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure btn_12_2Click(Sender: TObject);
procedure btn_12_4Click(Sender: TObject);
procedure cxViewRCMD_DDataControllerSortingChanged(Sender: TObject);
procedure cxViewRCMDKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
UsrNameReg: TRegistry;
sFooter, sHeader, dt_sysdate2: string;
gbControlKeyDown: Boolean;
SCboLevelSeq : TStringList;
// 엑셀다운 내용(조회시 조회조건 기록)
FDetailKeyNum,
FExcelDownMng,
FExcelDownNormal,
FExcelDownHigh,
FExcelDownDetail,
FExcelDownSleep,
FExcelDownMile,
FExcelDownMileDetail,
FExcelDownRCMD,
FExcelDownRCMDD : string;
nFocus : integer;
AIndex : Integer;
bTag_Page2 : Boolean;
FCuData : TCuData;
FSchData, FSaveData : Array[1..6] of TMileData;
gslUpsoPeeSeq : TStringList;
procedure proc_SND_SMS(sGrid: TcxGridDBTableView; ASubscribe: Boolean = True);
procedure cxGridCopy(ASource, ATarget: TcxGridDBTableView; AKeyIndex: Integer; AKeyValue: string);
function DeleteCustomer(AView: TcxGridDBTableView; ALabel: TcxLabel): Boolean;
function DeleteCustomerData(AHdNo, ABrNo, AKeyNum, ACustNum, ACuSeq : string): Boolean;
procedure ResponseBATCH_CUST_MLG(AXmlStr: WideString);
procedure ChageCustLevel(AKeyNumber: string; ACombo: TcxComboBox);
procedure RequestData(AData: string);
procedure RequestDataCustLevel;
procedure RequestDataLevelFromGroupSeq(AGroupSeq: string);
procedure OnRefreshCustLevel(Sender: TObject);
procedure DelCustLevel(ALevelSeq: string);
procedure DelCustGroup(AGroupSeq: string);
function GetActiveDateControl(AIndex : integer; var AStDt, AEdDt: TcxDateEdit): Boolean;
procedure CustSetDateControl(AGubun: Integer; AStDt, AEdDt: TcxDateEdit);
procedure proc_bubin_init;
procedure proc_DetailSearch;
procedure proc_VirtureNum;
procedure proc_VirtureNum_init;
function func_ChkPhone: Boolean;
procedure proc_Cust_PhoneSel(Aidx: integer);
procedure proc_SleepSearch;
procedure proc_HighSearch;
procedure ResponseCustLevel(AXmlStr: WideString);
procedure ResponseCustGroup(AXmlStr: WideString);
procedure ResponseLevelFromGroupSeq(AXmlStr: WideString);
procedure ShowCustLevelWindow(AGroupName, AGroupSeq:string; AOneYear : Boolean; ALevelSeq: string = '');
procedure proc_EventCnt_Init( iGuBun : Integer );
procedure proc_init_mileage;
procedure proc_MileageAcc;
procedure proc_OKCashBack;
function func_Cust_Search(AHdNo, ABrNo, AKeyNumber, ASeq : string):Boolean;
procedure proc_CustCounsel_Title;
procedure proc_CustCounsel_Clear;
procedure proc_CustCounsel_Save;
procedure pSetMultiMileSave( pData : TMileData);
procedure pSetMultiMileInit;
public
{ Public declarations }
CutSeqList : TStringList;
iAddCnt : integer;
Click_chk : integer;
iFlag : integer;
// 좌측 메뉴 지사선택
lb_st_customer, lbNoSms: TStringList;
procedure proc_MileageSet;
procedure proc_MileageSet_Multi;
procedure proc_init;
procedure proc_BrNameSet;
procedure proc_GeneralSearch;
procedure proc_New_his(iType: Integer);
procedure proc_NotSMS(Br_no: string);
procedure proc_before_his;
procedure proc_before_comp;
procedure proc_before_new;
procedure proc_CustSearch(iType: Integer);
procedure proc_Branch_Change;
// 전문 응답 처리
procedure proc_recieve(slList: TStringList);
function func_buninSearch(sBrNo, sKeyNum, sCode: string): string;
function GetDeptCustomerCount(AHdNo, ABrNo, ADeptCode: string): Integer;
function func_recieve(slList: TStringList): Boolean;
procedure proc_MileageDetail;
end;
var
Frm_CUT: TFrm_CUT;
implementation
{$R *.dfm}
uses Main, xe_Dm, xe_Func, xe_GNL, xe_gnl2, xe_gnl3, xe_Lib, xe_Msg, xe_Query,
xe_packet, xe_xml, xe_CUT012, xe_CUT011, xe_Flash, xe_SMS, xe_structure,
xe_CUT03, xe_CUT02, xe_CUT07 , xe_CUT09, xe_CUT013, xe_CUT019,
xe_Jon03, xe_JON51, xe_BTN01, xe_BTN, xe_SearchWord;
procedure TFrm_CUT.btnAll2Click(Sender: TObject);
begin
grpExcel_OPT.Visible := False;
end;
procedure TFrm_CUT.btn_1_2Click(Sender: TObject);
var i, iSeq, iKeynumber, iCnt : Integer;
CutSeq : string;
begin
try
cxGrid1.Enabled := False;
CutSeqList := TStringList.Create;
cxRMileP.Checked := False;
cxRMileM.Checked := False;
cxRMileS.Checked := False;
chkNMCNG1.Checked := True;
cxCurrencyEdit7.text := '0';
cxTextEdit16.text := '';
mmoMilelistError.Clear;
CutSeq := '';
iCnt := 0;
iAddCnt := 0;
iSeq := CustView1.GetColumnByFieldName('SEQ').Index;
iKeynumber := CustView1.GetColumnByFieldName('대표번호').Index;
for I := 0 to CustView1.DataController.RecordCount - 1 do
begin
if (CustView1.ViewData.Records[i].Selected) then
begin
if CutSeq = '' then
begin
CutSeq := StringReplace(CustView1.ViewData.Records[I].Values[iKeynumber], '-', '', [rfreplaceAll]) + '/' + CustView1.ViewData.Records[I].Values[iSeq];
end else
begin
CutSeq := CutSeq + ',' + StringReplace(CustView1.ViewData.Records[I].Values[iKeynumber], '-', '', [rfreplaceAll]) + '/' + CustView1.ViewData.Records[I].Values[iSeq];
end;
Inc(iCnt);
Inc(iAddCnt);
end;
if iAddCnt = 1000 then
begin
CutSeqList.Add(CutSeq);
CutSeq := '';
iAddCnt := 0;
end;
end;
CutSeqList.Add(CutSeq);
if icnt < 1 then
begin
cxGrid1.Enabled := True;
GMessagebox('고객이 선택되지 않았습니다.', CDMSE);
Exit;
end;
cxlbl7.Caption := inttostr(icnt) + ' 명';
cxCurrencyEdit5.Text := inttostr(iAddCnt);
pnl_Chang_select.Visible := True;
except
end;
end;
procedure TFrm_CUT.btn_1_3Click(Sender: TObject);
begin
proc_bubin_init;
end;
procedure TFrm_CUT.btnAll6Click(Sender: TObject);
var i : Integer;
ErrCode: integer;
XmlData, sTemp, ErrMsg: string;
chkNum : string;
begin
Try
if (cxRMileP.Checked = False) and (cxRMileM.Checked = False) and (cxRMileS.Checked = False) then
begin
GMessagebox('마일리지 적용구분이 선택되지 않았습니다.', CDMSE);
Exit;
end;
if ( Trim(cxTextEdit16.TEXT) = '' ) And ( chkNMCNG2.Checked ) then
begin
if GMessagebox('고객명이 없습니다.' + #13#10 + '그래도 진행 하시겠습니까?', CDMSQ) = IDOK then
begin
mmoMilelistError.Lines.Add('고객명+마일리지 일괄변경 시작');
mmoMilelistError.Lines.Add('==============================');
if cxRMileP.Checked then chkNum := '1'
else if cxRMileM.Checked then chkNum := '2'
else if cxRMileS.Checked then chkNum := '3';
for i := 0 to CutSeqList.Count -1 do
begin
sTemp := '';
if i = CutSeqList.Count -1 then
sTemp := cxCurrencyEdit5.Text
else
sTemp := '1000';
if chkNMCNG1.Checked then
sTemp := sTemp + '│' + CutSeqList[i] + '│' + cxTextEdit16.Text + '│' + chkNum + '│' + StringReplace(cxCurrencyEdit7.Text, ',', '', [rfreplaceAll]) + '│' + '0'
else
sTemp := sTemp + '│' + CutSeqList[i] + '│' + cxTextEdit16.Text + '│' + chkNum + '│' + StringReplace(cxCurrencyEdit7.Text, ',', '', [rfreplaceAll]) + '│' + '1';
if not RequestBase_ErrorResult(GetCallable05('BATCH_CUST_MLG', 'MNG_CUST.BATCH_CUST_MLG', sTemp), XmlData, ErrCode, ErrMsg) then
begin
mmoMilelistError.Lines.Add(ErrMsg);
end else
ResponseBATCH_CUST_MLG(XmlData);
mmoMilelistError.Lines.Add('[' + IntToStr(i) + ']' + ErrMsg);
end;
end else Exit;
end else
begin
mmoMilelistError.Lines.Add('고객명+마일리지 일괄변경 시작');
mmoMilelistError.Lines.Add('==============================');
if cxRMileP.Checked then chkNum := '1'
else if cxRMileM.Checked then chkNum := '2'
else if cxRMileS.Checked then chkNum := '3';
for i := 0 to CutSeqList.Count -1 do
begin
sTemp := '';
if i = CutSeqList.Count -1 then
sTemp := cxCurrencyEdit5.Text
else
sTemp := '1000';
if chkNMCNG1.Checked then
sTemp := sTemp + '│' + CutSeqList[i] + '│' + cxTextEdit16.Text + '│' + chkNum + '│' + StringReplace(cxCurrencyEdit7.Text, ',', '', [rfreplaceAll]) + '│' + '0'
else
sTemp := sTemp + '│' + CutSeqList[i] + '│' + cxTextEdit16.Text + '│' + chkNum + '│' + StringReplace(cxCurrencyEdit7.Text, ',', '', [rfreplaceAll]) + '│' + '1';
if not RequestBase_ErrorResult(GetCallable05('BATCH_CUST_MLG', 'MNG_CUST.BATCH_CUST_MLG', sTemp), XmlData, ErrCode, ErrMsg) then
begin
mmoMilelistError.Lines.Add(ErrMsg);
end else
ResponseBATCH_CUST_MLG(XmlData);
mmoMilelistError.Lines.Add('[' + IntToStr(i+1) + ']' + ErrMsg);
mmoMilelistError.Lines.Add('==============================');
end;
end;
except
cxGrid1.Enabled := True;
CutSeqList.Free;
mmoMilelistError.Lines.Add('고객명+마일리지 일괄변경 중 오류 발생');
end;
if not chkSearchAdd.Checked then
CustView1.DataController.SetRecordCount(0);
proc_CustSearch(Click_chk);
cxCheckBox4.Checked := False;
FreeAndNil(CutSeqList);
end;
procedure TFrm_CUT.btnAll7Click(Sender: TObject);
begin
cxGrid1.Enabled := True;
pnl_Chang_select.Visible := False;
end;
procedure TFrm_CUT.btnMultiSchClick(Sender: TObject);
begin
proc_MileageSet_Multi;
end;
procedure TFrm_CUT.proc_MileageSet_Multi;
function fgetType( sValue : String ) : Integer;
begin
if StrToFloatDef(sValue, 0) = 0 then Result := 0 else
if StrToFloatDef(sValue, 0) <= 1 then Result := 2
else Result := 1
end;
function fgetValue( sValue : String ) : Integer;
begin
if StrToFloatDef(sValue, 0) = 0 then Result := 0 else
if StrToFloatDef(sValue, 0) <= 1 then Result := Trunc(StrToFloatDef(sValue, 0) * 100)
else Result := StrToIntDef(sValue, 0);
end;
var
msg, sBrNo, sBrName, Param : string;
XmlData, ErrMsg: string;
xdom: msDomDocument;
lst_Count, lst_Result: IXMLDomNodeList;
ls_Rcrd: TStringList;
I, ErrCode, idx : Integer;
begin
try
sBrNo := cxBrNo8.Text;
if sBrNo = '' then
begin
GMessagebox('마일리지 설정은 지사를 선택하셔야 합니다.', CDMSE);
proc_init_mileage;
Exit;
end;
if (GT_USERIF.LV = '10') and (not IsPassedManagementCu(sBrNo)) then
begin
msg := '[%s(%s)] 지사에서 고객관련 관리권한 이관(콜센터 상담원)을 설정 하지 않았습니다.'
+ #13#10'(해당 지사관리자에게 관리권한 이관[회사>지사관리>상세설정]을 요청바랍니다.)';
sBrName := GetBrName(sBrNo);
GMessagebox(Format(msg, [sBrNo, sBrName]), CDMSE);
proc_init_mileage;
Exit;
end;
if fGetChk_Search_HdBrNo('마일리지설정') then Exit;
Pnl_CUTA8.Enabled := True;
Param := sBrNo;
if not RequestBase(GetSel06('GET_MILEAGE_CFG_LIST', 'MNG_BR_MLG_CFG.GET_MILEAGE_CFG_LIST', '100', Param), XmlData, ErrCode, ErrMsg) then
begin
GMessagebox(Format('마일리지 복합결제 설정 조회 중 오류발생'#13#10'[%d]%s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
pSetMultiMileInit;
xdom := ComsDomDocument.Create;
try
xdom.loadXML(XmlData);
lst_Count := xdom.documentElement.selectNodes('/cdms/Service/Data');
if StrToIntDef(lst_Count.item[0].attributes.getNamedItem('Count').Text,0) > 0 then
begin
// 초기화
for i := 1 to 6 do
begin
if i in [1,2,3] then FSchData[i].mType := 'T'
else FSchData[i].mType := 'A';
if i in [1,4] then FSchData[i].mGubun := '0' else
if i in [2,5] then FSchData[i].mGubun := '1' else
if i in [3,6] then FSchData[i].mGubun := '3';
FSchData[i].mCash := '0';
FSchData[i].mPost := '0';
FSchData[i].mCard := '0';
FSchData[i].mMile := '0';
FSchData[i].mReceipNo := 'n';
FSchData[i].mFirstAdd := '0';
FSchData[i].mOverAdd := '0';
end;
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for I := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
if ls_Rcrd[0] = 'T' then
begin
if ls_Rcrd[1] = '0' then
begin
idx := 1;
cbCashType0.ItemIndex := fgetType(ls_Rcrd[2]);
edtCashValue0.Value := fgetValue(ls_Rcrd[2]);
cbPostType0.ItemIndex := fgetType(ls_Rcrd[3]);
edtPostValue0.Value := fgetValue(ls_Rcrd[3]);
cbCardType0.ItemIndex := fgetType(ls_Rcrd[4]);
edtCardValue0.Value := fgetValue(ls_Rcrd[4]);
cbMileType0.ItemIndex := fgetType(ls_Rcrd[5]);
edtMileValue0.Value := fgetValue(ls_Rcrd[5]);
chkReceipNoMile0.Checked := Trim(ls_Rcrd[6]) = 'y';
edtFirstAdd0.EditValue := ls_Rcrd[7];
edtOverAdd0.EditValue := ls_Rcrd[8];
end else
if ls_Rcrd[1] = '1' then
begin
idx := 2;
cbCashType1.ItemIndex := fgetType(ls_Rcrd[2]);
edtCashValue1.Value := fgetValue(ls_Rcrd[2]);
cbPostType1.ItemIndex := fgetType(ls_Rcrd[3]);
edtPostValue1.Value := fgetValue(ls_Rcrd[3]);
cbCardType1.ItemIndex := fgetType(ls_Rcrd[4]);
edtCardValue1.Value := fgetValue(ls_Rcrd[4]);
cbMileType1.ItemIndex := fgetType(ls_Rcrd[5]);
edtMileValue1.Value := fgetValue(ls_Rcrd[5]);
chkReceipNoMile1.Checked := Trim(ls_Rcrd[6]) = 'y';
edtFirstAdd1.EditValue := ls_Rcrd[7];
edtOverAdd1.EditValue := ls_Rcrd[8];
end else
if ls_Rcrd[1] = '3' then
begin
idx := 3;
cbCashType3.ItemIndex := fgetType(ls_Rcrd[2]);
edtCashValue3.Value := fgetValue(ls_Rcrd[2]);
cbPostType3.ItemIndex := fgetType(ls_Rcrd[3]);
edtPostValue3.Value := fgetValue(ls_Rcrd[3]);
cbCardType3.ItemIndex := fgetType(ls_Rcrd[4]);
edtCardValue3.Value := fgetValue(ls_Rcrd[4]);
cbMileType3.ItemIndex := fgetType(ls_Rcrd[5]);
edtMileValue3.Value := fgetValue(ls_Rcrd[5]);
chkReceipNoMile3.Checked := Trim(ls_Rcrd[6]) = 'y';
edtFirstAdd3.EditValue := ls_Rcrd[7];
edtOverAdd3.EditValue := ls_Rcrd[8];
end;
end else
if ls_Rcrd[0] = 'A' then
begin
if ls_Rcrd[1] = '0' then
begin
idx := 4;
cbCashType0A.ItemIndex := fgetType(ls_Rcrd[2]);
edtCashValue0A.Value := fgetValue(ls_Rcrd[2]);
cbPostType0A.ItemIndex := fgetType(ls_Rcrd[3]);
edtPostValue0A.Value := fgetValue(ls_Rcrd[3]);
cbCardType0A.ItemIndex := fgetType(ls_Rcrd[4]);
edtCardValue0A.Value := fgetValue(ls_Rcrd[4]);
cbMileType0A.ItemIndex := fgetType(ls_Rcrd[5]);
edtMileValue0A.Value := fgetValue(ls_Rcrd[5]);
chkReceipNoMile0A.Checked := Trim(ls_Rcrd[6]) = 'y';
edtFirstAdd0A.EditValue := ls_Rcrd[7];
edtOverAdd0A.EditValue := ls_Rcrd[8];
end else
if ls_Rcrd[1] = '1' then
begin
idx := 5;
cbCashType1A.ItemIndex := fgetType(ls_Rcrd[2]);
edtCashValue1A.Value := fgetValue(ls_Rcrd[2]);
cbPostType1A.ItemIndex := fgetType(ls_Rcrd[3]);
edtPostValue1A.Value := fgetValue(ls_Rcrd[3]);
cbCardType1A.ItemIndex := fgetType(ls_Rcrd[4]);
edtCardValue1A.Value := fgetValue(ls_Rcrd[4]);
cbMileType1A.ItemIndex := fgetType(ls_Rcrd[5]);
edtMileValue1A.Value := fgetValue(ls_Rcrd[5]);
chkReceipNoMile1A.Checked := Trim(ls_Rcrd[6]) = 'y';
edtFirstAdd1A.EditValue := ls_Rcrd[7];
edtOverAdd1A.EditValue := ls_Rcrd[8];
end else
if ls_Rcrd[1] = '3' then
begin
idx := 6;
cbCashType3A.ItemIndex := fgetType(ls_Rcrd[2]);
edtCashValue3A.Value := fgetValue(ls_Rcrd[2]);
cbPostType3A.ItemIndex := fgetType(ls_Rcrd[3]);
edtPostValue3A.Value := fgetValue(ls_Rcrd[3]);
cbCardType3A.ItemIndex := fgetType(ls_Rcrd[4]);
edtCardValue3A.Value := fgetValue(ls_Rcrd[4]);
cbMileType3A.ItemIndex := fgetType(ls_Rcrd[5]);
edtMileValue3A.Value := fgetValue(ls_Rcrd[5]);
chkReceipNoMile3A.Checked := Trim(ls_Rcrd[6]) = 'y';
edtFirstAdd3A.EditValue := ls_Rcrd[7];
edtOverAdd3A.EditValue := ls_Rcrd[8];
end;
end;
FSchData[idx].mType := ls_Rcrd[0];
FSchData[idx].mGubun := ls_Rcrd[1];
FSchData[idx].mCash := ls_Rcrd[2];
FSchData[idx].mPost := ls_Rcrd[3];
FSchData[idx].mCard := ls_Rcrd[4];
FSchData[idx].mMile := ls_Rcrd[5];
FSchData[idx].mReceipNo := ls_Rcrd[6];
FSchData[idx].mFirstAdd := ls_Rcrd[7];
FSchData[idx].mOverAdd := ls_Rcrd[8];
end;
finally
ls_Rcrd.Free;
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
end;
finally
xdom := Nil;
end;
except
on e: exception do
begin
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_CUT.btn_3_3Click(Sender: TObject);
begin
DeleteCustomer(CustView3, lbCount01);
end;
procedure TFrm_CUT.btn_1_7Click(Sender: TObject);
begin
DeleteCustomer(CustView1, lbCount01);
end;
procedure TFrm_CUT.btn_2_3Click(Sender: TObject);
begin
DeleteCustomer(CustView2, lbCount02);
end;
procedure TFrm_CUT.cbCardType0APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCardUnit0A.Caption := '%'
else lblCardUnit0A.Caption := '원';
end;
procedure TFrm_CUT.cbCardType0PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCardUnit0.Caption := '%'
else lblCardUnit0.Caption := '원';
end;
procedure TFrm_CUT.cbCardType1APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCardUnit1A.Caption := '%'
else lblCardUnit1A.Caption := '원';
end;
procedure TFrm_CUT.cbCardType1PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCardUnit1.Caption := '%'
else lblCardUnit1.Caption := '원';
end;
procedure TFrm_CUT.cbCardType3APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCardUnit3A.Caption := '%'
else lblCardUnit3A.Caption := '원';
end;
procedure TFrm_CUT.cbCardType3PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCardUnit3.Caption := '%'
else lblCardUnit3.Caption := '원';
end;
procedure TFrm_CUT.cbCashType0APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCashUnit0A.Caption := '%'
else lblCashUnit0A.Caption := '원';
end;
procedure TFrm_CUT.cbCashType0PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCashUnit0.Caption := '%'
else lblCashUnit0.Caption := '원';
end;
procedure TFrm_CUT.cbCashType1APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCashUnit1A.Caption := '%'
else lblCashUnit1A.Caption := '원';
end;
procedure TFrm_CUT.cbCashType1PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCashUnit1.Caption := '%'
else lblCashUnit1.Caption := '원';
end;
procedure TFrm_CUT.cbCashType3APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCashUnit3A.Caption := '%'
else lblCashUnit3A.Caption := '원';
end;
procedure TFrm_CUT.cbCashType3PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblCashUnit3.Caption := '%'
else lblCashUnit3.Caption := '원';
end;
procedure TFrm_CUT.cbGubun1_1Click(Sender: TObject);
begin
if cbGubun1_1.ItemIndex = 0 then
begin
chkBubinCust.Enabled := True;
cbBCustList.Enabled := False;
btn_1_3.Enabled := False;
end else
if cbGubun1_1.ItemIndex = 3 then
begin
proc_bubin_init;
chkBubinCust.Enabled := False;
cbBCustList.Enabled := True;
btn_1_3.Enabled := True;
end else
begin
chkBubinCust.Enabled := False;
cbBCustList.Enabled := False;
cbBCustList.ItemIndex := 0;
btn_1_3.Enabled := False;
end;
end;
procedure TFrm_CUT.cbGubun1_1PropertiesChange(Sender: TObject);
begin
if cbGubun1_1.ItemIndex = 2 then
begin
if gs_CallBellUse then
begin
chkCallBell.visible := True;
chkCallBell.Checked := False;
cbLevel01.Left := 222;
cbLevel01.width := 97;
end;
end
else
begin
chkCallBell.visible := False;
chkCallBell.Checked := False;
cbLevel01.Left := 175;
cbLevel01.width := 144;
end;
end;
procedure TFrm_CUT.cbGubun4_1Click(Sender: TObject);
begin
if cbGubun4_1.ItemIndex = 0 then
begin
chkCust04Type06.Enabled := True;
chkCust04Type07.Enabled := False;
chkCust04Type07Click(chkCust04Type07);
btn_4_1.Enabled := False;
end else
if cbGubun4_1.ItemIndex = 3 then
begin
proc_bubin_init;
chkCust04Type06.Enabled := False;
chkCust04Type07.Enabled := True;
btn_4_1.Enabled := True;
chkCust04Type07Click(chkCust04Type07);
end else
begin
chkCust04Type06.Enabled := False;
chkCust04Type07.Enabled := False;
chkCust04Type07Click(chkCust04Type07);
btn_4_1.Enabled := False;
end;
end;
procedure TFrm_CUT.cbGubun6_1Click(Sender: TObject);
begin
if cbGubun6_1.ItemIndex = 0 then
begin
chkCust06Type02.Enabled := True;
end else
if cbGubun6_1.ItemIndex = 3 then
begin
chkCust06Type02.Enabled := False;
end;
end;
procedure TFrm_CUT.cbKeynumber01Click(Sender: TObject);
var
sName, sBrName, sHdNo, sBrNo: string;
iIdx: Integer;
begin
if TcxComboBox(Sender).Tag = 1 then Exit;
if GT_USERIF.LV = '60' then
begin
if GT_SEL_BRNO.GUBUN <> '1' then
begin
if TcxComboBox(Sender).Text = '전체' then
begin
sName := '[' + GT_SEL_BRNO.HDNO + '] 전체';
sHdNo := GT_SEL_BRNO.HDNO;
sBrNo := '';
end else
begin
sHdNo := GT_SEL_BRNO.HDNO;
if cxPageControl1.ActivePageIndex in [11, 10] then
begin
sBrNo := GT_SEL_BRNO.BrNo;
end else
begin
if (TcxComboBox(Sender).Properties.Items.Count > 1) and (TcxComboBox(Sender).ItemIndex > 0) then
begin
if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB
sBrNo := scb_DsBranchCode.Strings[scb_KeyNumber.IndexOf(TcxComboBox(Sender).Text)]
else
sBrNo := scb_DsBranchCode.Strings[TcxComboBox(Sender).ItemIndex - 1]
end else
begin
if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB
sBrNo := scb_DsBranchCode.Strings[scb_KeyNumber.IndexOf(TcxComboBox(Sender).Text)]
else
sBrNo := scb_DsBranchCode.Strings[TcxComboBox(Sender).ItemIndex];
end;
end;
iIdx := scb_BranchCode.IndexOf(sBrNo);
if iIdx >= 0 then
sBrName := scb_BranchName[iIdx]
else
sBrName := '';
sName := '[' + sHdNo + '] - [' + sBrNo + ']' + sBrName;
end;
end else
begin
sHdNo := GT_SEL_BRNO.HDNO;
sBrNo := GT_SEL_BRNO.BrNo;
iIdx := scb_BranchCode.IndexOf(sBrNo);
if iIdx >= 0 then
sBrName := scb_BranchName[iIdx]
else
sBrName := '';
sName := '[' + sHdNo + '] - [' + sBrNo + ']' + sBrName;
end;
end else
begin
sHdNo := GT_SEL_BRNO.HDNO;
sBrNo := GT_SEL_BRNO.BrNo;
iIdx := scb_BranchCode.IndexOf(sBrNo);
if iIdx >= 0 then
sBrName := scb_BranchName[iIdx]
else
sBrName := '';
sName := '[' + sHdNo + '] - [' + sBrNo + ']' + sBrName;
end;
case cxPageControl1.ActivePageIndex of
0:
begin
lbCustCompany01.Caption := sName;
cxHdNo1.Text := sHdNo;
cxBrNo1.Text := sBrNo;
proc_bubin_init;
end;
1:
begin
lbCustCompany02.Caption := sName;
cxHdNo2.Text := sHdNo;
cxBrNo2.Text := sBrNo;
end;
2:
begin
lbCustCompany03.Caption := sName;
cxHdNo3.Text := sHdNo;
cxBrNo3.Text := sBrNo;
end;
3:
begin
lbCustCompany04.Caption := sName;
cxHdNo4.Text := sHdNo;
cxBrNo4.Text := sBrNo;
proc_bubin_init;
end;
4:
begin
lbCustCompany05.Caption := sName;
cxHdNo5.Text := sHdNo;
cxBrNo5.Text := sBrNo;
if ((sBrNo <> 'B811') and (sBrNo <> 'G640') and (sBrNo <> 'B100') and (sBrNo <> 'C468')) or (GS_PRJ_AREA = 'O') then
begin
ShowMessage('안심번호 설정은 신청한 지사를 선택하셔야 합니다.' + #13#10 + #13#10
+ '문의사항은 콜마너 업무게시판에 등록해 주세요.');
Exit;
end;
proc_VirtureNum_init;
end;
5:
begin
lbCustCompany06.Caption := sName;
cxHdNo6.Text := sHdNo;
cxBrNo6.Text := sBrNo;
end;
6:
begin
lbCustCompany07.Caption := sName;
end;
7:
begin
lbCustCompany08.Caption := sName;
cxHdNo8.Text := sHdNo;
cxBrNo8.Text := sBrNo;
end;
8:
begin
lbCustCompany09.Caption := sName;
cxHdNo9.Text := sHdNo;
cxBrNo9.Text := sBrNo;
end;
9:
begin
lbCustCompany10.Caption := sName;
cxHdNo10.Text := sHdNo;
cxBrNo10.Text := sBrNo;
end;
10:
begin
lbCustCompany11.Caption := sName;
cxHdNo11.Text := sHdNo;
cxBrNo11.Text := sBrNo;
end;
end;
end;
procedure TFrm_CUT.cbKeynumber01PropertiesChange(Sender: TObject);
begin
ChageCustLevel(TcxComboBox(Sender).Text, cbLevel01);
end;
procedure TFrm_CUT.cbKeynumber02PropertiesChange(Sender: TObject);
begin
ChageCustLevel(TcxComboBox(Sender).Text, cb_S_Grad);
end;
procedure TFrm_CUT.cbKeynumber04PropertiesChange(Sender: TObject);
begin
ChageCustLevel(TcxComboBox(Sender).Text, cbLevel04);
end;
procedure TFrm_CUT.cbKeynumber06PropertiesChange(Sender: TObject);
begin
ChageCustLevel(TcxComboBox(Sender).Text, cbLevel06);
end;
procedure TFrm_CUT.cbLevel01MouseEnter(Sender: TObject);
begin
TcxComboBox(Sender).Hint := TcxComboBox(Sender).Text;
end;
procedure TFrm_CUT.cbMileType0APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblMileUnit0A.Caption := '%'
else lblMileUnit0A.Caption := '원';
end;
procedure TFrm_CUT.cbMileType0PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblMileUnit0.Caption := '%'
else lblMileUnit0.Caption := '원';
end;
procedure TFrm_CUT.cbMileType1APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblMileUnit1A.Caption := '%'
else lblMileUnit1A.Caption := '원';
end;
procedure TFrm_CUT.cbMileType1PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblMileUnit1.Caption := '%'
else lblMileUnit1.Caption := '원';
end;
procedure TFrm_CUT.cbMileType3APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblMileUnit3A.Caption := '%'
else lblMileUnit3A.Caption := '원';
end;
procedure TFrm_CUT.cbMileType3PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblMileUnit3.Caption := '%'
else lblMileUnit3.Caption := '원';
end;
procedure TFrm_CUT.cbPostType0APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblPostUnit0A.Caption := '%'
else lblPostUnit0A.Caption := '원';
end;
procedure TFrm_CUT.cbPostType0PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblPostUnit0.Caption := '%'
else lblPostUnit0.Caption := '원';
end;
procedure TFrm_CUT.cbPostType1APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblPostUnit1A.Caption := '%'
else lblPostUnit1A.Caption := '원';
end;
procedure TFrm_CUT.cbPostType1PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblPostUnit1.Caption := '%'
else lblPostUnit1.Caption := '원';
end;
procedure TFrm_CUT.cbPostType3APropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblPostUnit3A.Caption := '%'
else lblPostUnit3A.Caption := '원';
end;
procedure TFrm_CUT.cbPostType3PropertiesChange(Sender: TObject);
begin
if TcxComboBox(Sender).ItemIndex = 2 then lblPostUnit3.Caption := '%'
else lblPostUnit3.Caption := '원';
end;
procedure TFrm_CUT.Cb_DelDateClick(Sender: TObject);
begin
if CB_DelDate.Checked then
begin
Pnl_Chk3.Enabled := True;
de_3stDate.Enabled := True;
de_3edDate.Enabled := True;
end else
begin
Pnl_Chk3.Enabled := False;
de_3stDate.Enabled := False;
de_3edDate.Enabled := False;
end;
end;
procedure TFrm_CUT.CB_SetDateClick(Sender: TObject);
begin
if CB_SetDate.Checked then
begin
Pnl_Chk1.Enabled := True;
de_1stDate.Enabled := True;
de_1edDate.Enabled := True;
end else
begin
Pnl_Chk1.Enabled := False;
de_1stDate.Enabled := False;
de_1edDate.Enabled := False;
end;
end;
procedure TFrm_CUT.cb_st_cityPropertiesChange(Sender: TObject);
var
i, k: Integer;
sl_City: TStringList;
begin
try
if cb_st_city.Tag = 1 then
Exit;
cb_st_ward.Properties.Items.Clear;
cb_st_ward.Properties.Items.Add('지역전체');
sl_City := TStringList.Create;
sl_city.Clear;
sl_city.Assign(GT_MAPOrigi.slCity); // 20080616.
if cb_st_city.ItemIndex > 1 then
begin
for k := 0 to 2 do
begin
i := sl_City.IndexOf(cb_st_City.Text);
if i > 1 then
begin
if (cb_st_City.Text <> sl_city.Strings[i - 1]) and
(cb_st_City.Text = sl_city.Strings[i])
and (cb_st_City.Text <> sl_city.Strings[i + 1]) then
begin
sl_City.Delete(i);
sl_City.Insert(i, ' ');
end;
end;
end;
end;
if cb_st_city.ItemIndex = 0 then
Exit;
// 20080616.
for i := sl_city.IndexOf(cb_st_City.Text) to GT_MAPOrigi.slCity.Count - 1 do
begin
if i > 1 then
begin
if (cb_st_City.Text <> GT_MAPOrigi.slCity[i]) and (cb_st_City.Text <> GT_MAPOrigi.slCity[i + 1]) then
break;
end;
if (cb_st_city.Text = sl_city.Strings[i]) and (cb_st_Ward.Properties.Items.IndexOf(GT_MAPOrigi.slWard[i]) < 0) and (GT_MAPOrigi.slWard[i] <> '' ) then
cb_st_Ward.Properties.Items.Add(GT_MAPOrigi.slWard[i]);
end;
cb_st_Ward.ItemIndex := 0;
finally
freeandnil(sl_city);
end;
end;
procedure TFrm_CUT.cb_S_Cnt1PropertiesChange(Sender: TObject);
begin
if (Trim(cb_S_Cnt1.Text) <> '') or (Trim(cb_S_Cnt2.Text) <> '')
or (Trim(cb_S_CCnt1.Text) <> '') or (Trim(cb_S_CCnt2.Text) <> '') then
begin
cxDate2_1S.Enabled := False;
cxDate2_1E.Enabled := False;
cxDate2_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 1;
cxDate2_1E.Date := cxDate2_1S.Date + 1;
chk_Before.Checked := False;
chk_Before_Finish.Checked := False;
end else
begin
cxDate2_1S.Enabled := True;
cxDate2_1E.Enabled := True;
end;
end;
procedure TFrm_CUT.cb_S_GradClick(Sender: TObject);
begin
if cb_S_Grad.ItemIndex > 0 then
begin
cxDate2_1S.Enabled := False;
cxDate2_1E.Enabled := False;
cxDate2_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 1;
cxDate2_1E.Date := cxDate2_1S.Date + 1;
end else
begin
cxDate2_1S.Enabled := True;
cxDate2_1E.Enabled := True;
end;
end;
procedure TFrm_CUT.CB_UseDateClick(Sender: TObject);
begin
if CB_UseDate.Checked then
begin
Pnl_Chk2.Enabled := True;
de_2stDate.Enabled := True;
de_2edDate.Enabled := True;
end else
begin
Pnl_Chk2.Enabled := False;
de_2stDate.Enabled := False;
de_2edDate.Enabled := False;
end;
end;
procedure TFrm_CUT.ChageCustLevel(AKeyNumber: string; ACombo: TcxComboBox);
var
I : Integer;
CustGroup: TCustGroup;
begin
ACombo.Properties.Items.Clear;
SCboLevelSeq.Clear;
ACombo.Properties.Items.Add('전체');
SCboLevelSeq.Add('');
if AKeyNumber = '전체' then
begin
for I := 0 to Length(scb_CustGroupInfo) - 1 do
begin
ACombo.Properties.Items.Add(Format('%s - %s', [scb_CustGroupInfo[i].GroupName, scb_CustGroupInfo[i].LevelName]));
SCboLevelSeq.Add(scb_CustGroupInfo[I].LevelSeq);
end;
end else
begin
GetCustGroup(AKeyNumber, CustGroup);
for i := 0 to Length(CustGroup.LevelInfo) - 1 do
begin
ACombo.Properties.Items.Add(Format('%s - %s', [CustGroup.GroupName, CustGroup.LevelInfo[i].LevelName]));
SCboLevelSeq.Add(CustGroup.LevelInfo[i].LevelSeq);
end;
end;
ACombo.ItemIndex := 0;
end;
procedure TFrm_CUT.chkCust04Type12Click(Sender: TObject);
begin
cxGridSelectAll(CustView4, TcxCheckBox(Sender).Checked);
end;
procedure TFrm_CUT.chkCust06Type04Click(Sender: TObject);
begin
cxGridSelectAll(CustView6, TcxCheckBox(Sender).Checked);
end;
procedure TFrm_CUT.chkCust08Type01Click(Sender: TObject);
begin
if chkCust08Type01.Checked then
begin
if cxRadioButton10.Checked then
begin
cxRadioButton13.Checked := True;
cxRadioButton13Click(cxRadioButton13);
cxRadioButton16.Checked := True;
cxRadioButton16Click(cxRadioButton16);
cxRadioButton19.Checked := True;
cxRadioButton19Click(cxRadioButton19);
end
else
if cxRadioButton11.Checked then
begin
cxRadioButton14.Checked := True;
cxRadioButton13Click(cxRadioButton14);
cxRadioButton17.Checked := True;
cxRadioButton16Click(cxRadioButton17);
cxRadioButton20.Checked := True;
cxRadioButton19Click(cxRadioButton20);
end
else
if cxRadioButton12.Checked then
begin
cxRadioButton15.Checked := True;
cxRadioButton13Click(cxRadioButton15);
cxRadioButton18.Checked := True;
cxRadioButton16Click(cxRadioButton18);
cxRadioButton21.Checked := True;
cxRadioButton19Click(cxRadioButton21);
end;
cxTextEdit4.Value := cxTextEdit1.Value;
cxTextEdit5.Value := cxTextEdit2.Value;
cxTextEdit6.Text := cxTextEdit3.Text;
cxTextEdit7.Value := cxTextEdit1.Value;
cxTextEdit8.Value := cxTextEdit2.Value;
cxTextEdit9.Text := cxTextEdit3.Text;
cxTextEdit10.Value := cxTextEdit1.Value;
cxTextEdit11.Value := cxTextEdit2.Value;
cxTextEdit12.Text := cxTextEdit3.Text;
end;
end;
procedure TFrm_CUT.chkBRNoMileClick(Sender: TObject);
begin
if chkBRNoMile.Checked then
begin
chkBRNoMile.Tag := 1;
cxTextEdit7.Value := 0;
cxTextEdit8.Value := 0;
cxTextEdit9.Text := '';
cxLabel148.Caption := '원';
cxRadioButton16.Checked := True;
end;
end;
procedure TFrm_CUT.chkBubinNameClick(Sender: TObject);
begin
if chkBubinName.Checked then
begin
cbBCustList.Enabled := True;
btn_1_3.Enabled := True;
end else
begin
cbBCustList.Enabled := False;
btn_1_3.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust03Type01Click(Sender: TObject);
begin
if chkCust03Type01.Checked then
begin
Pnl_A3Chk1.Enabled := True;
de_A31stDate.Enabled := True;
de_A31edDate.Enabled := True;
end else
begin
Pnl_A3Chk1.Enabled := False;
de_A31stDate.Enabled := False;
de_A31edDate.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust03Type02Click(Sender: TObject);
begin
if chkCust03Type02.Checked then
begin
Pnl_A3Chk3.Enabled := True;
de_A33stDate.Enabled := True;
de_A33edDate.Enabled := True;
end else
begin
Pnl_A3Chk3.Enabled := False;
de_A33stDate.Enabled := False;
de_A33edDate.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust03Type03Click(Sender: TObject);
begin
if chkCust03Type03.Checked then
begin
Pnl_A3Chk2.Enabled := True;
de_A32stDate.Enabled := True;
de_A32edDate.Enabled := True;
end else
begin
Pnl_A3Chk2.Enabled := False;
de_A32stDate.Enabled := False;
de_A32edDate.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust03Type07Click(Sender: TObject);
begin
cxGridSelectAll(CustView3, TcxCheckBox(Sender).Checked);
end;
procedure TFrm_CUT.chkCust04Type01Click(Sender: TObject);
begin
if chkCust04Type01.Checked then
begin
cxDate4_1S.Enabled := True;
cxDate4_1E.Enabled := True;
btn_Date4_1.Enabled := True;
end else
begin
cxDate4_1S.Enabled := False;
cxDate4_1E.Enabled := False;
btn_Date4_1.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust04Type02Click(Sender: TObject);
begin
if chkCust04Type02.Checked then
begin
cxDate4_2S.Enabled := True;
cxDate4_2E.Enabled := True;
btn_Date4_2.Enabled := True;
end else
begin
cxDate4_2S.Enabled := False;
cxDate4_2E.Enabled := False;
btn_Date4_2.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust04Type03Click(Sender: TObject);
begin
if chkCust04Type03.Checked then
begin
cbArea03.Enabled := True;
cbArea04.Enabled := True;
rbCust04Type01.Enabled := True;
rbCust04Type02.Enabled := True;
cbArea03.Tag := 1;
cbArea03.ItemIndex := 0;
cbArea03.Tag := 0;
end else
begin
cbArea03.Enabled := False;
cbArea04.Enabled := False;
rbCust04Type01.Enabled := False;
rbCust04Type02.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust04Type04Click(Sender: TObject);
begin
if chkCust04Type04.Checked then
begin
edCust04Type01.Enabled := True;
edCust04Type02.Enabled := True;
end else
begin
edCust04Type01.Enabled := False;
edCust04Type02.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust04Type05Click(Sender: TObject);
begin
if chkCust04Type05.Checked then
begin
edCust04Type03.Enabled := True;
edCust04Type04.Enabled := True;
end else
begin
edCust04Type03.Enabled := False;
edCust04Type04.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust04Type07Click(Sender: TObject);
begin
if chkCust04Type07.Checked then
begin
cbBCustList4.Enabled := True;
btn_4_1.Enabled := True;
end else
begin
cbBCustList4.Enabled := False;
btn_4_1.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust04Type09Click(Sender: TObject);
begin
if chkCust04Type09.Checked then
begin
cxDate4_3S.Enabled := True;
cxDate4_3E.Enabled := True;
btn_Date4_3.Enabled := True;
end else
begin
cxDate4_3S.Enabled := False;
cxDate4_3E.Enabled := False;
btn_Date4_3.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust09Type01Click(Sender: TObject);
begin
cxGridSelectAll(CustView9, TcxCheckBox(Sender).Checked);
end;
procedure TFrm_CUT.chkCust09Type02Click(Sender: TObject);
begin
if chkCust09Type02.Checked then
begin
cxDate9_1S.Enabled := True;
cxDate9_1E.Enabled := True;
btn_Date9_1.Enabled := True;
end else
begin
cxDate9_1S.Enabled := False;
cxDate9_1E.Enabled := False;
btn_Date9_1.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust09Type03Click(Sender: TObject);
begin
if chkCust09Type03.Checked then
begin
cxDate9_2S.Enabled := True;
cxDate9_2E.Enabled := True;
btn_Date9_2.Enabled := True;
end else
begin
cxDate9_2S.Enabled := False;
cxDate9_2E.Enabled := False;
btn_Date9_2.Enabled := False;
end;
end;
procedure TFrm_CUT.chkCust10Type02Click(Sender: TObject);
begin
if chkCust10Type02.Checked then
begin
cxDate10_1S.Enabled := True;
cxDate10_1E.Enabled := True;
btn_Date10_1.Enabled := True;
end else
begin
cxDate10_1S.Enabled := False;
cxDate10_1E.Enabled := False;
btn_Date10_1.Enabled := False;
end;
end;
procedure TFrm_CUT.chkLTNoMileClick(Sender: TObject);
begin
if (chkLTNoMile.checked) and (chkCDNoMile.checked) and (cxCheckBox3.checked) then
begin
cxCheckBox3.checked := False;
end;
if (chkLTNoMile.checked) and (Not chkCDNoMile.checked) then
begin
cxCheckBox3.Caption := '"후불(카드)" 별도 적립 사용';
end else
if (Not chkLTNoMile.checked) and (chkCDNoMile.checked) then
begin
cxCheckBox3.Caption := '"후불" 별도 적립 사용';
end else
if (Not chkLTNoMile.checked) and (Not chkCDNoMile.checked) then
begin
cxCheckBox3.Caption := '"후불" + "후불(카드)" 별도 적립 사용';
end else
if (chkLTNoMile.checked) and (chkCDNoMile.checked) then
begin
cxCheckBox3.Caption := '"후불" + "후불(카드)" 별도 적립 사용';
end;
end;
procedure TFrm_CUT.chk_All_SelectClick(Sender: TObject);
begin
cxGridSelectAll(CustView2, TcxCheckBox(Sender).Checked);
end;
procedure TFrm_CUT.chk_BeforeClick(Sender: TObject);
begin
if bTag_Page2 then Exit;
if chk_Before.Checked then
begin
// chk_Before.Checked := True;
cxDate2_1S.Enabled := False;
cxDate2_1E.Enabled := False;
cxDate2_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 1;
cxDate2_1E.Date := cxDate2_1S.Date + 1;
//////////////////////////체크박스 연동안되도록 //////////////////////////
bTag_Page2 := True;
chk_Before_New.Checked := False;
chk_Before_Finish.Checked := False;
bTag_Page2 := False;
//////////////////////////체크박스 연동안되도록 //////////////////////////
GroupBox4.Enabled := False;
cb_st_city.Enabled := False;
cb_st_ward.Enabled := False;
cb_S_Cnt1.Text := '';
cb_S_Cnt2.Text := '';
cb_s_CCnt1.Text := '';
cb_s_CCnt2.Text := '';
cb_S_Cnt1.Enabled := False;
cb_S_Cnt2.Enabled := False;
cb_S_CCnt1.Enabled := False;
cb_S_CCnt2.Enabled := False;
cb_S_Grad.Enabled := False;
rg_SType.Enabled := False;
rrb_st_all.Checked := True;
rrb_st_comp.Checked := False;
rrb_st_cancel.Checked := False;
rrb_st_req.Checked := False;
end else
begin
// chk_Before.Checked := False;
cxDate2_1S.Enabled := True;
cxDate2_1E.Enabled := True;
cxDate2_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 1;
cxDate2_1E.Date := cxDate2_1S.Date + 1;
//////////////////////////체크박스 연동안되도록 //////////////////////////
bTag_Page2 := True;
chk_Before_New.Checked := False;
chk_Before_Finish.Checked := False;
bTag_Page2 := False;
//////////////////////////체크박스 연동안되도록 //////////////////////////
GroupBox4.Enabled := True;
cb_st_city.Enabled := True;
cb_st_ward.Enabled := True;
cb_S_Cnt1.Text := '';
cb_S_Cnt2.Text := '';
cb_s_CCnt1.Text := '';
cb_s_CCnt2.Text := '';
cb_S_Cnt1.Enabled := True;
cb_S_Cnt2.Enabled := True;
cb_S_CCnt1.Enabled := True;
cb_S_CCnt2.Enabled := True;
cb_S_Grad.Enabled := True;
rg_SType.Enabled := True;
rrb_st_all.Checked := True;
rrb_st_comp.Checked := False;
rrb_st_cancel.Checked := False;
rrb_st_req.Checked := False;
cbGubun2_1.ItemIndex := 0;
if rbUseList01.Checked then
begin
cb_st_city.Enabled := True;
cb_st_ward.Enabled := True;
cb_S_Cnt1.Enabled := False;
cb_S_Cnt2.Enabled := False;
cb_S_CCnt1.Enabled := False;
cb_S_CCnt2.Enabled := False;
cb_S_Grad.Enabled := False;
GroupBox4.Enabled := True;
rrb_st_all.Checked := True;
end else
begin
cb_st_city.Enabled := False;
cb_st_ward.Enabled := False;
cbKeynumber02.ItemIndex := 0;
cbGubun2_1.ItemIndex := 0;
cb_Sms_Gubun.ItemIndex := 0;
cb_S_Grad.ItemIndex := 0;
cb_Sms_Gubun.Enabled := True;
cb_S_Cnt1.Enabled := True;
cb_S_Cnt2.Enabled := True;
cb_S_CCnt1.Enabled := True;
cb_S_CCnt2.Enabled := True;
cb_S_Grad.Enabled := True;
GroupBox4.Enabled := False;
rrb_st_all.Checked := True;
rrb_st_comp.Checked := False;
rrb_st_cancel.Checked := False;
rrb_st_req.Checked := False;
end;
end;
end;
procedure TFrm_CUT.chk_Before_NewClick(Sender: TObject);
begin
if bTag_Page2 then exit;
if chk_Before_New.Checked then
begin
// chk_Before_New.Checked := True;
cxDate2_1S.Enabled := False;
cxDate2_1E.Enabled := False;
cxDate2_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 1;
cxDate2_1E.Date := cxDate2_1S.Date + 1;
//////////////////////////체크박스 연동안되도록 //////////////////////////
bTag_Page2 := True;
chk_Before.Checked := False;
chk_Before_Finish.Checked := False;
bTag_Page2 := False;
//////////////////////////체크박스 연동안되도록 //////////////////////////
GroupBox4.Enabled := False;
cb_st_city.Enabled := False;
cb_st_ward.Enabled := False;
cb_S_Cnt1.Text := '';
cb_S_Cnt2.Text := '';
cb_s_CCnt1.Text := '';
cb_s_CCnt2.Text := '';
cb_S_Cnt1.Enabled := False;
cb_S_Cnt2.Enabled := False;
cb_S_CCnt1.Enabled := False;
cb_S_CCnt2.Enabled := False;
cb_S_Grad.Enabled := False;
rg_SType.Enabled := False;
rrb_st_all.Checked := True;
rrb_st_comp.Checked := False;
rrb_st_cancel.Checked := False;
rrb_st_req.Checked := False;
end else
begin
// chk_Before_New.Checked := False;
cxDate2_1S.Enabled := True;
cxDate2_1E.Enabled := True;
cxDate2_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 1;
cxDate2_1E.Date := cxDate2_1S.Date + 1;
//////////////////////////체크박스 연동안되도록 //////////////////////////
bTag_Page2 := True;
chk_Before.Checked := False;
chk_Before_Finish.Checked := False;
bTag_Page2 := False;
//////////////////////////체크박스 연동안되도록 //////////////////////////
GroupBox4.Enabled := True;
cb_st_city.Enabled := True;
cb_st_ward.Enabled := True;
cb_S_Cnt1.Text := '';
cb_S_Cnt2.Text := '';
cb_s_CCnt1.Text := '';
cb_s_CCnt2.Text := '';
cb_S_Cnt1.Enabled := True;
cb_S_Cnt2.Enabled := True;
cb_S_CCnt1.Enabled := True;
cb_S_CCnt2.Enabled := True;
cb_S_Grad.Enabled := True;
rg_SType.Enabled := True;
rrb_st_all.Checked := True;
rrb_st_comp.Checked := False;
rrb_st_cancel.Checked := False;
rrb_st_req.Checked := False;
cbGubun2_1.ItemIndex := 0;
if rbUseList01.Checked then
begin
cb_st_city.Enabled := True;
cb_st_ward.Enabled := True;
cb_S_Cnt1.Enabled := False;
cb_S_Cnt2.Enabled := False;
cb_S_CCnt1.Enabled := False;
cb_S_CCnt2.Enabled := False;
cb_S_Grad.Enabled := False;
GroupBox4.Enabled := True;
rrb_st_all.Checked := True;
end else
begin
cb_st_city.Enabled := False;
cb_st_ward.Enabled := False;
cbKeynumber02.ItemIndex := 0;
cbGubun2_1.ItemIndex := 0;
cb_Sms_Gubun.ItemIndex := 0;
cb_S_Grad.ItemIndex := 0;
cb_Sms_Gubun.Enabled := True;
cb_S_Cnt1.Enabled := True;
cb_S_Cnt2.Enabled := True;
cb_S_CCnt1.Enabled := True;
cb_S_CCnt2.Enabled := True;
cb_S_Grad.Enabled := True;
GroupBox4.Enabled := False;
rrb_st_all.Checked := True;
rrb_st_comp.Checked := False;
rrb_st_cancel.Checked := False;
rrb_st_req.Checked := False;
end;
end;
end;
procedure TFrm_CUT.CustSetDateControl(AGubun: Integer; AStDt, AEdDt: TcxDateEdit);
begin
case AGubun of
0: //오늘
begin
AStDt.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
AEdDt.Date := AStDt.Date + 1;
end;
1: //어제
begin
AStDt.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 1;
AEdDt.Date := AStDt.Date + 1;
end;
2: //최근일주일
begin
AStDt.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 7;
AEdDt.Date := AStDt.Date + 7;
end;
3: //1~31일
begin
AStDt.Date := StartOfTheMonth(now);
AEdDt.Date := EndOfTheMonth(Now);
end;
11: //최근한달
begin
AStDt.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 31;
AEdDt.Date := AStDt.Date + 31;
end;
12: //3개월
begin
AStDt.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 91;
AEdDt.Date := AStDt.Date + 91;
end;
13: //6개월
begin
AStDt.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 181;
AEdDt.Date := AStDt.Date + 181;
end;
14: //1년
begin
AStDt.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 365;
AEdDt.Date := AStDt.Date + 365;
end;
end;
end;
procedure TFrm_CUT.CustView1CellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
var
iBrNo, iKeyNum, iSeq, iRow: Integer;
sBrNo, sKeyNum, sSeq: string;
begin
// 권한 적용 (지호 2008-08-19)
if TCK_USER_PER.COM_CustModify <> '1' then
begin
GMessagebox('고객 수정권한이 없습니다.', CDMSE);
Exit;
end;
iRow := CustView1.DataController.FocusedRecordIndex;
if iRow = -1 then
Exit;
iBrNo := CustView1.GetColumnByFieldName('지사코드').Index;
iKeyNum := CustView1.GetColumnByFieldName('대표번호').Index;
iSeq := CustView1.GetColumnByFieldName('SEQ').Index;
sBrNo := CustView1.DataController.Values[iRow, iBrNo];
sKeyNum := CustView1.DataController.Values[iRow, iKeyNum];
sKeyNum := StringReplace(sKeyNum, '-', '', [rfReplaceAll]);
sSeq := CustView1.DataController.Values[iRow, iSeq];
// 6 : 수정창에서 고객수정 4 : 접수창에서 고객수정
if ( Not Assigned(Frm_CUT011) ) Or ( Frm_CUT011 = Nil ) then Frm_CUT011 := TFrm_CUT011.Create(Self);
Frm_CUT011.FControlInitial(False);
Frm_CUT011.Tag := 6;
Frm_CUT011.Hint := IntToStr(Self.Tag);
Frm_CUT011.clbCuSeq.Caption := sSeq;
Frm_CUT011.proc_search_brKeyNum(sBrNo, sKeyNum);
// Frm_CUT011.Left := (Screen.Width - Frm_CUT011.Width) div 2;
// Frm_CUT011.top := (Screen.Height - Frm_CUT011.Height) div 2;
// if Frm_CUT011.top <= 10 then Frm_CUT011.top := 10;
Frm_CUT011.Show;
Frm_CUT011.proc_cust_Intit;
end;
procedure TFrm_CUT.CustView1ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
begin
AIndex := AColumn.Index;
end;
procedure TFrm_CUT.CustView1ColumnPosChanged(Sender: TcxGridTableView; AColumn: TcxGridColumn);
begin
proc_CustCounsel_Save;
end;
procedure TFrm_CUT.CustView1DataControllerSortingChanged(Sender: TObject);
begin
gfSetIndexNo(CustView1, AIndex, GS_SortNoChange);
end;
procedure TFrm_CUT.CustView1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (ssCtrl in Shift) and ((Key = Ord('c')) or (Key = Ord('C')) or (Key = VK_INSERT)) then
begin
ShowMessage('고객 정보를 복사 할 수 없습니다.');
Key := 0;
end;
if Key = VK_CONTROL then
begin
gbControlKeyDown := True;
CustView1.OptionsSelection.CellMultiSelect := False;
CustView1.OptionsSelection.CellSelect := False;
CustView1.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.CustView1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_CONTROL then
begin
gbControlKeyDown := False;
end;
end;
procedure TFrm_CUT.CustView1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (gbControlKeyDown = False) and (Button = mbLeft) then
begin
CustView1.OptionsSelection.CellMultiSelect := True;
CustView1.OptionsSelection.CellSelect := True;
CustView1.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.CustView1StylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; var AStyle: TcxStyle);
var
iCU_tel1, iCU_tel2, iCU_tel3, iCU_SMS1, iCU_SMS2, iCU_SMS3, iRow : Integer;
sCU_SMS1, sCU_SMS2, sCU_SMS3 : string;
begin
iCU_tel1 := CustView1.GetColumnByFieldName('고객번호').Index;
iCU_tel2 := CustView1.GetColumnByFieldName('고객번호2').Index;
iCU_tel3 := CustView1.GetColumnByFieldName('고객번호3').Index;
iCU_SMS1 := CustView1.GetColumnByFieldName('SMS수신거부').Index;
iCU_SMS2 := CustView1.GetColumnByFieldName('SMS수신거부2').Index;
iCU_SMS3 := CustView1.GetColumnByFieldName('SMS수신거부3').Index;
iRow := CustView1.DataController.GetRowInfo(ARecord.Index).RecordIndex;
sCU_SMS1 := ''; sCU_SMS2 := ''; sCU_SMS3 := '';
sCU_SMS1 := CustView1.DataController.Values[iRow, iCU_SMS1];
sCU_SMS2 := CustView1.DataController.Values[iRow, iCU_SMS2];
sCU_SMS3 := CustView1.DataController.Values[iRow, iCU_SMS3];
if (AItem.Index = iCU_tel1) and (sCU_SMS1 = '수신') then
begin
AStyle := Frm_Main.cxStyle2;
end;
if (AItem.Index = iCU_tel2) and (sCU_SMS2 = 'y') then
begin
AStyle := Frm_Main.cxStyle2;
end;
if (AItem.Index = iCU_tel3) and (sCU_SMS3 = 'y') then
begin
AStyle := Frm_Main.cxStyle2;
end;
end;
procedure TFrm_CUT.CustView2KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (ssCtrl in Shift) and ((Key = Ord('c')) or (Key = Ord('C'))) then
begin
ShowMessage('고객 정보를 복사 할 수 없습니다.');
Key := 0;
end;
if Key = VK_CONTROL then
begin
gbControlKeyDown := True;
CustView2.OptionsSelection.CellMultiSelect := False;
CustView2.OptionsSelection.CellSelect := False;
CustView2.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.CustView2KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_CONTROL then
begin
gbControlKeyDown := False;
end;
end;
procedure TFrm_CUT.CustView2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (gbControlKeyDown = False) and (Button = mbLeft) then
begin
CustView2.OptionsSelection.CellMultiSelect := True;
CustView2.OptionsSelection.CellSelect := True;
CustView2.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.CustView3ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
begin
AIndex := AColumn.Index;
end;
procedure TFrm_CUT.CustView3KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (ssCtrl in Shift) and ((Key = Ord('c')) or (Key = Ord('C'))) then
begin
ShowMessage('고객 정보를 복사 할 수 없습니다.');
Key := 0;
end;
if Key = VK_CONTROL then
begin
gbControlKeyDown := True;
CustView3.OptionsSelection.CellMultiSelect := False;
CustView3.OptionsSelection.CellSelect := False;
CustView3.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.CustView3MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (gbControlKeyDown = False) and (Button = mbLeft) then
begin
CustView3.OptionsSelection.CellMultiSelect := True;
CustView3.OptionsSelection.CellSelect := True;
CustView3.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.CustView6ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
begin
AIndex := AColumn.Index;
end;
procedure TFrm_CUT.CustView6KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (ssCtrl in Shift) and ((Key = Ord('c')) or (Key = Ord('C'))) then
begin
ShowMessage('고객 정보를 복사 할 수 없습니다.');
Key := 0;
end;
if Key = VK_CONTROL then
begin
gbControlKeyDown := True;
CustView6.OptionsSelection.CellMultiSelect := False;
CustView6.OptionsSelection.CellSelect := False;
CustView6.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.CustView6MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (gbControlKeyDown = False) and (Button = mbLeft) then
begin
CustView6.OptionsSelection.CellMultiSelect := True;
CustView6.OptionsSelection.CellSelect := True;
CustView6.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.CustView9CellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
var
iRow: Integer;
sBrNo, sSeq, sHdno, sType, sName, sBrName,
sTel, sInfo, sTotalMlg, sCurMlg, sBrMlg, sCnt, sPrize: string;
begin
iRow := CustView9.DataController.FocusedRecordIndex;
if iRow = -1 then
Exit;
sBrNo := CustView9.DataController.Values[iRow, 2];
sBrName := CustView9.DataController.Values[iRow, 3];
sSeq := CustView9.DataController.Values[iRow, 1];
sHdno := frm_Main.func_search_hdNo(sBrNo);
sType := CustView9.DataController.Values[iRow, 5];
sName := CustView9.DataController.Values[iRow, 6];
sTel := CustView9.DataController.Values[iRow, 7];
sInfo := CustView9.DataController.Values[iRow, 12];
sTotalMlg := CustView9.DataController.Values[iRow, 8];
sCurMlg := CustView9.DataController.Values[iRow, 9];
sCnt := CustView9.DataController.Values[iRow, 10];
sBrMlg := CustView9.DataController.Values[iRow, 15];
sPrize := CustView9.DataController.Values[iRow, 16];
if ( Not Assigned(Frm_CUT07) ) Or ( Frm_CUT07 = NIl ) then Frm_CUT07 := TFrm_CUT07.Create(Nil);
Frm_CUT07.cxlbBrNo.Caption := sBrNo;
Frm_CUT07.cxlbCode.Caption := sSeq;
Frm_CUT07.cxLabel14.Caption := sHdno;
Frm_CUT07.cxTextEdit4.Text := sBrName;
Frm_CUT07.cxedEdit1.Text := sType;
Frm_CUT07.cxTextEdit1.Text := sName;
Frm_CUT07.cxTextEdit2.Text := sTel;
Frm_CUT07.cxmmMemo.Text := sInfo;
Frm_CUT07.edMileage01.Text := sTotalMlg;
Frm_CUT07.cxCurrencyEdit1.Text := sCurMlg;
Frm_CUT07.cxCurrencyEdit2.Text := sBrMlg;
Frm_CUT07.cxCurrencyEdit3.Text := sCnt;
Frm_CUT07.cxCurrencyEdit4.Text := '0';
Frm_CUT07.cxCurrencyEdit5.Text := sBrMlg;
Frm_CUT07.cxTextEdit3.Text := sPrize;
Frm_CUT07.Show;
end;
procedure TFrm_CUT.CustView9ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
begin
AIndex := AColumn.Index;
end;
procedure TFrm_CUT.CustView9KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_CONTROL then
begin
gbControlKeyDown := True;
CustView9.OptionsSelection.CellMultiSelect := False;
CustView9.OptionsSelection.CellSelect := False;
CustView9.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.CustView9MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (gbControlKeyDown = False) and (Button = mbLeft) then
begin
CustView9.OptionsSelection.CellMultiSelect := True;
CustView9.OptionsSelection.CellSelect := True;
CustView9.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.CustView10ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
begin
AIndex := AColumn.Index;
end;
procedure TFrm_CUT.CustView10KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_CONTROL then
begin
gbControlKeyDown := True;
CustView10.OptionsSelection.CellMultiSelect := False;
CustView10.OptionsSelection.CellSelect := False;
CustView10.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.CustView10MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (gbControlKeyDown = False) and (Button = mbLeft) then
begin
CustView10.OptionsSelection.CellMultiSelect := True;
CustView10.OptionsSelection.CellSelect := True;
CustView10.OptionsSelection.MultiSelect := True;
end;
end;
procedure TFrm_CUT.btn_2_2Click(Sender: TObject);
begin
if (GT_SEL_BRNO.GUBUN = '0') and (not Check_ALLHD(GT_SEL_BRNO.HDNO)) then
begin
GMessagebox('해당본사에 대한 전체 권한이 없습니다.' + #13#10 + '지사를 선택하여 주십시오.', CDMSE);
Exit;
end;
if not chkCust02Type04.Checked then
CustView2.DataController.SetRecordCount(0);
proc_GeneralSearch;
end;
procedure TFrm_CUT.btn_2_1Click(Sender: TObject);
var
ls_TxQry, ls_TxLoad, sQueryTemp : string;
sBrNo: string;
sWhere: string;
slReceive: TStringList;
ErrCode: integer;
begin
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) > 2100)
or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
DoubleBuffered := True;
sBrNo := cxBrNo2.Text;
if sBrNo <> '' then
sWhere := ' AND B.HD_NO = ''' + cxHdNo2.Text + ''' AND B.BR_NO = ''' +
sBrNo + ''' '
else
sWhere := ' AND B.HD_NO = ''' + cxHdNo2.Text + ''' ';
ls_TxLoad := GTx_UnitXmlLoad('SEL02.XML');
fGet_BlowFish_Query(GSQ_BRANCH_SMS2, sQueryTemp);
ls_TxQry := Format(sQueryTemp, [sWhere]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', GT_USERIF.ID, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', Self.Caption + '5', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'PagingString', '20000', [rfReplaceAll]);
lbNoSms.Clear;
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
end;
procedure TFrm_CUT.btn_2_5Click(Sender: TObject);
begin
proc_SND_SMS(CustView2);
end;
procedure TFrm_CUT.btn_2_4Click(Sender: TObject);
begin
if CustView2.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSE);
Exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
ShowMessage('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
if (TCK_USER_PER.COM_CustExcelDown <> '1') then
begin
ShowMessage('[조회고객엑셀다운] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
grpExcel_OPT.Left := (Width - grpExcel_OPT.Width) div 2;
grpExcel_OPT.top := (Height - grpExcel_OPT.Height) div 2;
grpExcel_OPT.Visible := True;
grpExcel_OPT.BringToFront;
end;
procedure TFrm_CUT.btn_3_1Click(Sender: TObject);
var
ls_TxQry, ls_TxLoad, sQueryTemp: string;
sBrNo: string;
sWhere: string;
slReceive: TStringList;
ErrCode: integer;
begin
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) > 2100)
or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
//////////////////////////////////////////////////////////////////////////////
// 고객>고급검색]2000건/콜센터(통합)/지사별수신거부고객전체검색
FExcelDownHigh := Format('%s/지사별 수신거부고객 전체검색', [GetSelBrInfo]);
//////////////////////////////////////////////////////////////////////////////
DoubleBuffered := True;
sBrNo := cxBrNo3.Text;
if sBrNo <> '' then
sWhere := ' AND B.HD_NO = ''' + cxHdNo3.Text + ''' AND B.BR_NO = ''' + sBrNo + ''' '
else
sWhere := ' AND B.HD_NO = ''' + cxHdNo3.Text + ''' ';
ls_TxLoad := GTx_UnitXmlLoad('SEL02.XML');
fGet_BlowFish_Query(GSQ_BRANCH_SMS2, sQueryTemp);
ls_TxQry := Format(sQueryTemp, [sWhere]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', GT_USERIF.ID, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', Self.Caption + '5', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'PagingString', '20000', [rfReplaceAll]);
lbNoSms.Clear;
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
end;
procedure TFrm_CUT.btn_3_2Click(Sender: TObject);
begin
if (GT_SEL_BRNO.GUBUN = '0') and (not Check_ALLHD(GT_SEL_BRNO.HDNO)) then
begin
GMessagebox('해당본사에 대한 전체 권한이 없습니다.' + #13#10 + '지사를 선택하여 주십시오.', CDMSE);
Exit;
end;
if not chkCust03Type04.Checked then
CustView3.DataController.SetRecordCount(0);
proc_HighSearch;
end;
procedure TFrm_CUT.btn_3_4Click(Sender: TObject);
begin
if CustView3.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSE);
Exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
ShowMessage('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
if (TCK_USER_PER.COM_CustExcelDown <> '1') then
begin
ShowMessage('[조회고객엑셀다운] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
grpExcel_OPT.Left := (Width - grpExcel_OPT.Width) div 2;
grpExcel_OPT.top := (Height - grpExcel_OPT.Height) div 2;
grpExcel_OPT.Visible := True;
grpExcel_OPT.BringToFront;
end;
procedure TFrm_CUT.btn_3_5Click(Sender: TObject);
begin
proc_SND_SMS(CustView3, chkCust03Type06.Checked);
end;
procedure TFrm_CUT.btn_4_3Click(Sender: TObject);
begin
if (GT_SEL_BRNO.GUBUN = '0') and (not Check_ALLHD(GT_SEL_BRNO.HDNO)) then
begin
GMessagebox('해당본사에 대한 전체 권한이 없습니다.' + #13#10 + '지사를 선택하여 주십시오.', CDMSE);
Exit;
end;
if not chkCust04Type08.Checked then
CustView4.DataController.SetRecordCount(0);
proc_DetailSearch;
end;
procedure TFrm_CUT.btn_4_5Click(Sender: TObject);
begin
if CustView4.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSE);
Exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
ShowMessage('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
if (TCK_USER_PER.COM_CustExcelDown <> '1') then
begin
ShowMessage('[조회고객엑셀다운] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
grpExcel_OPT.Left := (Width - grpExcel_OPT.Width) div 2;
grpExcel_OPT.top := (Height - grpExcel_OPT.Height) div 2;
grpExcel_OPT.Visible := True;
grpExcel_OPT.BringToFront;
end;
procedure TFrm_CUT.btn_4_6Click(Sender: TObject);
begin
proc_SND_SMS(CustView4, chkCust03Type06.Checked);
end;
procedure TFrm_CUT.btn_6_6Click(Sender: TObject);
begin
if (GT_SEL_BRNO.GUBUN = '0') and (not Check_ALLHD(GT_SEL_BRNO.HDNO)) then
begin
GMessagebox('해당본사에 대한 전체 권한이 없습니다.' + #13#10 + '지사를 선택하여 주십시오.', CDMSE);
Exit;
end;
if not chkCust06Type03.Checked then
CustView6.DataController.SetRecordCount(0);
proc_SleepSearch;
end;
procedure TFrm_CUT.btn_6_1Click(Sender: TObject);
begin
cxDate6_1.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - StrToIntDef(TcxButton(Sender).Caption, 1);
end;
procedure TFrm_CUT.btn_6_9Click(Sender: TObject);
begin
proc_SND_SMS(CustView6, chkCust06Type05.Checked);
end;
procedure TFrm_CUT.btn_7_1Click(Sender: TObject);
begin
RequestDataCustLevel;
end;
procedure TFrm_CUT.btn_7_2Click(Sender: TObject);
begin
ShowCustLevelWindow('', '', False);
end;
procedure TFrm_CUT.btn_7_3Click(Sender: TObject);
var
Row: Integer;
GroupName, GroupSeq: string;
begin
Row := cxViewCustGroup.DataController.FocusedRecordIndex;
if Row < 0 then
begin
GMessageBox('그룹을 선택해 주세요.', CDMSE);
Exit;
end;
GroupName := cxViewCustGroup.DataController.Values[Row, cxColCGGroupName.Index];
GroupName := Copy(GroupName, Pos(']', GroupName) + 1, Length(GroupName));
GroupSeq := cxViewCustGroup.DataController.Values[Row, cxColCGGroupSeq.Index];
if Application.MessageBox(PChar(Format('[%s]그룹을 삭제할까요?', [GroupName])), CDMSI, MB_YESNO +
MB_ICONQUESTION + MB_DEFBUTTON2) = IDYES then
begin
DelCustGroup(GroupSeq);
end;
end;
procedure TFrm_CUT.btn_7_4Click(Sender: TObject);
var
Row: Integer;
GroupName,
GroupSeq: string;
bOneYear : Boolean;
begin
Row := cxViewCustGroup.DataController.FocusedRecordIndex;
if Row < 0 then
begin
GMessageBox('등급 추가할 그룹을 선택해 주세요.', CDMSE);
Exit;
end;
bOneYear := False;
GroupName := cxViewCustGroup.DataController.Values[Row, cxColCGGroupName.Index];
GroupName := Copy(GroupName, Pos(']', GroupName) + 1, Length(GroupName));
if Pos('[최근 1년 유지]', GroupName) > 0 then
begin
GroupName := StringReplace(GroupName, ' [최근 1년 유지]', '', [rfReplaceAll]);
bOneYear := True;
end;
GroupSeq := cxViewCustGroup.DataController.Values[Row, cxColCGGroupSeq.Index];
ShowCustLevelWindow(GroupName, GroupSeq, bOneYear);
end;
procedure TFrm_CUT.btn_7_5Click(Sender: TObject);
var
Row: Integer;
GroupName, LevelName, LevelSeq: string;
begin
Row := cxViewCustGroup.DataController.FocusedRecordIndex;
if Row < 0 then
begin
GMessageBox('삭제하실 등급을 선택해 주세요.', CDMSE);
Exit;
end;
GroupName := cxViewCustGroup.DataController.Values[Row, cxColCGGroupName.Index];
LevelName := cxViewCustGroup.DataController.Values[Row, cxColCGLevelName.Index];
LevelSeq := cxViewCustGroup.DataController.Values[Row, cxColCGLevelSeq.Index];
if Application.MessageBox(PChar(Format('[%s>%s]등급을 삭제할까요?', [GroupName, LevelName])), CDMSI, MB_YESNO +
MB_ICONQUESTION + MB_DEFBUTTON2) = IDYES then
begin
DelCustLevel(LevelSeq);
end;
end;
procedure TFrm_CUT.btn_8_1Click(Sender: TObject);
begin
proc_MileageSet;
end;
procedure TFrm_CUT.btn_8_2Click(Sender: TObject);
var
sTemp, XmlData, ErrMsg: string;
i, ErrCode: integer;
asParam: array[1..41] of string;
begin
asParam[1] := cxBrNo8.Text; //지사코드
if asParam[1] = '' then
begin
GMessagebox('마일리지 설정은 지사를 선택하셔야 합니다.', CDMSE);
Exit; // [hjf]
end;
if (cxCheckBox3.checked) and (cxCurrencyEdit6.Value < 1) then
begin
GMessagebox('후불(마일)+후불(카드) 사용시 입력값은 1이상이어야 합니다. ', CDMSE);
cxCurrencyEdit6.SetFocus;
Exit;
end;
if (cxCheckBox3.checked) and (cxCurrencyEdit6.Value > 100) and (rb_Declining.checked) then
begin
GMessagebox('후불(마일)+후불(카드) 정률 사용시 100%를 넘을 수 없습니다.', CDMSE);
cxCurrencyEdit6.SetFocus;
Exit;
end;
if Not func_EucKr_Check(cxTextEdit3, 0) then Exit;
if Not func_EucKr_Check(cxTextEdit6, 0) then Exit;
if Not func_EucKr_Check(cxTextEdit9, 0) then Exit;
if cxRadioButton10.Checked then asParam[2] := '0' else //개인-마일리지부여
if cxRadioButton11.Checked then asParam[2] := '1' else
if cxRadioButton12.Checked then asParam[2] := '2';
asParam[3] := StringReplace(cxTextEdit1.Text, ',', '', [rfReplaceAll]); //개인-마일리지부여 금액
asParam[4] := StringReplace(cxTextEdit2.Text, ',', '', [rfReplaceAll]); //개인-지사단위설정금액
asParam[5] := cxTextEdit3.Text; //개인-지급상품
if cxRadioButton13.Checked then asParam[6] := '0' else //업소-마일리지부여
if cxRadioButton14.Checked then asParam[6] := '1' else
if cxRadioButton15.Checked then asParam[6] := '2';
asParam[7] := StringReplace(cxTextEdit4.Text, ',', '', [rfReplaceAll]); //업소-마일리지부여 금액
asParam[8] := StringReplace(cxTextEdit5.Text, ',', '', [rfReplaceAll]); //업소-지사단위설정금액
asParam[9] := cxTextEdit6.Text; //업소-지급상품
if cxRadioButton16.Checked then asParam[10] := '0' else //법인-마일리지부여
if cxRadioButton17.Checked then asParam[10] := '1' else
if cxRadioButton18.Checked then asParam[10] := '2';
asParam[11] := StringReplace(cxTextEdit7.Text, ',', '', [rfReplaceAll]); //법인-마일리지부여 금액
asParam[12] := StringReplace(cxTextEdit8.Text, ',', '', [rfReplaceAll]); //법인-지사단위설정금액
asParam[13] := cxTextEdit9.Text; //법인-지급상품
if cxRadioButton19.Checked then asParam[14] := '0' else //불량-마일리지부여
if cxRadioButton20.Checked then asParam[14] := '1' else
if cxRadioButton21.Checked then asParam[14] := '2';
asParam[15] := StringReplace(cxTextEdit10.Text, ',', '', [rfReplaceAll]); //불량-마일리지부여 금액
asParam[16] := StringReplace(cxTextEdit11.Text, ',', '', [rfReplaceAll]); //불량-지사단위설정금액
asParam[17] := cxTextEdit12.Text; //불량-지급상품
if chkCDNoMile.checked = True then asParam[18] := 'n' //"후불(카드)" 마일리지 적립 안함
else asParam[18] := 'y';
if chkLTNoMile.checked = True then asParam[19] := 'n' //"후불" 마일리지 적립안함
else asParam[19] := 'y';
if cxCheckBox5.checked = True then asParam[20] := 'y' //개인-1회완료시추가적립
else asParam[20] := 'n';
asParam[21] := StringReplace(cxCurrencyEdit1.text, ',', '', [rfReplaceAll]); //개인-1회완료시추가금액
if cxCheckBox6.checked = True then asParam[22] := 'y' //업소-1회완료시추가적립
else asParam[22] := 'n';
asParam[23] := StringReplace(cxCurrencyEdit2.text, ',', '', [rfReplaceAll]); //업소-1회완료시추가금액
if cxCheckBox7.checked = True then asParam[24] := 'y' //법인-1회완료시추가적립
else asParam[24] := 'n';
asParam[25] := StringReplace(cxCurrencyEdit3.text, ',', '', [rfReplaceAll]); //법인-1회완료시추가금액
if cxCheckBox8.checked = True then asParam[26] := 'y' //불량-1회완료시추가적립
else asParam[26] := 'n';
asParam[27] := StringReplace(cxCurrencyEdit4.text, ',', '', [rfReplaceAll]); //불량-1회완료시추가금액
if chkReceipNoMile.checked = True then asParam[28] := 'n' //"현금영수증" 발행시 마일리지 적립 안함
else asParam[28] := 'y';
asParam[29] := StringReplace(CEMiOver1.Text, ',', '', [rfReplaceAll]); //개인-오더요금
asParam[30] := StringReplace(CEMiOver2.Text, ',', '', [rfReplaceAll]); //개인-오더요금
asParam[31] := StringReplace(CEMiOver3.Text, ',', '', [rfReplaceAll]); //개인-오더요금
asParam[32] := StringReplace(CEMiOver4.Text, ',', '', [rfReplaceAll]); //개인-오더요금
if rbPEventY.checked then asParam[33] := 'y' //개인-이벤트횟수
else asParam[33] := 'n';
if rbUEventY.checked then asParam[34] := 'y' //업소-이벤트횟수
else asParam[34] := 'n';
if rbBEventY.checked then asParam[35] := 'y' //법인-이벤트횟수
else asParam[35] := 'n';
asParam[36] := 'n'; // 불량고객 사용 안함
if cxCheckBox3.checked then
begin
asParam[37] := StringReplace(cxCurrencyEdit6.Text, ',', '', [rfReplaceAll]);//"후불" + "후불(카드)" 별도 적립 사용금액
if cxCheckBox2.checked then sTemp := 'y' else sTemp := 'n'; //고객구분 별 적용 -개인
if cxCheckBox10.checked then sTemp := sTemp + 'y' else sTemp := sTemp + 'n'; //고객구분 별 적용 -업소
if cxCheckBox11.checked then sTemp := sTemp + 'y' else sTemp := sTemp + 'n'; //고객구분 별 적용 -법인
asParam[38] := sTemp; //고객구분 별 적용 -개인,업소,법인
if rb_Straight.checked then asParam[39] := '1' else //"후불" + "후불(카드)" 별도 적립 사용금액-정액/정률
if rb_Declining.checked then asParam[39] := '2' else asParam[39] := '0';
end
else
begin
asParam[37] := '0';
asParam[38] := 'nnn';
asParam[39] := '0';
end;
if chkMileSaveCash.checked then asParam[40] := 'y' else asParam[40] := 'n'; //"후불(마일)" 결제 시 현금액 마일리지 적립
if chkMileSaveMile.checked then asParam[41] := 'y' else asParam[41] := 'n'; //"후불(마일)" 결제 시 마일리지액 마일리지 적립
sTemp := '';
for i := 1 to 41 do
begin
if i = 1 then sTemp := asParam[1]
else
begin
sTemp := sTemp + '│' + asParam[i];
end;
end;
if not RequestBase(GetCallable05('SET_BRANCH_MLG', 'MNG_CUST.SET_BRANCH_MLG', sTemp), XmlData, ErrCode, ErrMsg) then
begin
GMessageBox(Format('[%d] %s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
GMessagebox('마일리지 설정이 완료 되었습니다.', CDMSI);
end;
procedure TFrm_CUT.btn_8_3Click(Sender: TObject);
begin
proc_EventCnt_Init(TcxButton(Sender).Tag);
end;
procedure TFrm_CUT.btn_9_1Click(Sender: TObject);
var
iRow, iSeq: Integer;
sSeq: string;
begin
iRow := CustView9.DataController.FocusedRecordIndex;
if iRow = -1 then Exit;
iSeq := CustView9.GetColumnByFieldName('고객코드').Index;
sSeq := CustView9.DataController.Values[iRow, iSeq];
Frm_Main.procMenuCreateActive(410, '마일리지상세(적립+지급)');
cxedCuSEQ.Text := sSeq;
// CustView9.DataController.SetRecordCount(0);
proc_MileageDetail;
end;
procedure TFrm_CUT.btn_9_2Click(Sender: TObject);
begin
if (GT_SEL_BRNO.GUBUN = '0') and (not Check_ALLHD(GT_SEL_BRNO.HDNO)) then
begin
GMessagebox('해당본사에 대한 전체 권한이 없습니다.' + #13#10 + '지사를 선택하여 주십시오.', CDMSE);
Exit;
end;
CustView9.DataController.SetRecordCount(0);
proc_MileageAcc;
end;
procedure TFrm_CUT.btn_9_3Click(Sender: TObject);
begin
if CustView9.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSE);
Exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
ShowMessage('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
if (TCK_USER_PER.COM_CustExcelDown <> '1') then
begin
ShowMessage('[조회고객엑셀다운] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
grpExcel_OPT.Left := (Width - grpExcel_OPT.Width) div 2;
grpExcel_OPT.top := (Height - grpExcel_OPT.Height) div 2;
grpExcel_OPT.Visible := True;
grpExcel_OPT.BringToFront;
end;
procedure TFrm_CUT.btn_9_4Click(Sender: TObject);
begin
proc_SND_SMS(CustView9);
end;
procedure TFrm_CUT.btn_6_7Click(Sender: TObject);
begin
DeleteCustomer(CustView6, lbCount06);
end;
procedure TFrm_CUT.btn_6_8Click(Sender: TObject);
begin
if CustView6.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSE);
Exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
ShowMessage('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
if (TCK_USER_PER.COM_CustExcelDown <> '1') then
begin
ShowMessage('[조회고객엑셀다운] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
grpExcel_OPT.Left := (Width - grpExcel_OPT.Width) div 2;
grpExcel_OPT.top := (Height - grpExcel_OPT.Height) div 2;
grpExcel_OPT.Visible := True;
grpExcel_OPT.BringToFront;
end;
procedure TFrm_CUT.btn_4_1Click(Sender: TObject);
begin
proc_bubin_init;
end;
procedure TFrm_CUT.btn_Date2_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_Date3_1Click(Sender: TObject);
begin
pm_Date.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_Date3_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_Date3_2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Pop_Ymd.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_Date4_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_Date9_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_UpsoPee_CloseClick(Sender: TObject);
begin
cxGrid1.Enabled := True;
gbUpsoPee.visible := False;
end;
procedure TFrm_CUT.btn_UpsoPee_SaveClick(Sender: TObject);
var XmlData, ErrMsg, param, sTmp : string;
ErrCode, i : Integer;
begin
Try
sTmp := cxLabel230.Caption + '개 업소의 수수료를';
if rb_Straight_Upso.checked then
sTmp := sTmp + #13#10 + rb_Straight_Upso.Caption + ' 으로 1콜완료시' + edtCalValue.text + cxLabel235.Caption else
if rb_Straight_Upso.checked then
sTmp := sTmp + #13#10 + rb_Declining_Upso.Caption + ' 으로 1콜완료시' + edtCalValue.text + cxLabel235.Caption;
sTmp := sTmp + #13#10 + #13#10 + '위와같이 일괄 설정하시겠습니까?';
if Application.MessageBox(PChar(sTmp), '', MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON1) = IDNO then
begin
exit;
end;
param := '';
if rb_Declining_Upso.Checked then Param := '2' else Param := '1';
param := Param + '│' + edtCalValue.text;
Screen.Cursor := crHourGlass;
for i := 0 to gslUpsoPeeSeq.count - 1 do
begin
Param := Param + '│' + gslUpsoPeeSeq[i];
if not RequestBase(GetCallable06('SET_BATCH_CUST_MILE', 'BIZ_CUST.SET_BATCH_CUST_MILE', param), XmlData, ErrCode, ErrMsg) then
begin
GMessagebox(Format('업소수수료 일괄 등록 시 오류가 발생하였습니다.'#13#10'[%d]%s', [ErrCode, ErrMsg]), CDMSE);
cxGrid1.Enabled := True;
exit;
end;
end;
GMessagebox('업소수수료 일괄등록이 완료되었습니다.', CDMSI);
Finally
cxGrid1.Enabled := True;
gslUpsoPeeSeq.Free;
btn_UpsoPee_Close.Click;
Screen.Cursor := crDefault;
End;
end;
procedure TFrm_CUT.btn_Date10_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_Date11_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_Date12_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Pop_Ymd.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_Date13_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_Date14_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_Date16_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := TcxButton(Sender).Tag;
end;
procedure TFrm_CUT.btn_Date1_1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := 11;
end;
procedure TFrm_CUT.btn_Date1_2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pop_Ymd.Tag := 12;
end;
procedure TFrm_CUT.btn_Date1_3MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pop_Ymd.Tag := 13;
end;
procedure TFrm_CUT.btn_Date1_4MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pop_Ymd.Tag := 14;
end;
procedure TFrm_CUT.btn_Date1_5MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := 15;
end;
procedure TFrm_CUT.btn_Date1_6MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pm_Date.Tag := 16;
end;
procedure TFrm_CUT.btn_1_4Click(Sender: TObject);
begin
if not chkSearchAdd.Checked then
CustView1.DataController.SetRecordCount(0);
proc_CustSearch(0);
Click_chk := 0;
end;
procedure TFrm_CUT.btn_4_2Click(Sender: TObject);
begin
mniDetailCustLevel.Click;
end;
procedure TFrm_CUT.btn_5_1Click(Sender: TObject);
begin
proc_Cust_PhoneSel(0);
end;
procedure TFrm_CUT.btn_5_2Click(Sender: TObject);
var iRow, iPhone, iIndex, iIndex1 : Integer;
sBrNo : string;
begin
sBrNo := cxBrNo5.Text;
if ((sBrNo <> 'B811') and (sBrNo <> 'G640') and (sBrNo <> 'B100') and (sBrNo <> 'C468')) or (GS_PRJ_AREA = 'O') then
begin
ShowMessage('안심번호 설정은 신청한 지사를 선택하셔야 합니다.' + #13#10 + #13#10
+ '문의사항은 콜마너 업무게시판에 등록해 주세요.');
Screen.Cursor := crDefault;
Exit;
end;
if (cbKeynumber05.ItemIndex < 0) or (cbKeynumber05.Text = '전체') then
begin
ShowMessage('대표번호를 선택하여 주십시오.');
Exit;
end;
if cxTextEdit19.Text = '' then
begin
ShowMessage('안심번호를 입력하신 뒤 검색하여 주십시오.');
Screen.Cursor := crDefault;
Exit;
end else
if (cxTextEdit19.Text <> '') then
begin
iRow := cxGridDBTableView1.GetColumnByFieldName('4num').Index;
iPhone := cxGridDBTableView1.GetColumnByFieldName('4Phone').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(nFocus,iRow ,cxTextEdit19.Text,True,False,True);
iIndex1 := cxGridDBTableView1.DataController.FindRecordIndexByText(nFocus,iPhone,cxTextEdit19.Text,True,False,True);
if (iIndex < 0) and (iIndex1 < 0) then
begin
ShowMessage('검색하신 4자리 번호가 없습니다.');
Exit;
end;
if (iIndex > -1) or (iIndex1 > -1) then
begin
if (iIndex <= iIndex1) then
begin
if iIndex = -1 then cxGridDBTableView1.DataController.FocusedRecordIndex := iIndex1
else cxGridDBTableView1.DataController.FocusedRecordIndex := iIndex;
cxGrid14.SetFocus;
nFocus := iIndex+1;
end else
if (iIndex > iIndex1) then
begin
if iIndex1 = -1 then cxGridDBTableView1.DataController.FocusedRecordIndex := iIndex
else cxGridDBTableView1.DataController.FocusedRecordIndex := iIndex1;
cxGrid14.SetFocus;
nFocus := iIndex1+1;
end;
end;
end;
end;
procedure TFrm_CUT.btn_5_4Click(Sender: TObject);
begin
if cxGridDBTableView1.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSE);
Exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
ShowMessage('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
if (TCK_USER_PER.COM_CustExcelDown <> '1') then
begin
ShowMessage('[조회고객엑셀다운] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
grpExcel_OPT.Left := (Width - grpExcel_OPT.Width) div 2;
grpExcel_OPT.top := (Height - grpExcel_OPT.Height) div 2;
grpExcel_OPT.Visible := True;
grpExcel_OPT.BringToFront;
end;
procedure TFrm_CUT.btn_5_5Click(Sender: TObject);
var XmlData, Param, ErrMsg: string;
ErrCode: Integer;
I, iRow, iIndex : Integer;
sVnum : AnsiString;
sType, sMsg, sBrNo : string;
begin
sBrNo := cxBrNo5.text;
if ((sBrNo <> 'B811') and (sBrNo <> 'G640') and (sBrNo <> 'B100') and (sBrNo <> 'C468')) or (GS_PRJ_AREA = 'O') then
begin
ShowMessage('안심번호 설정은 신청한 지사를 선택하셔야 합니다.' + #13#10 + #13#10
+ '문의사항은 콜마너 업무게시판에 등록해 주세요.');
Exit;
end;
if (cbKeynumber05.ItemIndex < 0) or (cbKeynumber05.Text = '전체') then
begin
ShowMessage('대표번호를 선택하여 주십시오.');
Exit;
end;
if Sender = btn_5_5 then
begin
sType := 'y';
sMsg := '등록 되었습니다.' ;
Param := cxHdNo5.Text + '│' + cxTextEdit18.Text + '│';
if not RequestBase(GetSel05('CHK_VIRTUAL_TEL', 'MNG_CUST.CHK_VIRTUAL_TEL', '10',Param), XmlData, ErrCode, ErrMsg) then
begin
ShowMessage(strtocall(cxTextEdit18.Text) + '번호는 동일 본사내 다른 지사에 안심번호가 등록되어 있습니다.');
iRow := cxGridDBTableView1.GetColumnByFieldName('고객번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow, strtocall(cxTextEdit18.Text),True,False,True);
cxGridDBTableView1.DataController.FocusedRecordIndex := iIndex;
Exit;
end;
end else
if Sender = btn_5_7 then
begin
sType := '';
sMsg := '수정 되었습니다.'
end else
if Sender = btn_5_6 then
begin
sType := 'n';
sMsg := '해제 되었습니다.'
end;
iIndex := cxVirtureList.GetColumnByFieldName('').Index;
i := 0;
for iRow := 0 to cxVirtureList.DataController.RecordCount -1 do
begin
if cxVirtureList.DataController.Values[iRow, iIndex] = True then
begin
sVnum := cxVirtureList.DataController.Values[iRow, iIndex + 1] ;
inc(i);
end;
end;
if (sType = 'y') or (sType = 'n') then //등록일때
begin
if i > 1 then
begin
ShowMessage('한개 이상의 고객번호를 선택 하셨습니다.');
Exit;
end else
if i = 0 then
begin
ShowMessage('고객번호가 선택되지 않았습니다.');
Exit;
end;
if (sType = 'y') then
begin
if cxLabel240.Caption <> '' then
begin
ShowMessage('할당된 안심번호가 있습니다.' + #13#10 + '할당된 번호를 해제해 주십시오.');
Exit;
end;
if (cxLabel250.Caption)= '' then
begin
ShowMessage('안심번호가 선택되지 않았습니다.' + #13#10 + '하단의 안심번호를 선택해 주십시오.');
Exit;
end;
end else
if (sType = 'n') then
begin
if (cxLabel250.Caption = '') and (cxLabel240.Caption = '') then
begin
ShowMessage('할당된 안심번호가 없습니다.');
Exit;
end;
cxTextEdit20.Text := '';
end;
end;
if cxLabel251.Caption = '' then
begin
ShowMessage('선택된 고객이 없습니다.' + #13#10 + '고객전화번호검색을 통하여 검색해 주십시오.');
Exit;
end;
Param := '';
Param := Param + cxLabel251.Caption + '│';
Param := Param + calltostr(sVnum) + '│';
Param := Param + cxTextEdit20.Text + '│';
Param := Param + calltostr(cxLabel250.Caption) + '│' + sType + '│';
if not RequestBase(GetCallable05('SET_VIRTUAL_TEL', 'MNG_CUST.SET_VIRTUAL_TEL', Param), XmlData, ErrCode, ErrMsg) then
begin
ShowMessage(Format('[%d] %s', [ErrCode, ErrMsg]));
Exit;
end;
ShowMessage(sMsg);
if sType = 'n' then
begin
iRow := cxGridDBTableView1.GetColumnByFieldName('안심번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow,strtocall(cxLabel250.caption),True,True,True);
if iIndex > -1 then
begin
cxGridDBTableView1.DataController.Values[iIndex,2] := '';
cxGridDBTableView1.DataController.Values[iIndex,3] := '';
cxGridDBTableView1.DataController.Values[iIndex,4] := '';
cxGridDBTableView1.DataController.Values[iIndex,5] := '';
cxGridDBTableView1.DataController.Values[iIndex,6] := '';
cxGridDBTableView1.DataController.Values[iIndex,7] := '';
cxGridDBTableView1.DataController.Values[iIndex,8] := '';
cxGridDBTableView1.DataController.Values[iIndex,10] := '';
cxGridDBTableView1.DataController.Values[iIndex,11] := '';
// cxTextEdit18.Text := '';
cxTextEdit19.Text := '';
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxLabel240.Caption := '';
cxLabel251.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
end;
end else
if sType = 'y' then
begin
iRow := cxGridDBTableView1.GetColumnByFieldName('안심번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow,strtocall(cxLabel250.caption),True,True,True);
if iIndex > -1 then
begin
cxGridDBTableView1.DataController.Values[iIndex,2] := sVnum;
cxGridDBTableView1.DataController.Values[iIndex,3] := cxLabel243.Caption;
cxGridDBTableView1.DataController.Values[iIndex,4] := cxLabel245.Caption;
cxGridDBTableView1.DataController.Values[iIndex,5] := cxLabel247.Caption;
cxGridDBTableView1.DataController.Values[iIndex,6] := cbKeynumber05.Text
+ ' - ' + scb_BranchName[ scb_BranchCode.IndexOf(cxBrNo5.Text)];
cxGridDBTableView1.DataController.Values[iIndex,7] := cxTextEdit20.Text;
cxGridDBTableView1.DataController.Values[iIndex,8] := cxLabel251.Caption;
cxGridDBTableView1.DataController.Values[iIndex,10] := cxBrNo5.Text;
cxGridDBTableView1.DataController.Values[iIndex,11] := RightStr(sVnum,4);
// cxTextEdit18.Text := '';
cxTextEdit19.Text := '';
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxLabel240.Caption := '';
cxLabel251.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
end;
end else
if sType = '' then
begin
iRow := cxGridDBTableView1.GetColumnByFieldName('고객번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow,sVnum,True,True,True);
if iIndex > -1 then
begin
cxGridDBTableView1.DataController.Values[iIndex,7] := cxTextEdit20.Text;
// cxTextEdit18.Text := '';
cxTextEdit19.Text := '';
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxLabel240.Caption := '';
cxLabel251.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
end;
end;
// cxButton63Click(nil);
cxTextEdit18.Text := '';
end;
procedure TFrm_CUT.btn_5_7Click(Sender: TObject);
var XmlData, Param, ErrMsg: string;
ErrCode: Integer;
I, iRow, iIndex : Integer;
sVnum, sType, sMsg, sBrNo : string;
begin
sBrNo := cxBrNo5.text;
if ((sBrNo <> 'B811') and (sBrNo <> 'G640') and (sBrNo <> 'B100') and (sBrNo <> 'C468')) or (GS_PRJ_AREA = 'O') then
begin
ShowMessage('안심번호 설정은 신청한 지사를 선택하셔야 합니다.' + #13#10 + #13#10
+ '문의사항은 콜마너 업무게시판에 등록해 주세요.');
Exit;
end;
if (cbKeynumber05.ItemIndex < 0) or (cbKeynumber05.Text = '전체') then
begin
ShowMessage('대표번호를 선택하여 주십시오.');
Exit;
end;
if Sender = btn_5_5 then
begin
sType := 'y';
sMsg := '등록 되었습니다.' ;
Param := cxHdNo5.Text + '│' + cxTextEdit18.Text + '│';
if not RequestBase(GetSel05('CHK_VIRTUAL_TEL', 'MNG_CUST.CHK_VIRTUAL_TEL', '10',Param), XmlData, ErrCode, ErrMsg) then
begin
ShowMessage(strtocall(cxTextEdit18.Text) + '번호는 동일 본사내 다른 지사에 안심번호가 등록되어 있습니다.');
iRow := cxGridDBTableView1.GetColumnByFieldName('고객번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow, strtocall(cxTextEdit18.Text),True,False,True);
cxGridDBTableView1.DataController.FocusedRecordIndex := iIndex;
Exit;
end;
end else
if Sender = btn_5_7 then
begin
sType := '';
sMsg := '수정 되었습니다.'
end else
if Sender = btn_5_6 then
begin
sType := 'n';
sMsg := '해제 되었습니다.'
end;
iIndex := cxVirtureList.GetColumnByFieldName('').Index;
i := 0;
for iRow := 0 to cxVirtureList.DataController.RecordCount -1 do
begin
if cxVirtureList.DataController.Values[iRow, iIndex] = True then
begin
sVnum := cxVirtureList.DataController.Values[iRow, iIndex + 1] ;
inc(i);
end;
end;
if (sType = 'y') or (sType = 'n') then //등록일때
begin
if i > 1 then
begin
ShowMessage('한개 이상의 고객번호를 선택 하셨습니다.');
Exit;
end else
if i = 0 then
begin
ShowMessage('고객번호가 선택되지 않았습니다.');
Exit;
end;
if (sType = 'y') then
begin
if cxLabel240.Caption <> '' then
begin
ShowMessage('할당된 안심번호가 있습니다.' + #13#10 + '할당된 번호를 해제해 주십시오.');
Exit;
end;
if (cxLabel250.Caption)= '' then
begin
ShowMessage('안심번호가 선택되지 않았습니다.' + #13#10 + '하단의 안심번호를 선택해 주십시오.');
Exit;
end;
end else
if (sType = 'n') then
begin
if (cxLabel250.Caption = '') and (cxLabel240.Caption = '') then
begin
ShowMessage('할당된 안심번호가 없습니다.');
Exit;
end;
cxTextEdit20.Text := '';
end;
end;
if cxLabel251.Caption = '' then
begin
ShowMessage('선택된 고객이 없습니다.' + #13#10 + '고객전화번호검색을 통하여 검색해 주십시오.');
Exit;
end;
Param := '';
Param := Param + cxLabel251.Caption + '│';
Param := Param + calltostr(sVnum) + '│';
Param := Param + cxTextEdit20.Text + '│';
Param := Param + calltostr(cxLabel250.Caption) + '│' + sType + '│';
if not RequestBase(GetCallable05('SET_VIRTUAL_TEL', 'MNG_CUST.SET_VIRTUAL_TEL', Param), XmlData, ErrCode, ErrMsg) then
begin
ShowMessage(Format('[%d] %s', [ErrCode, ErrMsg]));
Exit;
end;
ShowMessage(sMsg);
if sType = 'n' then
begin
iRow := cxGridDBTableView1.GetColumnByFieldName('안심번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow,strtocall(cxLabel250.caption),True,True,True);
if iIndex > -1 then
begin
cxGridDBTableView1.DataController.Values[iIndex,2] := '';
cxGridDBTableView1.DataController.Values[iIndex,3] := '';
cxGridDBTableView1.DataController.Values[iIndex,4] := '';
cxGridDBTableView1.DataController.Values[iIndex,5] := '';
cxGridDBTableView1.DataController.Values[iIndex,6] := '';
cxGridDBTableView1.DataController.Values[iIndex,7] := '';
cxGridDBTableView1.DataController.Values[iIndex,8] := '';
cxGridDBTableView1.DataController.Values[iIndex,10] := '';
cxGridDBTableView1.DataController.Values[iIndex,11] := '';
cxTextEdit19.Text := '';
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxLabel240.Caption := '';
cxLabel251.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
end;
end else
if sType = 'y' then
begin
iRow := cxGridDBTableView1.GetColumnByFieldName('안심번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow,strtocall(cxLabel250.caption),True,True,True);
if iIndex > -1 then
begin
cxGridDBTableView1.DataController.Values[iIndex,2] := sVnum;
cxGridDBTableView1.DataController.Values[iIndex,3] := cxLabel243.Caption;
cxGridDBTableView1.DataController.Values[iIndex,4] := cxLabel245.Caption;
cxGridDBTableView1.DataController.Values[iIndex,5] := cxLabel247.Caption;
cxGridDBTableView1.DataController.Values[iIndex,6] := cbKeynumber05.Text
+ ' - ' + scb_BranchName[ scb_BranchCode.IndexOf(cxBrNo5.Text)];
cxGridDBTableView1.DataController.Values[iIndex,7] := cxTextEdit20.Text;
cxGridDBTableView1.DataController.Values[iIndex,8] := cxLabel251.Caption;
cxGridDBTableView1.DataController.Values[iIndex,10] := cxBrNo5.Text;
cxGridDBTableView1.DataController.Values[iIndex,11] := RightStr(sVnum,4);
cxTextEdit19.Text := '';
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxLabel240.Caption := '';
cxLabel251.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
end;
end else
if sType = '' then
begin
iRow := cxGridDBTableView1.GetColumnByFieldName('고객번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow,sVnum,True,True,True);
if iIndex > -1 then
begin
cxGridDBTableView1.DataController.Values[iIndex,7] := cxTextEdit20.Text;
cxTextEdit19.Text := '';
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxLabel240.Caption := '';
cxLabel251.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
end;
end;
cxTextEdit18.Text := '';
end;
procedure TFrm_CUT.btn_5_6Click(Sender: TObject);
var XmlData, Param, ErrMsg: string;
ErrCode: Integer;
I, iRow, iIndex : Integer;
sVnum, sType, sMsg, sBrNo : string;
begin
sBrNo := cxBrNo5.text;
if ((sBrNo <> 'B811') and (sBrNo <> 'G640') and (sBrNo <> 'B100') and (sBrNo <> 'C468')) or (GS_PRJ_AREA = 'O') then
begin
ShowMessage('안심번호 설정은 신청한 지사를 선택하셔야 합니다.' + #13#10 + #13#10
+ '문의사항은 콜마너 업무게시판에 등록해 주세요.');
Exit;
end;
if (cbKeynumber05.ItemIndex < 0) or (cbKeynumber05.Text = '전체') then
begin
ShowMessage('대표번호를 선택하여 주십시오.');
Exit;
end;
if Sender = btn_5_5 then
begin
sType := 'y';
sMsg := '등록 되었습니다.' ;
Param := cxHdNo5.Text + '│' + cxTextEdit18.Text + '│';
if not RequestBase(GetSel05('CHK_VIRTUAL_TEL', 'MNG_CUST.CHK_VIRTUAL_TEL', '10',Param), XmlData, ErrCode, ErrMsg) then
begin
ShowMessage(strtocall(cxTextEdit18.Text) + '번호는 동일 본사내 다른 지사에 안심번호가 등록되어 있습니다.');
iRow := cxGridDBTableView1.GetColumnByFieldName('고객번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow, strtocall(cxTextEdit18.Text),True,False,True);
cxGridDBTableView1.DataController.FocusedRecordIndex := iIndex;
Exit;
end;
end else
if Sender = btn_5_7 then
begin
sType := '';
sMsg := '수정 되었습니다.'
end else
if Sender = btn_5_6 then
begin
sType := 'n';
sMsg := '해제 되었습니다.'
end;
iIndex := cxVirtureList.GetColumnByFieldName('').Index;
i := 0;
for iRow := 0 to cxVirtureList.DataController.RecordCount -1 do
begin
if cxVirtureList.DataController.Values[iRow, iIndex] = True then
begin
sVnum := cxVirtureList.DataController.Values[iRow, iIndex + 1] ;
inc(i);
end;
end;
if (sType = 'y') or (sType = 'n') then //등록일때
begin
if i > 1 then
begin
ShowMessage('한개 이상의 고객번호를 선택 하셨습니다.');
Exit;
end else
if i = 0 then
begin
ShowMessage('고객번호가 선택되지 않았습니다.');
Exit;
end;
if (sType = 'y') then
begin
if cxLabel240.Caption <> '' then
begin
ShowMessage('할당된 안심번호가 있습니다.' + #13#10 + '할당된 번호를 해제해 주십시오.');
Exit;
end;
if (cxLabel250.Caption)= '' then
begin
ShowMessage('안심번호가 선택되지 않았습니다.' + #13#10 + '하단의 안심번호를 선택해 주십시오.');
Exit;
end;
end else
if (sType = 'n') then
begin
if (cxLabel250.Caption = '') and (cxLabel240.Caption = '') then
begin
ShowMessage('할당된 안심번호가 없습니다.');
Exit;
end;
cxTextEdit20.Text := '';
end;
end;
if cxLabel251.Caption = '' then
begin
ShowMessage('선택된 고객이 없습니다.' + #13#10 + '고객전화번호검색을 통하여 검색해 주십시오.');
Exit;
end;
Param := '';
Param := Param + cxLabel251.Caption + '│';
Param := Param + calltostr(sVnum) + '│';
Param := Param + cxTextEdit20.Text + '│';
Param := Param + calltostr(cxLabel250.Caption) + '│' + sType + '│';
if not RequestBase(GetCallable05('SET_VIRTUAL_TEL', 'MNG_CUST.SET_VIRTUAL_TEL', Param), XmlData, ErrCode, ErrMsg) then
begin
ShowMessage(Format('[%d] %s', [ErrCode, ErrMsg]));
Exit;
end;
ShowMessage(sMsg);
if sType = 'n' then
begin
iRow := cxGridDBTableView1.GetColumnByFieldName('안심번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow,strtocall(cxLabel250.caption),True,True,True);
if iIndex > -1 then
begin
cxGridDBTableView1.DataController.Values[iIndex,2] := '';
cxGridDBTableView1.DataController.Values[iIndex,3] := '';
cxGridDBTableView1.DataController.Values[iIndex,4] := '';
cxGridDBTableView1.DataController.Values[iIndex,5] := '';
cxGridDBTableView1.DataController.Values[iIndex,6] := '';
cxGridDBTableView1.DataController.Values[iIndex,7] := '';
cxGridDBTableView1.DataController.Values[iIndex,8] := '';
cxGridDBTableView1.DataController.Values[iIndex,10] := '';
cxGridDBTableView1.DataController.Values[iIndex,11] := '';
// cxTextEdit18.Text := '';
cxTextEdit19.Text := '';
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxLabel240.Caption := '';
cxLabel251.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
end;
end else
if sType = 'y' then
begin
iRow := cxGridDBTableView1.GetColumnByFieldName('안심번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow,strtocall(cxLabel250.caption),True,True,True);
if iIndex > -1 then
begin
cxGridDBTableView1.DataController.Values[iIndex,2] := sVnum;
cxGridDBTableView1.DataController.Values[iIndex,3] := cxLabel243.Caption;
cxGridDBTableView1.DataController.Values[iIndex,4] := cxLabel245.Caption;
cxGridDBTableView1.DataController.Values[iIndex,5] := cxLabel247.Caption;
cxGridDBTableView1.DataController.Values[iIndex,6] := cbKeynumber05.Text
+ ' - ' + scb_BranchName[ scb_BranchCode.IndexOf(cxBrNo5.Text)];
cxGridDBTableView1.DataController.Values[iIndex,7] := cxTextEdit20.Text;
cxGridDBTableView1.DataController.Values[iIndex,8] := cxLabel251.Caption;
cxGridDBTableView1.DataController.Values[iIndex,10] := cxBrNo5.Text;
cxGridDBTableView1.DataController.Values[iIndex,11] := RightStr(sVnum,4);
// cxTextEdit18.Text := '';
cxTextEdit19.Text := '';
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxLabel240.Caption := '';
cxLabel251.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
end;
end else
if sType = '' then
begin
iRow := cxGridDBTableView1.GetColumnByFieldName('고객번호').Index;
iIndex := cxGridDBTableView1.DataController.FindRecordIndexByText(0,iRow,sVnum,True,True,True);
if iIndex > -1 then
begin
cxGridDBTableView1.DataController.Values[iIndex,7] := cxTextEdit20.Text;
// cxTextEdit18.Text := '';
cxTextEdit19.Text := '';
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxLabel240.Caption := '';
cxLabel251.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
end;
end;
// cxButton63Click(nil);
cxTextEdit18.Text := '';
end;
procedure TFrm_CUT.btn_5_3Click(Sender: TObject);
begin
proc_VirtureNum;
end;
procedure TFrm_CUT.btn_1_5Click(Sender: TObject);
begin
if not chkSearchAdd.Checked then
CustView1.DataController.SetRecordCount(0);
proc_CustSearch(1);
Click_chk := 1;
end;
procedure TFrm_CUT.btn_1_6Click(Sender: TObject);
begin
// 7 : 접수창에서 신규등록 4 : 수정창에서 신규등록
if ( Not Assigned(Frm_CUT011) ) Or ( Frm_CUT011 = Nil ) then Frm_CUT011 := TFrm_CUT011.Create(Self);
Frm_CUT011.Tag := 7;
Frm_CUT011.Hint := IntToStr(Self.Tag);
Frm_CUT011.clbCuSeq.Caption := '';
Frm_CUT011.FControlInitial(False);
Frm_CUT011.proc_search_brKeyNum(cxBrNo1.Text, StringReplace(cbKeynumber01.Text, '-', '', [rfReplaceAll]));
Frm_CUT011.Left := (Screen.Width - Frm_CUT011.Width) div 2;
Frm_CUT011.top := (Screen.Height - Frm_CUT011.Height) div 2;
if Frm_CUT011.top <= 10 then Frm_CUT011.top := 10;
Frm_CUT011.Show;
Frm_CUT011.proc_cust_Intit;
end;
procedure TFrm_CUT.btn_1_8Click(Sender: TObject);
begin
if CustView1.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSE);
Exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
ShowMessage('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
if (TCK_USER_PER.COM_CustExcelDown <> '1') then
begin
ShowMessage('[조회고객엑셀다운] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
grpExcel_OPT.Left := (Width - grpExcel_OPT.Width) div 2;
grpExcel_OPT.top := (Height - grpExcel_OPT.Height) div 2;
grpExcel_OPT.Visible := True;
grpExcel_OPT.BringToFront;
end;
procedure TFrm_CUT.btn_10_1Click(Sender: TObject);
begin
if (GT_SEL_BRNO.GUBUN = '0') and (not Check_ALLHD(GT_SEL_BRNO.HDNO)) then
begin
GMessagebox('해당본사에 대한 전체 권한이 없습니다.' + #13#10 + '지사를 선택하여 주십시오.', CDMSE);
Exit;
end;
cxedCuSEQ.Text := '';
CustView10.DataController.SetRecordCount(0);
proc_MileageDetail;
end;
procedure TFrm_CUT.btn_10_2Click(Sender: TObject);
begin
if CustView10.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSE);
Exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
ShowMessage('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
if (TCK_USER_PER.COM_CustExcelDown <> '1') then
begin
ShowMessage('[조회고객엑셀다운] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
grpExcel_OPT.Left := (Width - grpExcel_OPT.Width) div 2;
grpExcel_OPT.top := (Height - grpExcel_OPT.Height) div 2;
grpExcel_OPT.Visible := True;
grpExcel_OPT.BringToFront;
end;
procedure TFrm_CUT.btn_11_1Click(Sender: TObject);
begin
if (GT_SEL_BRNO.GUBUN = '0') and (not Check_ALLHD(GT_SEL_BRNO.HDNO)) then
begin
GMessagebox('해당본사에 대한 전체 권한이 없습니다.' + #13#10 + '지사를 선택하여 주십시오.', CDMSE);
Exit;
end;
proc_OKCashBack;
end;
procedure TFrm_CUT.btn_11_2Click(Sender: TObject);
begin
if cxViewOKC.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSE);
Exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
ShowMessage('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
if (TCK_USER_PER.COM_CustExcelDown <> '1') then
begin
ShowMessage('[조회고객엑셀다운] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
grpExcel_OPT.Left := (Width - grpExcel_OPT.Width) div 2;
grpExcel_OPT.top := (Height - grpExcel_OPT.Height) div 2;
grpExcel_OPT.Visible := True;
grpExcel_OPT.BringToFront;
end;
procedure TFrm_CUT.btn_12_1Click(Sender: TObject);
var
ls_TxLoad, sNode, sWhere, sTemp, sTel1, sTel2, sCbcode, strTemp: string;
ls_rxxml: WideString;
lst_Node: IXMLDOMNodeList;
lst_clon: IXMLDOMNode;
slReceive: TStringList;
XmlData, Param, ErrMsg, ls_MSG_Err : string;
ErrCode, iRow, i, j, iIdx : Integer;
xdom: msDomDocument;
lst_Result : IXMLDomNodeList;
ls_Rcrd, slList : TStringList;
sHdNo, sBrNo, sEndDate : string ;
begin
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (GT_USERIF.LV = '10') and ((GT_SEL_BRNO.GUBUN <> '1') or (GT_SEL_BRNO.BrNo <> GT_USERIF.BR)) then
begin
GMessagebox('상담원 권한은 소속 지사만 조회할수 있습니다.', CDMSE);
Exit;
end;
if fGetChk_Search_HdBrNo('추천인관리(앱)') then Exit;
Try
//////////////////////////////////////////////////////////////////////////////
// 고객>추천인관리(앱)]20000건/콜센터(통합)/대표번호:전체/등록기간:20100101~20100131/마일리지11이상/지급완료24이상
FExcelDownRCMD := Format('%s/대표번호:%s',
[
GetSelBrInfo
, cbKeynumber12.Text
]);
//////////////////////////////////////////////////////////////////////////////
Param := '';
if (GT_SEL_BRNO.GUBUN <> '1') then
begin
if (GT_USERIF.LV = '60') then
begin
if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB
sHdNo := GT_SEL_BRNO.HDNO
else
sHdNo := GT_USERIF.HD;
end else
begin
sHdNo := GT_USERIF.HD;
sBrNo := GT_USERIF.BR;
end
end else
begin
sHdNo := GT_USERIF.HD;
sBrNo := GT_SEL_BRNO.BrNo;
end;
Param := sHdNo + '│' + sBrNo; //본사, 지사코드
Param := Param + '│' + StringReplace(cbKeynumber12.Text, '-', '', [rfReplaceAll]); // 대표번호
if Trim(edCustTel12.Text) = '' then strTemp := ''
else strTemp := edCustTel12.Text;
Param := Param + '│' + strTemp; //고객전화번호
if Trim(edReCmdCode.Text) = '' then strTemp := ''
else strTemp := edReCmdCode.Text;
Param := Param + '│' + strTemp; //추천코드
slList := TStringList.Create;
Screen.Cursor := crHourGlass;
Try
if not RequestBasePaging(GetSel05('GET_LIST_CUST_RECOMMEND', 'MNG_CUST_RECOMMEND.GET_LIST_CUST_RECOMMEND', '1000', Param), slList, ErrCode, ErrMsg) then
begin
Frm_Flash.hide;
Application.ProcessMessages;
GMessagebox(Format('추천인관리(앱) 조회 중 오류발생'#13#10'[%d]%s', [ErrCode, ErrMsg]), CDMSE);
Frm_Main.Enabled := True;
Screen.Cursor := crDefault;
Exit;
end;
xdom := ComsDomDocument.Create;
try
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
cxViewRCMD.DataController.SetRecordCount(0);
cxViewRCMD_D.DataController.SetRecordCount(0);
lblRCMD.Caption := '';
Application.ProcessMessages;
cxViewRCMD.BeginUpdate;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
xmlData := slList.Strings[j];
xdom.loadXML(XmlData);
ls_MSG_Err := GetXmlErrorCode(XmlData);
if ('0000' = ls_MSG_Err) then
begin
if (0 < GetXmlRecordCount(XmlData)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
// Application.ProcessMessages;
iRow := cxViewRCMD.DataController.AppendRecord;
cxViewRCMD.DataController.Values[iRow, 0] := iRow + 1;
cxViewRCMD.DataController.Values[iRow, 1] := ls_rcrd[0];
cxViewRCMD.DataController.Values[iRow, 2] := strtocall(ls_rcrd[1]);
cxViewRCMD.DataController.Values[iRow, 3] := ls_Rcrd[2];
cxViewRCMD.DataController.Values[iRow, 4] := StrToFloatDef(ls_rcrd[3], 0);
cxViewRCMD.DataController.Values[iRow, 5] := ls_rcrd[4];
end;
finally
ls_Rcrd.Free;
end;
end else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
Screen.Cursor := crDefault;
end else
begin
Frm_Flash.hide;
Application.ProcessMessages;
GMessagebox('검색된 내용이 없습니다', CDMSE);
end;
end;
finally
cxViewRCMD.EndUpdate;
xdom := Nil;
end;
Finally
frm_Main.proc_SocketWork(True);
Screen.Cursor := crDefault;
Frm_Flash.hide;
Frm_Main.Enabled := True;
End;
except
Frm_Flash.hide;
Frm_Main.Enabled := True;
Screen.Cursor := crDefault;
End;
end;
procedure TFrm_CUT.btn_12_2Click(Sender: TObject);
begin
if cxViewRCMD.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSE);
Exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
ShowMessage('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
// if (TCK_USER_PER.COM_CustExcelDown <> '1') then
// begin
// ShowMessage('[조회고객엑셀다운] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
// Exit;
// end;
grpExcel_OPT.Left := (Width - grpExcel_OPT.Width) div 2;
grpExcel_OPT.top := (Height - grpExcel_OPT.Height) div 2;
grpExcel_OPT.Visible := True;
grpExcel_OPT.Tag := 0;
grpExcel_OPT.BringToFront;
end;
procedure TFrm_CUT.btn_12_3Click(Sender: TObject);
var
ls_TxLoad, sNode, sWhere, sTemp, sTel1, sTel2, sCbcode, strTemp: string;
ls_rxxml: WideString;
lst_Node: IXMLDOMNodeList;
lst_clon: IXMLDOMNode;
slReceive: TStringList;
XmlData, Param, ErrMsg, ls_MSG_Err : string;
ErrCode, iRow, iSel, i, j, iIdx : Integer;
xdom: msDomDocument;
lst_Result : IXMLDomNodeList;
ls_Rcrd, slList : TStringList;
sHdNo, sBrNo, sSelRmd, sSelCuSeq : string;
begin
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if fGetChk_Search_HdBrNo('추천인관리(앱)-상세') then Exit;
if TcxButton(Sender).Tag = 3 then
begin
iSel := cxViewRCMD.DataController.FocusedRecordIndex;
sSelRmd := cxViewRCMD.DataController.Values[iSel, 1];
sSelCuSeq := cxViewRCMD.DataController.Values[iSel, 5]; //추천인고객번호
end else
if TcxButton(Sender).Tag = 5 then
begin
sSelCuSeq := '0';
sSelRmd := '전체';
end;
lblRCMD.Caption := sSelRmd;
Try
//////////////////////////////////////////////////////////////////////////////
// 고객>추천인관리(앱)]20000건/콜센터(통합)/대표번호:전체/등록기간:20100101~20100131/마일리지11이상/지급완료24이상
FExcelDownRCMDD := Format('%s/대표번호:%s-추천인코드:%s',
[
GetSelBrInfo
, cbKeynumber12.Text
, sSelRmd
]);
//////////////////////////////////////////////////////////////////////////////
Param := '';
if (GT_SEL_BRNO.GUBUN <> '1') then
begin
if (GT_USERIF.LV = '60') then
begin
if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB
sHdNo := GT_SEL_BRNO.HDNO
else
sHdNo := GT_USERIF.HD;
end else
begin
sHdNo := GT_USERIF.HD;
sBrNo := GT_USERIF.BR;
end
end else
begin
sHdNo := GT_USERIF.HD;
sBrNo := GT_SEL_BRNO.BrNo;
end;
Param := sHdNo + '│' + sBrNo; //본사, 지사코드
Param := Param + '│' + StringReplace(cbKeynumber12.Text, '-', '', [rfReplaceAll]); // 대표번호
Param := Param + '│' + sSelCuSeq; //추천인고객번호
if cxRBA.Checked then
strTemp := '│'
else
strTemp := formatdatetime('yyyymmdd', cxDate12_1S.Date) + '│' + formatdatetime('yyyymmdd', cxDate12_1E.Date);
Param := Param + '│' + strTemp; //등록일자
slList := TStringList.Create;
Screen.Cursor := crHourGlass;
Try
if not RequestBasePaging(GetSel05('GET_LIST_CUST_RECOMMEND_DETAIL', 'MNG_CUST_RECOMMEND.GET_LIST_CUST_RECOMMEND_DETAIL', '1000', Param), slList, ErrCode, ErrMsg) then
begin
Frm_Flash.hide;
Application.ProcessMessages;
GMessagebox(Format('추천인관리(앱) 상세 조회 중 오류발생'#13#10'[%d]%s', [ErrCode, ErrMsg]), CDMSE);
Frm_Main.Enabled := True;
Screen.Cursor := crDefault;
Exit;
end;
xdom := ComsDomDocument.Create;
try
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
cxViewRCMD_D.DataController.SetRecordCount(0);
Application.ProcessMessages;
cxViewRCMD_D.BeginUpdate;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
xmlData := slList.Strings[j];
xdom.loadXML(XmlData);
ls_MSG_Err := GetXmlErrorCode(XmlData);
if ('0000' = ls_MSG_Err) then
begin
if (0 < GetXmlRecordCount(XmlData)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
iRow := cxViewRCMD_D.DataController.AppendRecord;
cxViewRCMD_D.DataController.Values[iRow, 0] := iRow + 1;
cxViewRCMD_D.DataController.Values[iRow, 1] := strtocall(ls_rcrd[0]);
cxViewRCMD_D.DataController.Values[iRow, 2] := ls_rcrd[1];
cxViewRCMD_D.DataController.Values[iRow, 3] := StrToFloatDef(ls_rcrd[2], 0); //이용횟수
cxViewRCMD_D.DataController.Values[iRow, 4] := StrToFloatDef(ls_rcrd[3], 0); //완료횟수
cxViewRCMD_D.DataController.Values[iRow, 5] := GetStrToDateTimeGStr(ls_Rcrd[4], 4); //소멸예정일
cxViewRCMD_D.DataController.Values[iRow, 6] := GetStrToDateTimeGStr(ls_Rcrd[5], 4); //소멸예정일
cxViewRCMD_D.DataController.Values[iRow, 7] := GetStrToDateTimeGStr(ls_Rcrd[6], 4); //소멸예정일
cxViewRCMD_D.DataController.Values[iRow, 8] := ls_rcrd[7]; //추천인코드
end;
finally
ls_Rcrd.Free;
end;
end else
begin
Application.ProcessMessages;
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
Screen.Cursor := crDefault;
end else
begin
Frm_Flash.hide;
Application.ProcessMessages;
GMessagebox('검색된 내용이 없습니다', CDMSE);
end;
end;
finally
cxViewRCMD_D.EndUpdate;
xdom := Nil;
end;
Finally
frm_Main.proc_SocketWork(True);
Screen.Cursor := crDefault;
Frm_Flash.hide;
Frm_Main.Enabled := True;
End;
except
Frm_Flash.hide;
Frm_Main.Enabled := True;
Screen.Cursor := crDefault;
End;
end;
procedure TFrm_CUT.btn_12_4Click(Sender: TObject);
begin
if cxViewRCMD_D.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSE);
Exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
ShowMessage('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
// if (TCK_USER_PER.COM_CustExcelDown <> '1') then
// begin
// ShowMessage('[조회고객엑셀다운] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
// Exit;
// end;
grpExcel_OPT.Left := (Width - grpExcel_OPT.Width) div 2;
grpExcel_OPT.top := (Height - grpExcel_OPT.Height) div 2;
grpExcel_OPT.Visible := True;
grpExcel_OPT.Tag := 1;
grpExcel_OPT.BringToFront;
end;
procedure TFrm_CUT.btn_1_1Click(Sender: TObject);
begin
proc_SND_SMS(CustView1);
end;
procedure TFrm_CUT.cxButton1Click(Sender: TObject);
var
Param, ErrMsg : string;
ErrCode : Integer;
slList : TStringList;
sHdNo, sBrNo, strTemp : string ;
begin
if (GT_SEL_BRNO.GUBUN = '0') and (not Check_ALLHD(GT_SEL_BRNO.HDNO)) then
begin
GMessagebox('해당본사에 대한 전체 권한이 없습니다.' + #13#10 + '지사를 선택하여 주십시오.', CDMSE);
Exit;
end;
if not chkCust02Type04.Checked then
CustView2.DataController.SetRecordCount(0);
if (GT_USERIF.LV = '10') and ((GT_SEL_BRNO.GUBUN <> '1') or (GT_SEL_BRNO.BrNo <> GT_USERIF.BR)) then
begin
GMessagebox('상담원 권한은 소속 지사만 조회할수 있습니다.', CDMSE);
Exit;
end;
if fGetChk_Search_HdBrNo('일반검색') then Exit;
if not chkCust02Type04.Checked then
begin
if CustView2.DataController.RecordCount > 0 then
Exit;
end;
//////////////////////////////////////////////////////////////////////////////
// 고객>일반검색]2000건/콜센터(통합)/이용내역/대표번호:16886618/기간:20100101~20100131/완료:1~10/취소:1~10/SMS전체
FExcelDownNormal := Format('%s/구분:%s/대표번호:%s/기간:%s~%s%s%s/%s',
[
GetSelBrInfo
, IfThen(rbAll01.Checked, '전체', IfThen(rbNew01.Checked, '신규등록', '이용내역'))
, cbKeynumber02.Text
, cxDate2_1S.Text, cxDate2_1E.Text
, IfThen(cb_S_Cnt1.Text + cb_S_Cnt2.Text = '', '', Format('/완료:%s~%s', [cb_S_Cnt1.Text, cb_S_Cnt2.Text]))
, IfThen(cb_S_CCnt1.Text + cb_S_CCnt2.Text = '', '', Format('/취소:%s~%s', [cb_S_CCnt1.Text, cb_S_CCnt2.Text]))
, cb_Sms_Gubun.Text
]);
//////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
// 전일이용고객
//------------------------------------------------------------------------------
if chk_Before.Checked then
proc_before_his
//------------------------------------------------------------------------------
// 전일완료고객
//------------------------------------------------------------------------------
else if chk_Before_Finish.Checked then
proc_before_comp
//------------------------------------------------------------------------------
// 전일 신규고객
//------------------------------------------------------------------------------
else if chk_Before_New.Checked then
proc_before_new
else
begin
Try
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) >
2100) or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
lb_st_customer.Clear;
sBrNo := cxBrNo2.Text;
chk_All_Select.Checked := False;
chk_All_Select.OnClick(chk_All_Select);
Param := '';
Param := IntToStr(rg_SType.Tag);
if (GT_SEL_BRNO.GUBUN <> '1') then
begin
if (GT_USERIF.LV = '60') then
begin
if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB
sHdNo := GT_SEL_BRNO.HDNO
else
sHdNo := GT_USERIF.HD;
end else
begin
sHdNo := GT_USERIF.HD;
sBrNo := GT_USERIF.BR;
end
end else
begin
sHdNo := GT_USERIF.HD;
sBrNo := GT_SEL_BRNO.BrNo;
end;
Param := Param + '│' + sHdNo + '│' + sBrNo; //본사, 지사코드
strTemp := RemoveComma(cb_S_Cnt1.Text);
Param := Param + '│' + strTemp; //완료횟수S
strTemp := RemoveComma(cb_S_Cnt2.Text);
Param := Param + '│' + strTemp; //완료횟수E
strTemp := RemoveComma(cb_S_CCnt1.Text);
Param := Param + '│' + strTemp; //취소횟수S
strTemp := RemoveComma(cb_S_CCnt2.Text);
Param := Param + '│' + strTemp; //취소횟수E
strTemp := SCboLevelSeq[cb_S_Grad.itemindex];
Param := Param + '│' + strTemp; //등급
case cb_S_Grad.ItemIndex of
1: Param := Param + '│' + '0';
2: Param := Param + '│' + '1';
3: Param := Param + '│' + '3';
end;
if cb_Sms_Gubun.ItemIndex = 1 then Param := Param + '│' + 'y' else Param := Param + '│' + 'n';
Param := Param + '│' + IntToStr(cbOutBound1.ItemIndex);
if rg_SType.Tag = 2 then
begin
if cb_Sms_Gubun.ItemIndex > 0 then
begin
if (sg_notsms_list.DataController.RecordCount > 0) and
(sg_notsms_list.DataController.Values[0, 0] <> sBrno) then
proc_NotSMS(sBrNo);
end;
end;
if (cbKeynumber02.Text <> '전체') and (cbKeynumber02.Text <> '') then
Param := Param + '│' + StringReplace(cbKeynumber02.Text, '-', '', [rfReplaceAll]) else Param := Param + '│' + '';
if (cb_st_city.Text <> '지역전체') and (cb_st_ward.ItemIndex > 0) then
Param := Param + '│' + cb_st_city.Text + '│' + cb_st_ward.Text
else if (cb_st_city.Text <> '지역전체') and (cb_st_ward.ItemIndex < 1) then
Param := Param + '│' + cb_st_city.Text + '│' + ''
else Param := Param + '│' + '' + '│' + '' ;
if cxDate2_1S.Enabled then
Param := Param + '│' + formatdatetime('yyyymmdd', cxDate2_1S.Date) + '│' + formatdatetime('yyyymmdd', cxDate2_1E.Date)
else
Param := Param + '│' + '' + '│' + '' ;
case cbGubun2_1.ItemIndex of
1: Param := Param + '│' + '0';
2: Param := Param + '│' + '1';
3: Param := Param + '│' + '3';
end;
Param := Param + '│' + edCustMemo01.Text;
Param := Param + '│' + edCustName02.Text;
Param := Param + '│' + edCustTel02.Text;
slList := TStringList.Create;
Screen.Cursor := crHourGlass;
Try
if not RequestBasePaging(GetSel06('GET_LIST_CUST_GENERAL', 'CUSTOMER.GET_LIST_CUST_GENERAL', '1000', Param), slList, ErrCode, ErrMsg) then
begin
Frm_Flash.hide;
Application.ProcessMessages;
GMessagebox(Format('고객조회-일반 조회 중 오류발생'#13#10'[%d]%s', [ErrCode, ErrMsg]), CDMSE);
Frm_Main.Enabled := True;
Screen.Cursor := crDefault;
Exit;
end;
{ xdom := ComsDomDocument.Create;
try
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
CustView2.DataController.SetRecordCount(0);
CustView2.BeginUpdate;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
xmlData := slList.Strings[j];
xdom.loadXML(XmlData);
ls_MSG_Err := GetXmlErrorCode(XmlData);
if ('0000' = ls_MSG_Err) then
begin
if (0 < GetXmlRecordCount(XmlData)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
Application.ProcessMessages;
sEndDate := ls_rcrd[10];
//----------------------------------------------------------------------------------------------
// 대표번호 길이가 8보다 큰경우만 생성
//----------------------------------------------------------------------------------------------
if (trim(ls_rcrd[1]) <> '') then
begin
iRow := CustView2.DataController.FindRecordIndexByText(0, 18 + 1, ls_rcrd[1] + ls_rcrd[3], True, True, True);
//----------------------------------------------------------------------------------------------
// 대표번호 + 고객번호가 같은게 없을때만 생성
//----------------------------------------------------------------------------------------------
if (irow < 0) then
begin
iRow := CustView2.DataController.FindRecordIndexByText(0, 14 + 1, ls_rcrd[0], True, True, True);
//----------------------------------------------------------------------------------------------
// 고객순번이 중복이면 생략
//----------------------------------------------------------------------------------------------
if iRow > 0 then
continue;
if chkNmlPhoneOut02.Checked then
begin
if not CheckHPType(ls_rcrd[3], ErrDesc) then
Continue;
end;
iRow := CustView2.DataController.AppendRecord;
CustView2.DataController.Values[iRow, 18 + 1] := ls_rcrd[1] + ls_rcrd[3];
CustView2.DataController.Values[iRow, 17 + 1] := ls_rcrd[12];
CustView2.DataController.Values[iRow, 15 + 1] := ls_rcrd[11];
CustView2.DataController.Values[iRow, 9 + 1] := ls_rcrd[13];
CustView2.DataController.Values[iRow, 10 + 1] := ls_rcrd[14];
CustView2.DataController.Values[iRow, 1 + 1] := strtocall(ls_rcrd[1]);
CustView2.DataController.Values[iRow, 2 + 1] := ls_rcrd[2];
CustView2.DataController.Values[iRow, 3 + 1] := strtocall(ls_rcrd[3]);
CustView2.DataController.Values[iRow, 4 + 1] := ls_rcrd[4];
//----------------------------------------------------------------------------------------------
// 고객등급 생성(지사별 설정값 반영)
//----------------------------------------------------------------------------------------------
iComCnt := StrToIntDef(ls_rcrd[5], 0);
iCanCnt := StrToIntDef(ls_rcrd[6], 0);
iTotal := iComcnt + iCanCnt;
if iTotal = 0 then
iCanRate := 0
else
iCanRate := Round((iCanCnt / iTotal * 100));
CustView2.DataController.Values[iRow, 5 + 1] := IntToStr(iComCnt) + '/' + IntToStr(iCanCnt);
CustView2.DataController.Values[iRow, 6 + 1] := intToStr(iCanRate) + '%';
CustView2.DataController.Values[iRow, 7 + 1] := ls_rcrd[7];
CustView2.DataController.Values[iRow, 8 + 1] := ls_rcrd[8];
CustView2.DataController.Values[iRow, 11 + 1] := ls_rcrd[15];
if Trim(sEndDate) <> '' then
CustView2.DataController.Values[iRow, 12 + 1] := copy(sEndDate, 1, 4) + '-'
+ copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView2.DataController.Values[iRow, 12 + 1] := '';
CustView2.DataController.Values[iRow, 13 + 1] := ls_rcrd[9];
CustView2.DataController.Values[iRow, 14 + 1] := ls_rcrd[0];
CustView2.DataController.Values[iRow, 15 + 1] := '';
if rg_SType.Tag in [0, 1] then
CustView2.DataController.Values[iRow, 19 + 1] := '0'
else
CustView2.DataController.Values[iRow, 19 + 1] := '1';
CustView2.DataController.Values[iRow, 20 + 1] := func_buninSearch(ls_rcrd[9], ls_rcrd[1], ls_rcrd[16]);
iIdx := scb_BranchCode.IndexOf(ls_rcrd[9]);
if iIdx >= 0 then
CustView2.DataController.Values[iRow, 1] := scb_BranchName[iIdx]
else
CustView2.DataController.Values[iRow, 1] := '';
CustView2.DataController.Values[iRow, 21 + 1] := ls_rcrd[17];
CustView2.DataController.Values[iRow, 22 + 1] := ls_rcrd[18];
end;
end;
end;
finally
ls_Rcrd.Free;
end;
end
else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
lbCount09.Caption := '총 ' + IntToStr(CustView9.DataController.RecordCount) + '명';
frm_Main.sbar_Message.Panels[4].Text := '';
Screen.Cursor := crDefault;
end
else
begin
Frm_Flash.hide;
Application.ProcessMessages;
GMessagebox('검색된 내용이 없습니다', CDMSE);
end;
end;
finally
CustView9.EndUpdate;
xdom := Nil;
end; }
Finally
frm_Main.proc_SocketWork(True);
Screen.Cursor := crDefault;
Frm_Flash.hide;
Frm_Main.Enabled := True;
End;
except
Frm_Flash.hide;
Frm_Main.Enabled := True;
Screen.Cursor := crDefault;
End;
end;
end;
procedure TFrm_CUT.btnMultiSaveClick(Sender: TObject);
function fSetValue( idx : Integer; sValue : Real ) : String;
begin
if idx = 0 then Result := '0' else
if idx = 1 then Result := FloatToStr(sValue) else
if idx = 2 then
begin
if sValue <= 100 then
Result := FormatFloat('#,###.##', sValue/100)
else
Result := '0';
end;
end;
var
i : Integer;
begin
if cxBrNo8.Text = '' then //지사코드
begin
GMessagebox('마일리지 설정은 지사를 선택하셔야 합니다.', CDMSE);
Exit;
end;
try
// 초기화
for i := 1 to 6 do
begin
FSaveData[i].mType := '';
FSaveData[i].mGubun := '';
FSaveData[i].mCash := '';
FSaveData[i].mPost := '';
FSaveData[i].mCard := '';
FSaveData[i].mMile := '';
FSaveData[i].mReceipNo := '';
FSaveData[i].mFirstAdd := '';
FSaveData[i].mOverAdd := '';
end;
FSaveData[1].mType := 'T';
FSaveData[1].mGubun := '0';
FSaveData[1].mCash := fSetValue(cbCashType0.ItemIndex, edtCashValue0.Value);
FSaveData[1].mPost := fSetValue(cbPostType0.ItemIndex, edtPostValue0.Value);
FSaveData[1].mCard := fSetValue(cbCardType0.ItemIndex, edtCardValue0.Value);
FSaveData[1].mMile := fSetValue(cbMileType0.ItemIndex, edtMileValue0.Value);
if chkReceipNoMile0.Checked then FSaveData[1].mReceipNo := 'y'
else FSaveData[1].mReceipNo := 'n';
FSaveData[1].mFirstAdd := edtFirstAdd0.EditValue;
FSaveData[1].mOverAdd := edtOverAdd0.EditValue;
FSaveData[2].mType := 'T';
FSaveData[2].mGubun := '1';
FSaveData[2].mCash := fSetValue(cbCashType1.ItemIndex, edtCashValue1.Value);
FSaveData[2].mPost := fSetValue(cbPostType1.ItemIndex, edtPostValue1.Value);
FSaveData[2].mCard := fSetValue(cbCardType1.ItemIndex, edtCardValue1.Value);
FSaveData[2].mMile := fSetValue(cbMileType1.ItemIndex, edtMileValue1.Value);
if chkReceipNoMile1.Checked then FSaveData[2].mReceipNo := 'y'
else FSaveData[2].mReceipNo := 'n';
FSaveData[2].mFirstAdd := edtFirstAdd1.EditValue;
FSaveData[2].mOverAdd := edtOverAdd1.EditValue;
FSaveData[3].mType := 'T';
FSaveData[3].mGubun := '3';
FSaveData[3].mCash := fSetValue(cbCashType3.ItemIndex, edtCashValue3.Value);
FSaveData[3].mPost := fSetValue(cbPostType3.ItemIndex, edtPostValue3.Value);
FSaveData[3].mCard := fSetValue(cbCardType3.ItemIndex, edtCardValue3.Value);
FSaveData[3].mMile := fSetValue(cbMileType3.ItemIndex, edtMileValue3.Value);
if chkReceipNoMile3.Checked then FSaveData[3].mReceipNo := 'y'
else FSaveData[3].mReceipNo := 'n';
FSaveData[3].mFirstAdd := edtFirstAdd3.EditValue;
FSaveData[3].mOverAdd := edtOverAdd3.EditValue;
FSaveData[4].mType := 'A';
FSaveData[4].mGubun := '0';
FSaveData[4].mCash := fSetValue(cbCashType0A.ItemIndex, edtCashValue0A.Value);
FSaveData[4].mPost := fSetValue(cbPostType0A.ItemIndex, edtPostValue0A.Value);
FSaveData[4].mCard := fSetValue(cbCardType0A.ItemIndex, edtCardValue0A.Value);
FSaveData[4].mMile := fSetValue(cbMileType0A.ItemIndex, edtMileValue0A.Value);
if chkReceipNoMile0A.Checked then FSaveData[4].mReceipNo := 'y'
else FSaveData[4].mReceipNo := 'n';
FSaveData[4].mFirstAdd := edtFirstAdd0A.EditValue;
FSaveData[4].mOverAdd := edtOverAdd0A.EditValue;
FSaveData[5].mType := 'A';
FSaveData[5].mGubun := '1';
FSaveData[5].mCash := fSetValue(cbCashType1A.ItemIndex, edtCashValue1A.Value);
FSaveData[5].mPost := fSetValue(cbPostType1A.ItemIndex, edtPostValue1A.Value);
FSaveData[5].mCard := fSetValue(cbCardType1A.ItemIndex, edtCardValue1A.Value);
FSaveData[5].mMile := fSetValue(cbMileType1A.ItemIndex, edtMileValue1A.Value);
if chkReceipNoMile1A.Checked then FSaveData[5].mReceipNo := 'y'
else FSaveData[5].mReceipNo := 'n';
FSaveData[5].mFirstAdd := edtFirstAdd1A.EditValue;
FSaveData[5].mOverAdd := edtOverAdd1A.EditValue;
FSaveData[6].mType := 'A';
FSaveData[6].mGubun := '3';
FSaveData[6].mCash := fSetValue(cbCashType3A.ItemIndex, edtCashValue3A.Value);
FSaveData[6].mPost := fSetValue(cbPostType3A.ItemIndex, edtPostValue3A.Value);
FSaveData[6].mCard := fSetValue(cbCardType3A.ItemIndex, edtCardValue3A.Value);
FSaveData[6].mMile := fSetValue(cbMileType3A.ItemIndex, edtMileValue3A.Value);
if chkReceipNoMile3A.Checked then FSaveData[6].mReceipNo := 'y'
else FSaveData[6].mReceipNo := 'n';
FSaveData[6].mFirstAdd := edtFirstAdd3A.EditValue;
FSaveData[6].mOverAdd := edtOverAdd3A.EditValue;
for i := 1 to 6 do
begin
if ( ( FSchData[i].mType <> FSaveData[i].mType ) Or
( FSchData[i].mGubun <> FSaveData[i].mGubun ) Or
( FSchData[i].mCash <> FSaveData[i].mCash ) Or
( FSchData[i].mPost <> FSaveData[i].mPost ) Or
( FSchData[i].mCard <> FSaveData[i].mCard ) Or
( FSchData[i].mMile <> FSaveData[i].mMile ) Or
( FSchData[i].mReceipNo <> FSaveData[i].mReceipNo ) Or
( FSchData[i].mFirstAdd <> FSaveData[i].mFirstAdd ) Or
( FSchData[i].mOverAdd <> FSaveData[i].mOverAdd ) ) then pSetMultiMileSave(FSaveData[i]);
end;
GMessagebox('마일리지 설정이 완료 되었습니다.', CDMSI);
except
end;
end;
procedure TFrm_CUT.cxCheckBox3Click(Sender: TObject);
begin
if cxCheckBox3.checked then
begin
cxCheckBox3.Tag := 0;
if (chkLTNoMile.checked) and (chkCDNoMile.checked) then
begin
cxCheckBox3.checked := False;
cxCheckBox3.Tag := 99;
end;
if cxCheckBox3.Tag = 99 then exit;
rb_Straight.Enabled := True;
rb_Declining.Enabled := True;
cxCurrencyEdit6.Enabled := True;
cxLabel190.Enabled := True;
cxCheckBox2.Enabled := True;
cxCheckBox10.Enabled := True;
cxCheckBox11.Enabled := True;
if (Not cxCheckBox2.checked) and (Not cxCheckBox10.checked) and (Not cxCheckBox11.checked) then cxCheckBox2.checked := True;
//전부 미체크 시 고객만 자동체크
end else
begin
rb_Straight.Enabled := False;
rb_Declining.Enabled := False;
cxCurrencyEdit6.Enabled := False;
cxLabel190.Enabled := False;
cxCheckBox2.Enabled := False;
cxCheckBox10.Enabled := False;
cxCheckBox11.Enabled := False;
end;
end;
procedure TFrm_CUT.cxCheckBox4Click(Sender: TObject);
begin
cxGridSelectAll(CustView1, TcxCheckBox(Sender).Checked);
end;
procedure TFrm_CUT.cxCheckBox9Click(Sender: TObject);
begin
if cxCheckBox9.checked then
begin
de_6stDate.Enabled := True;
de_6edDate.Enabled := True;
btn_Date1_1.Enabled := True;
end else
begin
de_6stDate.Enabled := False;
de_6edDate.Enabled := False;
btn_Date1_1.Enabled := False;
end;
end;
procedure TFrm_CUT.cxColCGColorStylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; var AStyle: TcxStyle);
var
Idx: Integer;
begin
Idx := Sender.DataController.GetRowInfo(ARecord.Index).RecordIndex;
AStyle := stlCustLevelColor;
AStyle.Color := Hex6ToColor(Sender.DataController.Values[Idx, AItem.Index]);
end;
procedure TFrm_CUT.cxColCGLevelNameStylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; var AStyle: TcxStyle);
var
Idx: Integer;
begin
Idx := Sender.DataController.GetRowInfo(ARecord.Index).RecordIndex;
if UpperCase(Sender.DataController.Values[Idx, cxColCGDefaultYN.Index]) <> 'Y' then
Exit;
AStyle := stlCustLevelColor;
AStyle.Color := clWhite;
AStyle.Font.Style := [fsBold];
end;
procedure TFrm_CUT.cxColGLColorStylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; var AStyle: TcxStyle);
var
Idx: Integer;
begin
Idx := Sender.DataController.GetRowInfo(ARecord.Index).RecordIndex;
if Sender.DataController.Values[Idx, AItem.Index] = Null then
Exit;
AStyle := stlCustLevelColor;
AStyle.Color := Hex6ToColor(Sender.DataController.Values[Idx, AItem.Index]);
end;
procedure TFrm_CUT.cxColGLLevelNameStylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; var AStyle: TcxStyle);
var
Idx: Integer;
begin
Idx := Sender.DataController.GetRowInfo(ARecord.Index).RecordIndex;
if Sender.DataController.Values[Idx, cxColGLDefaultYN.Index] = Null then
Exit;
if UpperCase(Sender.DataController.Values[Idx, cxColGLDefaultYN.Index]) <> 'Y' then
Exit;
AStyle := stlCustLevelColor;
AStyle.Color := clWhite;
AStyle.Font.Style := [fsBold];
end;
procedure TFrm_CUT.cxGridCopy(ASource, ATarget: TcxGridDBTableView;
AKeyIndex: Integer; AKeyValue: string);
var
I, J,
Row: Integer;
KeyData: string;
begin
if AKeyIndex < 0 then
Exit;
if Trim(AKeyValue) = '' then
Exit;
for I := 0 to ASource.DataController.RecordCount - 1 do
begin
KeyData := ASource.DataController.GetValue(I, AKeyIndex);
if Pos(AKeyValue, KeyData) > 0 then
begin
Row := ATarget.DataController.AppendRecord;
ATarget.DataController.Values[Row, 0] := Row + 1;
for J := 1 to ASource.ColumnCount - 1 do
ATarget.DataController.Values[Row, J] := ASource.DataController.GetValue(I, J);
end;
end;
end;
procedure TFrm_CUT.cxGridDBTableView1CellClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
var iRow, iIndex : integer;
begin
iRow := cxGridDBTableView1.DataController.FocusedRecordIndex;
iIndex := cxGridDBTableView1.GetColumnByFieldName('cuseq').Index;
if cxGridDBTableView1.DataController.Values[iRow, iIndex] <> '' then
begin
cxLabel251.Caption := cxGridDBTableView1.DataController.Values[iRow, iIndex] ;
iIndex := cxGridDBTableView1.GetColumnByFieldName('고객명').Index;
cxLabel243.Caption := cxGridDBTableView1.DataController.Values[iRow, iIndex] ;
iIndex := cxGridDBTableView1.GetColumnByFieldName('이용횟수').Index;
cxLabel245.Caption := cxGridDBTableView1.DataController.Values[iRow, iIndex] ;
iIndex := cxGridDBTableView1.GetColumnByFieldName('최종일자').Index;
cxLabel247.Caption := cxGridDBTableView1.DataController.Values[iRow, iIndex] ;
if cxLabel247.Caption <> '' then
cxLabel247.Caption := copy(cxLabel247.Caption, 1,4) + '-' + copy(cxLabel247.Caption, 5,2) + '-' + copy(cxLabel247.Caption, 7,2); // 최종이용일자
iIndex := cxGridDBTableView1.GetColumnByFieldName('메모').Index;
cxTextEdit20.Text := cxGridDBTableView1.DataController.Values[iRow, iIndex] ;
iIndex := cxGridDBTableView1.GetColumnByFieldName('고객번호').Index;
cxTextEdit18.Text := strtocall(cxGridDBTableView1.DataController.Values[iRow, iIndex]) ;
cxLabel250.Caption := cxGridDBTableView1.DataController.Values[iRow, 1] ;
if cxTextEdit18.Text <> '' then
begin
proc_Cust_PhoneSel(1);
cxTextEdit18.Text := '';
end;
iFlag := 2;
end else
if iFlag <> 1 then
begin
cxTextEdit18.Text := '';
cxTextEdit19.Text := '';
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxLabel240.Caption := '';
cxLabel251.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
pnl5.Visible := False;
cxTextEdit20.Enabled := True;
end else
begin
if func_ChkPhone then
cxLabel250.Caption := strtocall(cxGridDBTableView1.DataController.Values[iRow, 1]) ;
end
end;
procedure TFrm_CUT.cxGridDBTableView1CellDblClick(
Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo;
AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
begin
Exit;
end;
procedure TFrm_CUT.cxGridDBTableView1ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
begin
AIndex := AColumn.Index;
end;
procedure TFrm_CUT.cxPageControl1Change(Sender: TObject);
Var iTag : Integer;
begin
if cxPageControl1.Tag = 1 then Exit;
iTag := cxPageControl1.Pages[cxPageControl1.ActivePageIndex].Tag;
if Assigned(Frm_JON51) then
if TCK_USER_PER.BTM_MENUSCH = '1' then Frm_JON51.Menu_Use_Mark('ADD', iTag);
case cxPageControl1.ActivePageIndex of
4:
begin
cbKeynumber05.ItemIndex := 1;
cbKeynumber01Click(cbKeynumber05);
if (cxBrNo5.text = '') then//(GT_USERIF.LV = '60') or
begin
ShowMessage('안심번호 설정은 신청한 지사를 선택하셔야 합니다.' + #13#10 + #13#10
+ '문의사항은 콜마너 업무게시판에 등록해 주세요.');
Exit;
end;
proc_VirtureNum_init;
if cxGridDBTableView1.DataController.RowCount < 1 then
cxGridDBTableView1.DataController.SetRecordCount(0);
// proc_VirtureNum; // 가상번호 리스트 조회
end;
7: proc_MileageSet; // [hjf] 090223 - 마일리지 설정 화면 이동 시 지사선택이 아닌경우 메시지 표출
10: proc_branch_change;
end;
end;
procedure TFrm_CUT.cxRadioButton10Click(Sender: TObject);
begin
cxTextEdit1.Value := 0;
cxTextEdit2.Value := 0;
cxTextEdit3.Text := '';
if cxRadioButton12.Checked then cxLabel92.Caption := '%'
else cxLabel92.Caption := '원';
end;
procedure TFrm_CUT.cxRadioButton13Click(Sender: TObject);
begin
cxTextEdit4.Value := 0;
cxTextEdit5.Value := 0;
cxTextEdit6.Text := '';
if cxRadioButton15.Checked then cxLabel128.Caption := '%'
else cxLabel128.Caption := '원';
end;
procedure TFrm_CUT.cxRadioButton16Click(Sender: TObject);
begin
cxTextEdit7.Value := 0;
cxTextEdit8.Value := 0;
cxTextEdit9.Text := '';
if cxRadioButton18.Checked then
begin
cxLabel148.Caption := '%';
chkBRNoMile.Checked := False;
end else
if cxRadioButton17.Checked then
begin
cxLabel148.Caption := '원';
chkBRNoMile.Checked := False;
end else
if cxRadioButton16.Checked then
begin
cxLabel148.Caption := '원';
end;
end;
procedure TFrm_CUT.cxRadioButton19Click(Sender: TObject);
begin
cxTextEdit10.Value := 0;
cxTextEdit11.Value := 0;
cxTextEdit12.Text := '';
if cxRadioButton21.Checked then cxLabel168.Caption := '%'
else cxLabel168.Caption := '원';
end;
procedure TFrm_CUT.cxRBAClick(Sender: TObject);
begin
cxDate12_1S.Enabled := cxRBB.Checked;
cxDate12_1E.Enabled := cxRBB.Checked;
btn_Date12_1.Enabled := cxRBB.Checked;
end;
procedure TFrm_CUT.cxTextEdit17KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = vk_Return then
btn_1_4Click(nil);
end;
procedure TFrm_CUT.cxTextEdit17KeyPress(Sender: TObject; var Key: Char);
begin
if key in ['0'..'9', #13, #8, #22] then //Ctrl+v = #22 or #$16
else
key := #0;
end;
procedure TFrm_CUT.cxTextEdit18KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = vk_Return then btn_5_1.Click;
end;
procedure TFrm_CUT.cxTextEdit19KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = vk_Return then btn_5_2.Click;
end;
procedure TFrm_CUT.cxViewCustGroupCellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
var
Row: Integer;
GroupName, GroupSeq, LevelSeq: string;
begin
Row := cxViewCustGroup.DataController.FocusedRecordIndex;
GroupName := cxViewCustGroup.DataController.Values[Row, cxColCGGroupName.Index];
GroupName := Copy(GroupName, Pos(']', GroupName) + 1, Length(GroupName));
GroupSeq := cxViewCustGroup.DataController.Values[Row, cxColCGGroupSeq.Index];
LevelSeq := cxViewCustGroup.DataController.Values[Row, cxColCGLevelSeq.Index];
ShowCustLevelWindow(GroupName, GroupSeq, False, LevelSeq);
end;
procedure TFrm_CUT.cxViewCustLevelCanSelectRecord(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
var AAllow: Boolean);
var
GroupSeq: string;
begin
GroupSeq := cxViewCustLevel.DataController.Values[ARecord.Index, cxColCLGroupSeq.Index];
RequestDataLevelFromGroupSeq(GroupSeq);
end;
procedure TFrm_CUT.cxViewCustLevelFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean);
var
GroupSeq: string;
begin
if not Assigned(AFocusedRecord) then Exit;
GroupSeq := cxViewCustLevel.DataController.Values[AFocusedRecord.Index, cxColCLGroupSeq.Index];
RequestDataLevelFromGroupSeq(GroupSeq);
end;
procedure TFrm_CUT.cxViewRCMDCellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
Var iRow : Integer;
begin
iRow := cxViewRCMD.DataController.FocusedRecordIndex;
if iRow = -1 then Exit;
btn_12_3.Click;
end;
procedure TFrm_CUT.cxViewRCMDDataControllerSortingChanged(Sender: TObject);
begin
gfSetIndexNo(cxViewRCMD, AIndex, GS_SortNoChange);
end;
procedure TFrm_CUT.cxViewRCMDKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
AGridSite: TcxGridSite;
AGridView: TcxGridTableView;
AValue: string;
begin
if (Key = Ord('C')) and (ssCtrl in Shift) then
begin
AGridSite := Sender as TcxGridSite;
AGridView := AGridSite.GridView as TcxGridDBTableView;
Clipboard.AsText := AGridView.Controller.FocusedRow.Values[AGridView.Controller.FocusedColumn.Index];
Key := 0;
end;
end;
procedure TFrm_CUT.cxViewRCMD_DDataControllerSortingChanged(Sender: TObject);
begin
gfSetIndexNo(cxViewRCMD_D, AIndex, GS_SortNoChange);
end;
procedure TFrm_CUT.DelCustGroup(AGroupSeq: string);
var
XmlData, ErrMsg: string;
ErrCode: Integer;
begin
if not RequestBase(GetCallable05('DelCustLevelItem', 'cust_level.group_delete', AGroupSeq), XmlData, ErrCode, ErrMsg) then
begin
GMessageBox(Format('[%d] %s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
RequestDataCustLevel;
end;
procedure TFrm_CUT.DelCustLevel(ALevelSeq: string);
var
XmlData, ErrMsg: string;
ErrCode: Integer;
begin
if not RequestBase(GetCallable05('DelCustLevelItem', 'cust_level.lv_delete', ALevelSeq), XmlData, ErrCode, ErrMsg) then
begin
GMessageBox(Format('[%d] %s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
RequestDataCustLevel;
end;
function TFrm_CUT.DeleteCustomer(AView: TcxGridDBTableView;
ALabel: TcxLabel): Boolean;
var
I, Cnt: Integer;
iColBrNo, iColKeyNum, iColCustNum, iColSeq : Integer;
HdNo, BrNo, KeyNum, CustNum, CuSeq : string;
FailedCount: Integer;
Msg, FailedList: string;
DelRows: TStringList;
begin
Result := False;
Cnt := AView.DataController.GetSelectedCount;
if (Cnt = 0) then
begin
GMessagebox('고객을 선택해 주세요.', CDMSE);
Exit;
end;
Msg := Format('[%d]명의 고객을 삭제하시겠습니까?'#13#10'삭제시 고객정보, 이용횟수, 마일리지가 삭제됩니다.', [Cnt]);
if GMessagebox(Msg, CDMSQ) <> IDOK then Exit;
iColBrNo := AView.GetColumnByFieldName('지사코드').Index;
iColKeyNum := AView.GetColumnByFieldName('대표번호').Index;
iColCustNum := AView.GetColumnByFieldName('고객번호').Index;
iColSeq := AView.GetColumnByFieldName('SEQ').Index;
HdNo := GT_USERIF.HD;
FailedCount := 0;
try
// 읽어서 바로 삭제 시 DataController와 ViewData 데이터 인덱스 Sync가 틀어져서 리스트에 추가후 제거
DelRows := TStringList.Create;
try
for I := AView.DataController.RecordCount - 1 downto 0 do
begin
if AView.ViewData.Rows[I].Selected then
begin
BrNo := AView.ViewData.Rows[I].Values[iColBrNo];
KeyNum := AView.ViewData.Rows[I].Values[iColKeyNum];
CustNum := AView.ViewData.Rows[I].Values[iColCustNum];
CuSeq := AView.ViewData.Rows[I].Values[iColSeq];
if not DeleteCustomerData(HdNo, BrNo, KeyNum, CustNum, CuSeq) then
begin
FailedList := Format('대표번호: %s, 고객번호: %s', [KeyNum, CustNum]) + #13#10 + FailedList;
Inc(FailedCount);
end else
begin
DelRows.Add(Format('%.10d', [AView.ViewData.Rows[I].RecordIndex]));
end;
end;
end;
AView.DataController.BeginUpdate;
try
DelRows.Sort;
for I := DelRows.Count -1 downto 0 do
begin
AView.DataController.DeleteRecord(StrToInt(DelRows[I]));
end;
finally
AView.DataController.EndUpdate;
end;
finally
DelRows.Free;
end;
if FailedCount = 0 then
begin
Msg := Format('[%d]의 고객을 삭제했습니다.', [Cnt]);
GMessagebox(Msg, CDMSI);
end else
begin
Msg := Format('[%d]의 고객 삭제 중 [%d]명 고객정보 삭제에 실패했습니다.'#13#10#13#10, [Cnt, FailedCount]);
Msg := Msg + '[실패고객 정보]'#13#10 + FailedList;
GMessagebox(Msg, CDMSE);
end;
Result := True;
except on E: Exception do
begin
GMessagebox(Format('고객삭제 중 오류가 발생했습니다.[오류: %s]', [E.Message]), CDMSE);
Assert(False, E.Message);
end;
end;
ALabel.Caption := '총 ' + IntToStr(AView.DataController.RecordCount) + '명';
end;
function TFrm_CUT.DeleteCustomerData(AHdNo, ABrNo, AKeyNum, ACustNum,
ACuSeq: string): Boolean;
const
ls_Param = '<param>ParamString</param>';
var
rv_str, ls_TxLoad, ls_Msg_Err, sMsg: string;
sTemp, sParam: string;
ls_rxxml: WideString;
slReceive: TStringList;
ErrCode: integer;
begin
Result := False;
AKeyNum := StringReplace(AKeyNum, '-', '', [rfReplaceAll]);
ACustNum := StringReplace(ACustNum, '-', '', [rfReplaceAll]);
ls_TxLoad := GTx_UnitXmlLoad('CALLABLE.xml');
sTemp := 'PROC_DELETE_CUSTOMER_NEW1(?,?,?,?,?,?)';
sParam := StringReplace(ls_Param, 'ParamString', AHdNo, [rfReplaceAll]);
sParam := sParam + StringReplace(ls_Param, 'ParamString', ABrNo, [rfReplaceAll]);
sParam := sParam + StringReplace(ls_Param, 'ParamString', AKeynum, [rfReplaceAll]);
sParam := sParam + StringReplace(ls_Param, 'ParamString', ACustNum, [rfReplaceAll]);
sParam := sParam + StringReplace(ls_Param, 'ParamString', ACuSeq, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', En_Coding(GT_USERIF.ID), [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', 'DELETECUST', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'CallString', sTemp, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'CountString', IntToStr(5), [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ParamString', sParam, [rfReplaceAll]);
slReceive := TStringList.Create;
try
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False) then
begin
rv_str := slReceive[0];
if rv_str <> '' then
begin
ls_rxxml := rv_str;
try
ls_Msg_Err := GetXmlErrorCode(ls_rxxml);
sMsg := GetXmlErrorMsg(ls_rxxml);
if ('0000' = ls_Msg_Err) and ('1' = sMsg) then
begin
Result := True;
end;
except on E: Exception do
end;
end;
end;
finally
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
end;
procedure TFrm_CUT.edCustName01KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = vk_Return then
btn_1_4Click(nil);
end;
procedure TFrm_CUT.edCustName09KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = vk_Return then btn_9_2.click;
end;
procedure TFrm_CUT.edCustTel12KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = vk_Return then
btn_12_1Click(nil);
end;
procedure TFrm_CUT.FormClose(Sender: TObject; var Action: TCloseAction);
begin
UsrNameReg.WriteString('footer', sFooter);
UsrNameReg.WriteString('header', sHeader);
UsrNameReg.CloseKey;
FreeAndNil(UsrNameReg);
FreeAndNil(lb_st_customer);
FreeAndNil(lbNoSms);
FreeAndNil(SCboLevelSeq);
Action := caFree;
end;
procedure TFrm_CUT.FormCreate(Sender: TObject);
var i : Integer;
begin
try
// 날짜형식이 'yy/mm/dd'일경우 오류 발생 가능성으로 인해 자체 Display 포맷 변경
for i := 0 to ComponentCount - 1 do
begin
if Components[i] is TcxDateEdit then
begin
(Components[i] as TcxDateEdit).Properties.DisplayFormat := 'yyyy/mm/dd';
(Components[i] as TcxDateEdit).Properties.EditFormat := 'yyyy/mm/dd';
end;
end;
except
end;
lb_st_customer := TStringList.Create;
lbNoSms := TStringList.Create;
SCboLevelSeq := TStringList.Create;
cxPageControl1.ActivePageIndex := 0;
cxPageControl1.Tag := 1;
cxPageControl1.Pages[0].TabVisible := TCK_USER_PER.CUR_Manager = '1'; // 401.고객관리
cxPageControl1.Pages[1].TabVisible := TCK_USER_PER.CUR_General = '1'; // 402.일반검색
cxPageControl1.Pages[2].TabVisible := TCK_USER_PER.CUR_High = '1'; // 403.고급검색
cxPageControl1.Pages[3].TabVisible := TCK_USER_PER.CUR_Detail = '1'; // 404.상세검색
cxPageControl1.Pages[4].TabVisible := TCK_USER_PER.CUR_Virture = '1'; // 405.안심번호관리
cxPageControl1.Pages[5].TabVisible := TCK_USER_PER.CUR_Dormancy = '1'; // 406.휴먼고객
cxPageControl1.Pages[6].TabVisible := TCK_USER_PER.CUR_CustLevel = '1'; // 407.고객등급관리
cxPageControl1.Pages[7].TabVisible := TCK_USER_PER.CUR_Mileage = '1'; // 408.마일리지설정
cxPageControl1.Pages[8].TabVisible := TCK_USER_PER.CUR_MileageStat = '1'; // 409.마일리지현황(고객별)
cxPageControl1.Pages[9].TabVisible := TCK_USER_PER.CUR_MileageDetail = '1'; // 410.마일리지상세(적립+지급)
cxPageControl1.Pages[10].TabVisible := False; // TCK_USER_PER.CUR_OKCashBack = '1'; // 411.OK캐쉬백적립현황 메뉴 제거 20201020.CDS
// cxPageControl1.Pages[11].TabVisible := False;
cxPageControl1.Tag := 0;
pnl5.Left := 4;
pnl5.Top := 0;
proc_init;
UsrNameReg := TRegistry.Create;
UsrNameReg.RootKey := HKEY_CURRENT_USER;
UsrNameReg.OpenKey('Software\Microsoft\Internet Explorer\PageSetup', True);
if UsrNameReg.KeyExists('footer') then
begin
sFooter := UsrNameReg.ReadString('footer');
UsrNameReg.WriteString('footer', '');
end else
begin
UsrNameReg.CreateKey('footer');
UsrNameReg.WriteString('footer', '');
sFooter := '&u&b&d';
end;
if UsrNameReg.KeyExists('header') then
begin
sHeader := UsrNameReg.ReadString('header');
UsrNameReg.WriteString('header', '');
end else
begin
UsrNameReg.CreateKey('header');
UsrNameReg.WriteString('header', '');
sHeader := '&w&bPage &p of &P';
end;
end;
procedure TFrm_CUT.FormDestroy(Sender: TObject);
begin
Frm_CUT := Nil;
end;
procedure TFrm_CUT.FormShow(Sender: TObject);
Var i : Integer;
begin
fSetFont(Frm_CUT, GS_FONTNAME);
for i := 0 to pred(cxStyleCustLevel.Count) do
begin
TcxStyle(cxStyleCustLevel.Items[i]).Font.Name := GS_FONTNAME;
end;
for i := 0 to pred(cxStyleRepository1.Count) do
begin
TcxStyle(cxStyleRepository1.Items[i]).Font.Name := GS_FONTNAME;
end;
for i := 0 to pred(cxStyleRepository2.Count) do
begin
TcxStyle(cxStyleRepository2.Items[i]).Font.Name := GS_FONTNAME;
end;
end;
function TFrm_CUT.func_buninSearch(sBrNo, sKeyNum, sCode: string): string;
var
i: Integer;
begin
Result := '';
for i := 0 to GT_BUBIN_INFO.brNo_KeyNum.Count - 1 do
begin
if (GT_BUBIN_INFO.brNo_KeyNum.Strings[i] = Rpad(sbrNo, 5, ' ') + Rpad(StringReplace(sKeyNum, '-', '', [rfReplaceAll]), 15, ' '))
and (GT_BUBIN_INFO.cbcode[i] = sCode + ',' + sBrNo) then
begin
Result := Trim(GT_BUBIN_INFO.cbCorpNm.Strings[i]) + ' / ' +
Trim(GT_BUBIN_INFO.cbDeptNm.Strings[i]);
Break;
end;
end;
end;
function TFrm_CUT.func_ChkPhone: Boolean;
var iRow, iCnt : integer;
begin
iCnt := 0;
for iRow := 0 to cxVirtureList.DataController.RowCount - 1 do
begin
if cxVirtureList.DataController.Values[iRow, 2] <> '' then
inc(iCnt);
end;
if iCnt > 0 then Result := False
else Result := True;
end;
function TFrm_CUT.func_recieve(slList: TStringList): Boolean;
var
xdom: msDomDocument;
lst_Result: IXMLDomNodeList;
ls_Rcrd: TStringList;
ls_MSG_Err, ls_ClientKey: string;
ls_XML: Widestring;
ls_RV_Cnt: Integer;
i, j, iRow: Integer;
ls_rxxml: string;
begin
try
Screen.Cursor := crHourGlass;
ls_XML := slList[0];
xdom := ComsDomDocument.Create;
try
result := True;
if not xdom.loadXML(ls_XML) then
begin
Result := False;
Exit;
end;
ls_MSG_Err := GetXmlErrorCode(ls_XML);
if ('0000' = ls_MSG_Err) then
begin
ls_RV_Cnt := GetXmlRecordCount(ls_XML);
if (0 < ls_RV_Cnt) then
begin
ls_ClientKey := GetXmlClientKey(ls_XML);
if ls_ClientKey = 'NOSM0002' then
begin
sg_notsms_list.BeginUpdate;
for j := 0 to slList.Count - 1 do
begin
Application.ProcessMessages;
ls_rxxml := slList.Strings[j];
if not xdom.loadXML(ls_rxxml) then
begin
Exit;
end;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
iRow := sg_notsms_list.DataController.AppendRecord;
sg_notsms_list.DataController.Values[iRow, 0] := ls_Rcrd[1];
sg_notsms_list.DataController.Values[iRow, 1] := ls_Rcrd[0];
sg_notsms_list.DataController.Values[iRow, 2] := ls_Rcrd[1] + ls_Rcrd[0];
end;
finally
ls_Rcrd.Free;
end;
end;
end;
sg_notsms_list.EndUpdate;
result := False;
end;
end else
begin
Result := False;
end;
end else
begin
Result := False;
GMessagebox(MSG012 + CRLF + ls_Msg_Err, CDMSE);
end;
Application.ProcessMessages;
finally
Screen.Cursor := crDefault;
xdom := Nil;
end;
except
Result := False;
end;
end;
function TFrm_CUT.GetActiveDateControl(AIndex : integer; var AStDt, AEdDt: TcxDateEdit): Boolean;
begin
Result := True;
case AIndex of
11 : begin
AStDt := de_6stDate;
AEdDt := de_6edDate;
end;
12 : begin
AStDt := de_1stDate;
AEdDt := de_1edDate;
end;
13 : begin
AStDt := de_3stDate;
AEdDt := de_3edDate;
end;
14 : begin
AStDt := de_2stDate;
AEdDt := de_2edDate;
end;
15 : begin
AStDt := de_4stDate;
AEdDt := de_4edDate;
end;
16 : begin
AStDt := de_5stDate;
AEdDt := de_5edDate;
end;
21 : begin
AStDt := cxDate2_1S;
AEdDt := cxDate2_1E;
end;
31 : begin
AStDt := cxDate3_1S;
AEdDt := cxDate3_1E;
end;
32 : begin
AStDt := de_A31stDate;
AEdDt := de_A31edDate;
end;
33 : begin
AStDt := de_A33stDate;
AEdDt := de_A33edDate;
end;
34 : begin
AStDt := de_A32stDate;
AEdDt := de_A32edDate;
end;
41 : begin
AStDt := cxDate4_1S;
AEdDt := cxDate4_1E;
end;
42 : begin
AStDt := cxDate4_2S;
AEdDt := cxDate4_2E;
end;
43 : begin
AStDt := cxDate4_3S;
AEdDt := cxDate4_3E;
end;
91 : begin
AStDt := cxDate9_1S;
AEdDt := cxDate9_1E;
end;
92 : begin
AStDt := cxDate9_2S;
AEdDt := cxDate9_2E;
end;
101: begin
AStDt := cxDate10_1S;
AEdDt := cxDate10_1E;
end;
111: begin
AStDt := dtOKCStDate;
AEdDt := dtOKCEdDate;
end;
112: begin
AStDt := cxDate12_1S;
AEdDt := cxDate12_1E;
end;
end;
end;
function TFrm_CUT.GetDeptCustomerCount(AHdNo, ABrNo,
ADeptCode: string): Integer;
var
xdom: msDomDocument;
lst_Result: IXMLDomNodeList;
ls_TxLoad, ls_TxQry, sQueryTemp,
XmlStr, ErrorCode: string;
StrList: TStringList;
ErrCode: Integer;
begin
Result := -1;
ls_TxLoad := GTx_UnitXmlLoad('SEL02.XML');
fGet_BlowFish_Query(GSQ_CUST_BUBIN_COUNT_SEARCH, sQueryTemp);
ls_TxQry := Format(sQueryTemp, [AHdNo, ABrNo, ADeptCode]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', En_Coding(GT_USERIF.ID), [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', self.Caption + '14', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'PagingString', '500', [rfReplaceAll]);
StrList := TStringList.Create;
try
if dm.SendSock(ls_TxLoad, StrList, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
xdom := ComsDomDocument.Create;
try
XmlStr := StrList[0];
if not xdom.loadXML(XmlStr) then
Exit;
ErrorCode := GetXmlErrorCode(XmlStr);
if ('0000' = ErrorCode) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
Result := StrToIntDef(GetTextSeperationFirst('│', lst_Result.item[0].attributes.getNamedItem('Value').Text), -1);
end;
finally
xdom := Nil;
end;
end;
finally
Frm_Flash.Hide;
FreeAndNil(StrList);
end;
end;
procedure TFrm_CUT.Label7Click(Sender: TObject);
procedure RunDownload;
var
IE: Variant;
begin
try
IE := CreateOleObject('InternetExplorer.Application');
IE.height := 100;
IE.width := 100;
IE.left := 0;
IE.top := 0;
IE.MenuBar := False;
IE.AddressBar := True;
IE.Resizable := False;
IE.StatusBar := False;
IE.ToolBar := False;
IE.Silent := false;
sleep(1);
IE.Navigate('http://www.callmaner.com/download/콜마너_고객등급변경신청서.xls');
IE.Visible := True;
Application.ProcessMessages;
sleep(1);
except on E: Exception do
GMessagebox(Format('신청서 다운로드 시 오류(Err: %s)가 발생하였습니다.'#13#10
+ '(다시시도 바랍니다.)' , [E.Message]), CDMSE);
end;
end;
begin
RunDownload;
end;
procedure TFrm_CUT.menuCallBellClick(Sender: TObject);
var sTmp : string;
i, j, iTmp, iAddRow : integer;
slTmp : TStringList;
iHdNo, iBrNo, iKeyNum, iSeq, iCuName, iRow: Integer;
sHdNo, sBrNo, sKeyNum, sSeq, sCuName: string;
begin
iRow := CustView1.DataController.FocusedRecordIndex;
if iRow = -1 then
Exit;
iHdNo := CustView1.GetColumnByFieldName('hdno').Index;
iBrNo := CustView1.GetColumnByFieldName('지사코드').Index;
iKeyNum := CustView1.GetColumnByFieldName('대표번호').Index;
iSeq := CustView1.GetColumnByFieldName('SEQ').Index;
iCuName := CustView1.GetColumnByFieldName('고객명').Index;
sHdNo := CustView1.DataController.Values[iRow, iHdNo];
sBrNo := CustView1.DataController.Values[iRow, iBrNo];
sKeyNum := CustView1.DataController.Values[iRow, iKeyNum];
sSeq := CustView1.DataController.Values[iRow, iSeq];
sCuName := CustView1.DataController.Values[iRow, iCuName];
if Frm_BTN.Scb_CallBell_KeyNumber.IndexOf(CallToStr(sKeyNum)) < 0 then
begin
GMessagebox('콜벨업소로 변경이 불가능합니다.', CDMSE);//'실착신번호가 연결되지 않은 대표번호로' + #13#10 + '콜벨업소로 변경이 불가능합니다.', CDMSI);
exit;
end;
if ( Not Assigned(Frm_BTN01) ) Or ( Frm_BTN01 = Nil ) then
Frm_BTN01 := TFrm_BTN01.Create(Nil)
else Frm_BTN01.proc_Init;
sTmp := '';
for i := 0 to Frm_BTN.Scb_CallBell_BrNo.Count - 1 do
begin
iTmp := scb_DsBranchCode.IndexOf(Frm_BTN.Scb_CallBell_BrNo[i]);
if iTmp < 0 then Continue;
if sTmp = Frm_BTN.Scb_CallBell_BrNo[i] then Continue;
// 본사코드 // 지사코드 // 지사명 // 대표번호
if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB
begin
if sHdNo = scb_HeadCode[iTmp] then
begin
Frm_BTN01.cboBranch.Properties.Items.Add(scb_HeadCode[iTmp] + '.' +
Frm_BTN.Scb_CallBell_BrNo[i] + ': ' + scb_DsBranchName[iTmp]);
sTmp := Frm_BTN.Scb_CallBell_BrNo[i];
end;
end else
begin
Frm_BTN01.cboBranch.Properties.Items.Add(scb_HeadCode[iTmp] + '.' +
Frm_BTN.Scb_CallBell_BrNo[i] + ': ' + scb_DsBranchName[iTmp]);
sTmp := Frm_BTN.Scb_CallBell_BrNo[i];
end;
end;
Frm_BTN01.cboBankCode.Properties.Items.Clear;
Frm_BTN01.cboBankName.Properties.Items.Clear;
Frm_BTN01.cboBankCode.Properties.Items.Assign(Frm_BTN.Scb_BankCd);
Frm_BTN01.cboBankName.Properties.Items.Assign(Frm_BTN.Scb_BankNm);
Frm_BTN01.cboBankName.ItemIndex := 0;
if not Frm_BTN.func_CallBellUpso(sBrNo, sSeq) then
begin
if func_Cust_Search(sHdNo, sBrNo, sKeyNum, sSeq) then
begin
//콜벨업소로 등록되지 않았다면
Frm_BTN01.clbCuSeq.Caption := sSeq;
for j := 0 to Frm_BTN01.cboBranch.Properties.Items.Count - 1 do
begin
sTmp := Copy(Frm_BTN01.cboBranch.Properties.Items[j], Pos('.', Frm_BTN01.cboBranch.Properties.Items[j]) + 1, Pos(':',
Frm_BTN01.cboBranch.Properties.Items[j]) - (Pos('.', Frm_BTN01.cboBranch.Properties.Items[j]) + 1)); //지사코드
if sBrNo = sTmp then
begin
Frm_BTN01.cboBranch.ItemIndex := j;
Break;
end;
end;
Frm_BTN01.cboKeynumber.ItemIndex := Frm_BTN01.cboKeynumber.Properties.Items.Indexof(StrToCall(sKeyNum));
Frm_BTN01.cboUpsoWK.ItemIndex := 0;
Frm_BTN01.edtUpsoName.Text := FCuData.CuName;
Frm_BTN01.edtUpsoHP.Text := '';
Frm_BTN01.cboStatus.ItemIndex := 0;
Frm_BTN01.btnSave.Enabled := True;
slTmp := TStringList.Create;
try
slTmp.Clear;
slTmp.Delimiter := '|';
slTmp.DelimitedText := FCuData.CuTelList;
Try
Frm_BTN01.cxUpsoTel.BeginUpdate;
Frm_BTN01.cxUpsoTel.DataController.SetRecordCount(0);
for i := 0 to slTmp.Count - 1 do
begin
iAddRow := Frm_BTN01.cxUpsoTel.DataController.AppendRecord;
Frm_BTN01.cxUpsoTel.DataController.Values[iAddRow, 0] := slTmp[i];
end;
Frm_BTN01.cxUpsoTel.EndUpdate;
except
Frm_BTN01.cxUpsoTel.EndUpdate;
End;
Frm_BTN01.rb_Straight.Checked := True;
Frm_BTN01.edtCalValue.Text := '';
Frm_BTN01.cboBankName.ItemIndex := 0;
Frm_BTN01.edtBankNumberCust.Text := '';
Frm_BTN01.edtBankOwnerCust.Text := '';
Frm_BTN01.lcsCallBell1 := FCuData.CuStart1;
Frm_BTN01.lcsCallBell2 := FCuData.CuStart2;
Frm_BTN01.lcsCallBell3 := FCuData.CuStart3;
Frm_BTN01.lbUpsoAreaName.Caption := FCuData.CuStart1 + ' ' + FCuData.CuStart2 + ' ' + FCuData.CuStart3;
Frm_BTN01.edtUpsoAreaDetail.Caption := FCuData.CuAreaDetail;
Frm_BTN01.meoCallBellArea.Text := FCuData.CuArea;
Frm_BTN01.edtXval.Caption := FCuData.CuXval;
Frm_BTN01.edtYval.Caption := FCuData.CuYVal;
if Trim(FCuData.CuMemo) <> '' then
begin
GetTextSeperationEx2('¶', FCuData.CuMemo, slTmp);
for j := 0 to slTmp.Count - 1 do
begin
Frm_BTN01.meoCallBellUpsoMemo.Lines.Add(slTmp[j]);
end;
end;
finally
slTmp.Free;
end;
end;
end;
Frm_BTN01.btnSave.Caption := '수정';
Frm_BTN01.pnlTitle.Caption := ' 콜벨 업소 수정';
Frm_BTN01.pnlTitle.Hint := 'Update';
Frm_BTN01.cboBranch.Enabled := False;
Frm_BTN01.cboKeynumber.Enabled := False;
if not Frm_BTN01.Showing then
begin
Frm_BTN01.Left := (Screen.Width - Frm_BTN01.Width) div 2;
Frm_BTN01.top := (Screen.Height - Frm_BTN01.Height) div 2;
if Frm_BTN01.top <= 10 then Frm_BTN01.top := 10;
Frm_BTN01.Tag := 1;
Frm_BTN01.Show;
end;
end;
procedure TFrm_CUT.N1Click(Sender: TObject);
begin
proc_CustCounsel_Clear;
end;
procedure TFrm_CUT.MenuItem6Click(Sender: TObject);
begin
btn_1_8Click(nil);
end;
procedure TFrm_CUT.menuUpsoPeeClick(Sender: TObject);
var i, iSeq, iCnt, iGubun : integer;
sCutSeq : string;
begin
cxGrid1.Enabled := False;
gslUpsoPeeSeq := TStringList.Create;
Try
iCnt := 0;
iAddCnt := 0;
sCutSeq := '';
iSeq := CustView1.GetColumnByFieldName('SEQ').Index;
iGubun := CustView1.GetColumnByFieldName('구분').Index;
Screen.Cursor := crHourGlass;
for I := 0 to CustView1.DataController.RecordCount - 1 do
begin
if (CustView1.ViewData.Records[i].Selected) and (CustView1.ViewData.Records[I].Values[iGubun] = '업소') then
begin
if sCutSeq = '' then
begin
sCutSeq := Trim(CustView1.ViewData.Records[I].Values[iSeq]);
end else
begin
sCutSeq := sCutSeq + ',' + Trim(CustView1.ViewData.Records[I].Values[iSeq]);
end;
Inc(iCnt);
Inc(iAddCnt);
end;
if iAddCnt = 100 then
begin
gslUpsoPeeSeq.Add(sCutSeq);
sCutSeq := '';
iAddCnt := 0;
end;
end;
gslUpsoPeeSeq.Add(sCutSeq);
if icnt < 1 then
begin
cxGrid1.Enabled := True;
GMessagebox('고객이 선택되지 않았습니다.', CDMSE);
Screen.Cursor := crDefault;
Exit;
end;
gbUpsoPee.Left := (frm_main.Width - gbUpsoPee.Width) div 2;
gbUpsoPee.top := ((frm_main.Height - gbUpsoPee.Height) div 2) - 50;
gbUpsoPee.visible := True;
edtCalValue.value := 0;
gbUpsoPee.BringToFront;
cxLabel230.Caption := inttostr(icnt) + ' 개';
Screen.Cursor := crDefault;
except
gslUpsoPeeSeq.Free;
Screen.Cursor := crDefault;
End;
end;
procedure TFrm_CUT.mniDetailCustLevelClick(Sender: TObject);
var
I: Integer;
iSeq: Integer;
begin
if FDetailKeyNum = '' then
begin
GMessageBox('고객등급 변경은 대표번호 선택하여 검색된 내역으로 시도바랍니다.', CDMSE);
cbKeynumber04.SetFocus;
Exit;
end;
if CustView4.DataController.GetSelectedCount = 0 then
begin
GMessageBox('고객을 선택해 주세요.', CDMSE);
Exit;
end;
if ( not Assigned(Frm_CUT03) ) Or ( Frm_CUT03 = Nil ) then Frm_CUT03 := TFrm_CUT03.Create(Self);
Frm_CUT03.SetData(GetBrNoFromKeyNum(FDetailKeyNum), FDetailKeyNum);
iSeq := CustView4.GetColumnByFieldName('SEQ').Index;
for I := 0 to CustView4.DataController.RecordCount - 1 do
begin
if not CustView4.ViewData.Rows[I].Selected then Continue;
Frm_CUT03.AddCustSeq(CustView4.ViewData.Rows[I].Values[iSeq]);
end;
Frm_CUT03.DispData;
Frm_CUT03.Show;
end;
procedure TFrm_CUT.mniN9Click(Sender: TObject);
var
iBrNo, iKeyNum, iSeq, iCustTel, iRow: Integer;
sBrNo, sKeyNum, sSeq, sCustTel: string;
begin
// 권한 적용 (지호 2008-08-19)
if TCK_USER_PER.COM_CustModify <> '1' then
begin
GMessagebox('고객 수정권한이 없습니다.', CDMSE);
Exit;
end;
iRow := CustView1.DataController.FocusedRecordIndex;
if iRow = -1 then Exit;
iBrNo := CustView1.GetColumnByFieldName('지사코드').Index;
iKeyNum := CustView1.GetColumnByFieldName('대표번호').Index;
iSeq := CustView1.GetColumnByFieldName('SEQ').Index;
iCustTel:= CustView1.GetColumnByFieldName('고객번호').Index;
sBrNo := CustView1.DataController.Values[iRow, iBrNo];
sKeyNum := CustView1.DataController.Values[iRow, iKeyNum];
sKeyNum := StringReplace(sKeyNum, '-', '', [rfReplaceAll]);
sSeq := CustView1.DataController.Values[iRow, iSeq];
sCustTel:= CustView1.DataController.Values[iRow, iCustTel];
if sCustTel = '' then
begin
GMessagebox('고객 전화번호가 없습니다.', CDMSE);
Exit;
end;
if ( not Assigned(Frm_CUT012) ) Or ( Frm_CUT012 = Nil ) then Frm_CUT012 := TFrm_CUT012.Create(Self);
Frm_CUT012.Show(sBrNo, sKeyNum, sSeq, sCustTel);
end;
procedure TFrm_CUT.N_TodayClick(Sender: TObject);
var
StDt, EdDt: TcxDateEdit;
begin
if GetActiveDateControl(pm_Date.Tag, StDt, EdDt) then
CustSetDateControl(0, StDt, EdDt);
end;
procedure TFrm_CUT.N_YesterdayClick(Sender: TObject);
var
StDt, EdDt: TcxDateEdit;
begin
if GetActiveDateControl(pm_Date.Tag, StDt, EdDt) then
CustSetDateControl(1, StDt, EdDt);
end;
procedure TFrm_CUT.N_WeekClick(Sender: TObject);
var
StDt, EdDt: TcxDateEdit;
begin
if GetActiveDateControl(pm_Date.Tag, StDt, EdDt) then
CustSetDateControl(2, StDt, EdDt);
end;
procedure TFrm_CUT.N_MonthClick(Sender: TObject);
var
StDt, EdDt: TcxDateEdit;
begin
if GetActiveDateControl(pm_Date.Tag, StDt, EdDt) then
CustSetDateControl(11, StDt, EdDt);
end;
procedure TFrm_CUT.N_1Start31EndClick(Sender: TObject);
var
StDt, EdDt: TcxDateEdit;
begin
if GetActiveDateControl(pm_Date.Tag, StDt, EdDt) then
CustSetDateControl(3, StDt, EdDt);
end;
procedure TFrm_CUT.MenuItem33Click(Sender: TObject);
var
StDt, EdDt: TcxDateEdit;
begin
if GetActiveDateControl(Pop_Ymd.Tag, StDt, EdDt) then //오늘
CustSetDateControl(0, StDt, EdDt);
end;
procedure TFrm_CUT.MenuItem34Click(Sender: TObject);
var
StDt, EdDt: TcxDateEdit;
begin
if GetActiveDateControl(Pop_Ymd.Tag, StDt, EdDt) then //1개월
CustSetDateControl(11, StDt, EdDt);
end;
procedure TFrm_CUT.MenuItem35Click(Sender: TObject);
var
StDt, EdDt: TcxDateEdit;
begin
if GetActiveDateControl(Pop_Ymd.Tag, StDt, EdDt) then //3개월
CustSetDateControl(12, StDt, EdDt);
end;
procedure TFrm_CUT.MenuItem36Click(Sender: TObject);
var
StDt, EdDt: TcxDateEdit;
begin
if GetActiveDateControl(Pop_Ymd.Tag, StDt, EdDt) then //6개월
CustSetDateControl(13, StDt, EdDt);
end;
procedure TFrm_CUT.MenuItem37Click(Sender: TObject);
var
StDt, EdDt: TcxDateEdit;
begin
if GetActiveDateControl(Pop_Ymd.Tag, StDt, EdDt) then //1년
CustSetDateControl(14, StDt, EdDt);
end;
procedure TFrm_CUT.OnRefreshCustLevel(Sender: TObject);
begin
RequestDataCustLevel;
end;
procedure TFrm_CUT.pmCustMgrPopup(Sender: TObject);
var iRow, iTmp : integer;
begin
menuCallBell.visible := False;
if gs_CallBellUse then
begin
iRow := CustView1.DataController.FocusedRecordIndex;
if iRow = -1 then
Exit;
iTmp := CustView1.GetColumnByFieldName('구분').Index;
if CustView1.DataController.Values[iRow, iTmp] = '업소' then
begin
menuCallBell.Caption := '콜벨업소로 변경';
menuCallBell.visible := True;
menuCallBell.Tag := 1;
end else
if CustView1.DataController.Values[iRow, iTmp] = '콜벨업소' then
begin
menuCallBell.Caption := '콜벨업소 정보수정';
menuCallBell.visible := True;
menuCallBell.Tag := 2;
end;
end;
end;
procedure TFrm_CUT.proc_before_comp;
var
ls_TxQry, ls_TxLoad, sQueryTemp : string;
lg_sWhere, sBrNo, sClientKey: string;
sCGubun, sCName, sCTel, sCmemo, sSql: string;
slReceive: TStringList;
ErrCode: integer;
begin
dt_sysdate2 := frm_main.func_sysdate;
chk_All_Select.Checked := False;
chk_All_Select.OnClick(chk_All_Select);
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) > 2100)
or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
lb_st_customer.Clear;
sBrNo := cxBrNo2.Text;
lg_swhere := '';
if sBrNo <> '' then
lg_sWhere := Format(' AND A.CONF_HEAD = ''%s'' AND A.CONF_BRCH = ''%s'' AND A.CONF_STATUS = ''2'' ', [cxHdNo2.Text, sBrNo])
else
lg_sWhere := Format(' AND A.CONF_HEAD = ''%s'' AND A.CONF_STATUS = ''2'' ', [cxHdNo2.Text]);
sCGubun := 'A.CONF_BAR';
sCName := 'A.CONF_USER';
sCTel := 'A.CONF_CUST_TEL';
sCmemo := 'A.CONF_MEMO';
sClientKey := self.Caption + '4';
fGet_BlowFish_Query(GSQ_HISTORY_LIST, sQueryTemp);
sSql := sQueryTemp;
if cb_Sms_Gubun.ItemIndex > 0 then
begin
if (sg_notsms_list.DataController.RecordCount > 0) and
(sg_notsms_list.DataController.Values[0, 0] <> sBrno) then
proc_NotSMS(sBrNo);
end;
if (cb_st_city.Text <> '지역전체') and (cb_st_ward.ItemIndex > 0) then
lg_sWhere := lg_sWhere + Format(' AND A.CONF_AREA = ''%s'' AND A.CONF_AREA2 = ''%s'' ', [cb_st_city.Text, cb_st_ward.Text])
else
if (cb_st_city.Text <> '지역전체') and (cb_st_ward.ItemIndex < 1) then
lg_sWhere := lg_sWhere + Format(' AND A.CONF_AREA = ''%s'' ', [cb_st_city.Text]);
if (cbKeynumber02.Text <> '전체') and (cbKeynumber02.Text <> '') then
lg_sWhere := lg_sWhere + format(' AND (A.KEY_NUMBER = ''%s'') ', [StringReplace(cbKeynumber02.Text, '-', '', [rfReplaceAll])]);
lg_sWhere := lg_sWhere +
format(' AND A.IN_DATE BETWEEN TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') AND TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') '
, [formatdatetime('yyyymmdd', cxDate2_1S.Date), formatdatetime('yyyymmdd', cxDate2_1E.Date)]);
case cbGubun2_1.ItemIndex of
1: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''0'' ';
2: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''1'' ';
3: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''3'' ';
end;
if Trim(edCustMemo01.Text) <> '' then
lg_sWhere := lg_sWhere + Format(' AND (%s LIKE ''%s'' || ''%s'' || ''%s'') ', [sCmemo, '%', trim(edCustMemo01.Text), '%']);
if trim(edCustName02.Text) <> '' then
lg_sWhere := lg_sWhere + Format(' AND (%s LIKE ''%s'' || ''%s'') ', [sCName, trim(edCustName02.Text), '%']);
if trim(edCustTel02.Text) <> '' then
lg_sWhere := lg_sWhere + Format(' AND (%s LIKE ''%s'' || ''%s'' || ''%s'') ', [sCTel, '%', trim(edCustTel02.Text), '%']);
ls_TxLoad := GTx_UnitXmlLoad('SEL02.XML');
ls_TxQry := Format(sSql, [lg_sWhere]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', GT_USERIF.ID, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', sClientKey, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'PagingString', '3000', [rfReplaceAll]);
cxPageControl1.Enabled := False;
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
cxPageControl1.Enabled := True;
Frm_Flash.Hide;
end;
lbCount02.Caption := '총 ' + IntToStr(CustView2.DataController.RecordCount) + '명';
end;
procedure TFrm_CUT.proc_before_his;
var
ls_TxQry, ls_TxLoad, sQueryTemp: string;
lg_sWhere, sBrNo, sClientKey: string;
sCGubun, sCName, sCTel, sCmemo, sSql: string;
slReceive: TStringList;
ErrCode: integer;
begin
if CustView2.DataController.RecordCount > 0 then
Exit;
dt_sysdate2 := frm_main.func_sysdate;
chk_All_Select.Checked := False;
chk_All_Select.OnClick(chk_All_Select);
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) > 2100)
or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
lb_st_customer.Clear;
sBrNo := cxBrNo2.Text;
lg_swhere := '';
if sBrNo <> '' then
lg_sWhere := Format(' AND A.CONF_HEAD = ''%s'' AND A.CONF_BRCH = ''%s'' ', [cxHdNo2.Text, sBrNo])
else
lg_sWhere := Format(' AND A.CONF_HEAD = ''%s'' ', [cxHdNo2.Text]);
sCGubun := 'A.CONF_BAR';
sCName := 'A.CONF_USER';
sCTel := 'A.CONF_CUST_TEL';
sCmemo := 'A.CONF_MEMO';
sClientKey := Self.Caption + '4';
fGet_BlowFish_Query(GSQ_HISTORY_LIST, sQueryTemp);
sSql := sQueryTemp;
if cb_Sms_Gubun.ItemIndex > 0 then
begin
if (sg_notsms_list.DataController.RecordCount > 0) and
(sg_notsms_list.DataController.Values[0, 0] <> sBrno) then
proc_NotSMS(sBrNo);
end;
lg_sWhere := lg_sWhere + ' AND A.CONF_STATUS IN (''2'', ''4'', ''8'') ';
if (cb_st_city.Text <> '지역전체') and (cb_st_ward.ItemIndex > 0) then
lg_sWhere := lg_sWhere + Format(' AND A.CONF_AREA = ''%s'' AND A.CONF_AREA2 = ''%s'' ', [cb_st_city.Text, cb_st_ward.Text])
else if (cb_st_city.Text <> '지역전체') and (cb_st_ward.ItemIndex < 1) then
lg_sWhere := lg_sWhere + Format(' AND A.CONF_AREA = ''%s'' ', [cb_st_city.Text]);
if (cbKeynumber02.Text <> '전체') and (cbKeynumber02.Text <> '') then
lg_sWhere := lg_sWhere + format(' AND (A.KEY_NUMBER = ''%s'') ', [StringReplace(cbKeynumber02.Text, '-', '', [rfReplaceAll])]);
lg_sWhere := lg_sWhere +
format(' AND A.IN_DATE BETWEEN TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') AND TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') '
, [formatdatetime('yyyymmdd', cxDate2_1S.Date), formatdatetime('yyyymmdd', cxDate2_1E.Date)]);
case cbGubun2_1.ItemIndex of
1: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''0'' ';
2: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''1'' ';
3: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''3'' ';
end;
if Trim(edCustMemo01.Text) <> '' then
lg_sWhere := lg_sWhere +
format(' AND (%s LIKE ''%s'' || ''%s'' || ''%s'') ', [sCmemo, '%', trim(edCustMemo01.Text), '%']);
if trim(edCustName02.Text) <> '' then
lg_sWhere := lg_sWhere + format(' AND (%s LIKE ''%s'' || ''%s'') ', [sCName, trim(edCustName02.Text), '%']);
if trim(edCustTel02.Text) <> '' then
lg_sWhere := lg_sWhere + format(' AND (%s LIKE ''%s'' || ''%s'' || ''%s'') ', [sCTel, '%', trim(edCustTel02.Text), '%']);
ls_TxLoad := GTx_UnitXmlLoad('SEL02.XML');
ls_TxQry := Format(sSql, [lg_sWhere]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', GT_USERIF.ID, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', sClientKey, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'PagingString', '3000', [rfReplaceAll]);
cxPageControl1.Enabled := False;
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
cxPageControl1.Enabled := True;
Frm_Flash.Hide;
end;
lbCount02.Caption := '총 ' + IntToStr(CustView2.DataController.RecordCount) + '명';
end;
procedure TFrm_CUT.proc_before_new;
var
ls_TxQry, ls_TxLoad, sQueryTemp: string;
lg_sWhere, sBrNo, sClientKey: string;
sCGubun, sCName, sCTel, sCmemo, sSql: string;
slReceive: TStringList;
ErrCode: integer;
begin
dt_sysdate2 := frm_main.func_sysdate;
chk_All_Select.Checked := False;
chk_All_Select.OnClick(chk_All_Select);
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) > 2100)
or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
lb_st_customer.Clear;
sBrNo := cxBrNo2.Text;
lg_swhere := '';
if sBrNo <> '' then
lg_sWhere :=
Format(' AND A.HD_NO = ''%s'' AND A.BR_NO = ''%s'' ', [cxHdNo2.Text, sBrNo])
else
lg_sWhere :=
Format(' AND A.HD_NO = ''%s'' ', [cxHdNo2.Text]);
sCGubun := 'A.CU_TYPE';
sCName := 'A.CMP_NM';
sCTel := 'B.CU_TEL';
sCmemo := 'A.CU_INFO';
sClientKey := self.Caption + '4';
fGet_BlowFish_Query(GSQ_CUSTOMER_LIST, sQueryTemp);
sSql := sQueryTemp;
if cb_Sms_Gubun.ItemIndex = 1 then
lg_sWhere := lg_sWhere + ' AND (B.CU_SMSYN = ''y'') '
else
if cb_Sms_Gubun.ItemIndex = 2 then
lg_sWhere := lg_sWhere + ' AND (B.CU_SMSYN = ''n'') ';
if (cbKeynumber02.Text <> '전체') and (cbKeynumber02.Text <> '') then
lg_sWhere := lg_sWhere + format(' AND (A.KEY_NUMBER = ''%s'') ',
[StringReplace(cbKeynumber02.Text, '-', '', [rfReplaceAll])]);
lg_sWhere := lg_sWhere +
format(' AND A.IN_DATE BETWEEN TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') AND TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') '
, [formatdatetime('yyyymmdd', cxDate2_1S.Date), formatdatetime('yyyymmdd', cxDate2_1E.Date)]);
case cbGubun2_1.ItemIndex of
1: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''0'' ';
2: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''1'' ';
3: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''3'' ';
end;
if Trim(edCustMemo01.Text) <> '' then
lg_sWhere := lg_sWhere +
format(' AND (%s LIKE ''%s'' || ''%s'' || ''%s'') ', [sCmemo, '%',
trim(edCustMemo01.Text), '%']);
if trim(edCustName02.Text) <> '' then
lg_sWhere := lg_sWhere + format(' AND (%s LIKE ''%s'' || ''%s'') ',
[sCName, trim(edCustName02.Text), '%']);
if trim(edCustTel02.Text) <> '' then
lg_sWhere := lg_sWhere +
format(' AND (%s LIKE ''%s'' || ''%s'' || ''%s'') ', [sCTel, '%',
trim(edCustTel02.Text), '%']);
ls_TxLoad := GTx_UnitXmlLoad('SEL02.XML');
ls_TxQry := Format(sSql, [lg_sWhere]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', GT_USERIF.ID, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', sClientKey, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'PagingString', '3000', [rfReplaceAll]);
cxPageControl1.Enabled := False;
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
cxPageControl1.Enabled := True;
Frm_Flash.Hide;
end;
lbCount02.Caption := '총 ' + IntToStr(CustView2.DataController.RecordCount) + '명';
end;
procedure TFrm_CUT.proc_Branch_Change;
begin
proc_BrNameSet;
end;
procedure TFrm_CUT.proc_BrNameSet;
var
sName, sBrNo, sHdNo : string;
StrList: TStringList;
iCol : integer;
begin
iCol := CustView1.GetColumnByFieldName('콜벨등록일').Index;
if gs_CallBellUse then
begin
if cbGubun1_1.Properties.Items.Count = 4 then
begin
cbGubun1_1.Properties.Items.add('콜벨업소');
end;
if (gs_CallBellUse) then //콜벨업소이면서
begin
if Not Assigned(Frm_BTN) then Frm_BTN := TFrm_BTN.Create(Nil);
Frm_BTN.proc_CallBell_BRANCH_INFO;
if Frm_BTN.Scb_BankCd.count = 0 then
Frm_BTN.proc_Bank;
end;
CustView1.Columns[iCol].visible := True;
end else
begin
if cbGubun1_1.Properties.Items.Count > 4 then
begin
cbGubun1_1.Properties.Items.delete(4);
end;
CustView1.Columns[iCol].visible := False;
end;
StrList := TStringList.Create;
try
if ((GT_USERIF.LV = '60') or (GT_USERIF.LV = '10')) and (GT_SEL_BRNO.GUBUN <> '1') then
begin
GetBrTelList(GT_SEL_BRNO.HDNO, StrList);
cbKeynumber01.Properties.Items.Assign(StrList);
sHdNo := GT_SEL_BRNO.HDNO;
sBrNo := '';
end else
begin
GetBrTelList(GT_SEL_BRNO.BrNo, StrList);
cbKeynumber01.Properties.Items.Assign(StrList);
sHdNo := GT_SEL_BRNO.HDNO;
sBrNo := GT_SEL_BRNO.BrNo;
end;
finally
StrList.Free;
end;
sName := GetSosokInfo;
cxHdNo1.Text := sHdNo;
cxBrNo1.Text := sBrNo;
cxHdNo2.Text := sHdNo;
cxBrNo2.Text := sBrNo;
cxHdNo3.Text := sHdNo;
cxBrNo3.Text := sBrNo;
cxHdNo4.Text := sHdNo;
cxBrNo4.Text := sBrNo;
cxHdNo5.Text := sHdNo;
cxBrNo5.Text := sBrNo;
cxHdNo6.Text := sHdNo;
cxBrNo6.Text := sBrNo;
cxHdNo8.Text := sHdNo;
cxBrNo8.Text := sBrNo;
cxHdNo9.Text := sHdNo;
cxBrNo9.Text := sBrNo;
cxHdNo10.Text := sHdNo;
cxBrNo10.Text := sBrNo;
cxHdNo11.Text := sHdNo;
cxBrNo11.Text := sBrNo;
lbCustCompany01.Caption := sName;
lbCustCompany02.Caption := sName;
lbCustCompany03.Caption := sName;
lbCustCompany04.Caption := sName;
lbCustCompany05.Caption := sName;
lbCustCompany06.Caption := sName;
lbCustCompany07.Caption := sName;
lbCustCompany08.Caption := sName;
lbCustCompany09.Caption := sName;
lbCustCompany10.Caption := sName;
lbCustCompany11.Caption := sName;
lbCustCompany12.Caption := sName;
cbKeynumber12.Properties.Items.Assign(cbKeynumber01.Properties.Items); // 전체가 없어야 됨
if cbKeynumber01.Properties.Items.Count >= 1 then
cbKeynumber01.Properties.Items.Insert(0, '전체');
cbKeynumber02.Properties.Items.Assign(cbKeynumber01.Properties.Items);
cbKeynumber03.Properties.Items.Assign(cbKeynumber01.Properties.Items);
cbKeynumber04.Properties.Items.Assign(cbKeynumber01.Properties.Items);
cbKeynumber05.Properties.Items.Assign(cbKeynumber01.Properties.Items);
cbKeynumber06.Properties.Items.Assign(cbKeynumber01.Properties.Items);
cbKeynumber09.Properties.Items.Assign(cbKeynumber01.Properties.Items);
cbKeynumber10.Properties.Items.Assign(cbKeynumber01.Properties.Items);
cbKeynumber01.Tag := 1;
cbKeynumber02.Tag := 1;
cbKeynumber03.Tag := 1;
cbKeynumber04.Tag := 1;
cbKeynumber05.Tag := 1;
cbKeynumber06.Tag := 1;
cbKeynumber09.Tag := 1;
cbKeynumber10.Tag := 1;
cbKeynumber12.Tag := 1;
cbKeynumber01.ItemIndex := 0;
cbKeynumber02.ItemIndex := 0;
cbKeynumber03.ItemIndex := 0;
cbKeynumber04.ItemIndex := 0;
cbKeynumber05.ItemIndex := 0;
cbKeynumber06.ItemIndex := 0;
cbKeynumber09.ItemIndex := 0;
cbKeynumber10.ItemIndex := 0;
cbKeynumber12.ItemIndex := 0;
cbKeynumber01.Tag := 0;
cbKeynumber02.Tag := 0;
cbKeynumber03.Tag := 0;
cbKeynumber04.Tag := 0;
cbKeynumber05.Tag := 0;
cbKeynumber06.Tag := 0;
cbKeynumber09.Tag := 0;
cbKeynumber10.Tag := 0;
cbKeynumber12.Tag := 0;
end;
procedure TFrm_CUT.proc_bubin_init;
var
i: Integer;
sBrNo, sKeyNum: string;
begin
if cxPageControl1.ActivePageIndex = 0 then
begin
if ( cbGubun1_1.ItemIndex = 3 ) Or ( chkBubinName.Checked ) then
begin
sBrNo := cxBrNo1.Text;
sKeyNum := cbKeynumber01.Text;
cbBCustList.Properties.Items.Clear;
cbBCustListCd.Properties.Items.Clear;
cbBCustList.Properties.Items.Add('선택');
cbBCustListCd.Properties.Items.Add('');
if (sBrNo = '') or (sKeyNum = '전체') then Exit;
for i := 0 to GT_BUBIN_INFO.brNo_KeyNum.Count - 1 do
begin
if GT_BUBIN_INFO.brNo_KeyNum.Strings[i] = Rpad(sbrNo, 5, ' ') +
Rpad(StringReplace(sKeyNum, '-', '', [rfReplaceAll]), 15, ' ') then
begin
cbBCustList.Properties.Items.Add(Trim(GT_BUBIN_INFO.cbCorpNm.Strings[i]) + ' / ' +
Trim(GT_BUBIN_INFO.cbDeptNm.Strings[i]));
cbBCustListCd.Properties.Items.Add(GT_BUBIN_INFO.cbcode.Strings[i]);
end;
end;
cbBCustList.ItemIndex := 0;
end;
end else
if cxPageControl1.ActivePageIndex = 3 then
begin
if ( cbGubun4_1.ItemIndex = 3 ) Or ( chkCust04Type07.Checked ) then
begin
sBrNo := cxBrNo1.Text;
sKeyNum := cbKeynumber04.Text;
cbBCustList4.Properties.Items.Clear;
cbBCustList4Cd.Properties.Items.Clear;
cbBCustList4.Properties.Items.Add('선택');
cbBCustList4Cd.Properties.Items.Add('');
if (sBrNo = '') or (sKeyNum = '전체') then
Exit
else
begin
for i := 0 to GT_BUBIN_INFO.brNo_KeyNum.Count - 1 do
begin
if GT_BUBIN_INFO.brNo_KeyNum.Strings[i] = Rpad(sbrNo, 5, ' ') +
Rpad(StringReplace(sKeyNum, '-', '', [rfReplaceAll]), 15, ' ') then
begin
cbBCustList4.Properties.Items.Add(Trim(GT_BUBIN_INFO.cbCorpNm.Strings[i]) + ' / ' +
Trim(GT_BUBIN_INFO.cbDeptNm.Strings[i]));
cbBCustList4Cd.Properties.Items.Add(GT_BUBIN_INFO.cbcode.Strings[i]);
end;
end;
end;
cbBCustList4.ItemIndex := 0;
end;
end;
end;
procedure TFrm_CUT.proc_CustCounsel_Clear;
var
i, iRow: Integer;
ln_env: TIniFile;
sTemp: string;
Column: TcxGridDBColumn;
begin
SetDebugeWrite('proc_CustCounsel_Clear');
try
ln_env := TIniFile.Create(ENVPATHFILE);
ln_env.EraseSection('CustCounsel');
CustView1.DataController.BeginUpdate;
try
for i := 0 to CustView1.ColumnCount - 1 do
begin
Column := CustView1.Columns[i];
if Column.Tag = 0 then
Continue;
sTemp := Column.DataBinding.FieldName;
iRow := lbCustCounselTitle.Items.IndexOf(sTemp);
Column.Index := iRow;
end;
CustView1.GetColumnByFieldName('No').Index := 0;
finally
CustView1.DataController.EndUpdate;
FreeAndNil(ln_env);
end;
except
on e: Exception do
begin
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_CUT.proc_CustCounsel_Save;
var
i: Integer;
ln_envfile: TIniFile;
sTemp: string;
nShow : Integer;
begin
try
// 접속기사 그리드 컬럼이동 설정값 저장.
ln_envfile := TIniFile.Create(ENVPATHFILE);
try
nShow := 0;
ln_envfile.EraseSection('CustCounsel');
for i := 0 to CustView1.ColumnCount - 1 do
begin
if CustView1.Columns[I].Tag = 0 then //보이는 칼럼은 Tag = 1, 숨긴칼럼은 Tag = 0
Continue;
sTemp := CustView1.Columns[i].DataBinding.FieldName;
if CustView1.Columns[I].Visible then
begin
ln_envfile.WriteString('CustCounsel', IntToStr(nShow), sTemp);
Inc(nShow);
end;
end;
finally
FreeAndNil(ln_envfile);
end;
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure TFrm_CUT.proc_CustCounsel_Title;
var
i : Integer;
ln_env: TIniFile;
ShowList : TStringList;
Column: TcxGridDBColumn;
begin
ln_Env := TIniFile.Create(ENVPATHFILE);
ShowList := TStringList.Create;
try
ln_env.ReadSectionValues('CustCounsel', ShowList);
if (ShowList.Count > 0) then
begin
for I := 0 to ShowList.Count - 1 do
begin
Column := CustView1.GetColumnByFieldName(ShowList.Values[IntToStr(I)]);
if Column.Tag = 0 then
Continue;
if Assigned(Column) then
begin
Column.Index := I;
end;
end;
end else
begin
proc_CustCounsel_Clear;
end;
finally
FreeAndNil(ShowList);
FreeAndNil(ln_env);
end;
end;
procedure TFrm_CUT.proc_CustSearch(iType: Integer);
var
sWhere, sCbcode, sFBr_no: string;
ls_TxQry, ls_TxLoad, sQueryTemp: string; // XML File Load
slReceive: TStringList;
ErrCode, i: integer;
sRangeType, sTmp : string;
begin
if (GT_USERIF.LV = '10') and ((GT_SEL_BRNO.GUBUN <> '1') or (GT_SEL_BRNO.BrNo <> GT_USERIF.BR)) then
begin
GMessagebox('상담원 권한은 소속 지사만 조회할수 있습니다.', CDMSE);
Exit;
end;
if fGetChk_Search_HdBrNo('고객관리') then Exit;
if not chkSearchAdd.Checked then
begin
if CustView1.DataController.RecordCount > 0 then Exit;
end;
////////////////////////////////////////////////////////////////////////////////
// 고객>고객관리]2000건/콜센터(통합)/대표번호:16886618/최초이용기간:20100110~2010100131/SMS전체
if iType = 1 then
begin
if rbFirstUseDate01.Checked then
begin
sRangeType := rbFirstUseDate01.Caption + ':' + de_4stDate.Text + '~' + de_4edDate.Text;
end else
if rbUseDate01.Checked then
begin
sRangeType := rbUseDate01.Caption + ':' + de_5stDate.Text + '~' + de_5edDate.Text;
end else
if rbUseCnt01.Checked then
sRangeType := rbUseCnt01.Caption + ':' + edUseCnt01.Text + '~' + edUseCnt02.Text;
sRangeType := '/' + sRangeType;
end;
FExcelDownMng := Format('%s/대표번호:%s%s/%s',
[
GetSelBrInfo
, cbKeynumber01.Text
, sRangeType
, cbSmsUse01.Text
]);
////////////////////////////////////////////////////////////////////////////////
sWhere := '';
if iType = 1 then
begin
if rbFirstUseDate01.Checked then
begin
if (de_4stDate.Text <> '') and (de_4edDate.Text <> '') then
sWhere := ' AND CU.IN_DATE BETWEEN TO_DATE(''' + FormatDateTime('yyyymmdd', de_4stDate.Date) + '0900' + ''',''YYYYMMDDHH24MISS'') '
+ ' AND TO_DATE(''' + FormatDateTime('yyyymmdd', de_4edDate.Date) + '0900' + ''',''YYYYMMDDHH24MISS'') '
else if (de_4stDate.Text <> '') and (de_4edDate.Text = '') then
sWhere := ' AND CU.IN_DATE >= TO_DATE(''' + FormatDateTime('yyyymmdd', de_4stDate.Date) + '0900' + ''',''YYYYMMDDHH24MISS'') '
else if (de_4stDate.Text = '') and (de_4edDate.Text <> '') then
sWhere := ' AND TO_DATE(''' + FormatDateTime('yyyymmdd', de_4edDate.Date) + '0900' + ''',''YYYYMMDDHH24MISS'') >= CU.IN_DATE ';
end else
if rbUseDate01.Checked then
begin
if (de_5stDate.Text <> '') and (de_5edDate.Text <> '') then
sWhere := ' AND CU.CU_LAST_END BETWEEN ''' + FormatDateTime('yyyymmdd', de_5stDate.Date) + '' + ''' '
+ ' AND ''' + FormatDateTime('yyyymmdd', de_5edDate.Date) + '' + ''' '
else if (de_5stDate.Text <> '') and (de_5edDate.Text = '') then
sWhere := ' AND CU.CU_LAST_END >= ''' + FormatDateTime('yyyymmdd', de_5stDate.Date) + '' + ''' '
else if (de_5stDate.Text = '') and (de_5edDate.Text <> '') then
sWhere := ' AND ''' + FormatDateTime('yyyymmdd', de_5edDate.Date) + '' + ''' >= CU.CU_LAST_END ';
end else
if rbUseCnt01.Checked then
begin
if (edUseCnt01.Text <> '') and (edUseCnt02.Text <> '') then
sWhere := ' AND CU.CU_ENDCNT BETWEEN ' + IntToStr(StrToIntDef(edUseCnt01.Text, 0)) + ' '
+ ' AND ' + IntToStr(StrToIntDef(edUseCnt02.Text, 0)) + ' '
else if (edUseCnt01.Text <> '') and (edUseCnt02.Text = '') then
sWhere := ' AND CU.CU_ENDCNT >= ' + IntToStr(StrToIntDef(edUseCnt01.Text, 0)) + ' '
else if (edUseCnt01.Text = '') and (edUseCnt02.Text <> '') then
sWhere := ' AND ' + IntToStr(StrToIntDef(edUseCnt02.Text, 0)) + ' >= CU.CU_ENDCNT ';
end;
end;
if cxBrNo1.Text <> '' then
begin
sWhere := sWhere + ' AND CU.BR_NO = ''' + cxBrNo1.Text + ''' ';
end else
begin
if (GT_SEL_BRNO.GUBUN = '0') and (not Check_ALLHD(GT_SEL_BRNO.HDNO)) then
begin
for i := 0 to scb_FamilyBrCode.Count -1 do
begin
if i = 0 then sFBr_no := '''' + scb_FamilyBrCode[i] + '''';
sFBr_no := sFBr_no + ', ' + '''' + scb_FamilyBrCode[i] + '''';
end;
sWhere := ' AND CU.BR_NO IN (' + sFBr_no + ')';
end;
end;
if (cbKeynumber01.ItemIndex > 0) and (cbKeynumber01.Text <> '') then
sWhere := sWhere + ' AND CU.KEY_NUMBER = ''' + StringReplace(cbKeynumber01.Text, '-', '', [rfReplaceAll]) + ''' ';
case cbGubun1_1.ItemIndex of
1: sWhere := sWhere + ' AND CU.CU_TYPE = ''0'' ';
2:
begin
if chkCallBell.checked then sWhere := sWhere + ' AND CU.CU_TYPE = ''1'' ' //전체업소
else sWhere := sWhere + ' AND CU.CU_TYPE = ''1'' AND ((CU.CALLBELL_STATUS != ''1'') or (CU.CALLBELL_STATUS is null)) '; //일반업소
end;
3: sWhere := sWhere + ' AND CU.CU_TYPE = ''3'' ';
4: sWhere := sWhere + ' AND CU.CU_TYPE = ''1'' AND CU.CALLBELL_STATUS = ''1'' '; //콜벨업소
end;
if cbLevel01.ItemIndex > 0 then
sWhere := sWhere + ' AND CU.CU_LEVEL_CD = ''' + SCboLevelSeq[cbLevel01.itemindex] + ''' ';
if chkBubinCust.Checked then
sWhere := sWhere + ' AND CU.CU_TYPE != ''3'' ';
if cbOutBound1.ItemIndex > 0 then
sWhere := sWhere + ' AND CU.CU_OUTBOUND = ''' + IntToStr(cbOutBound1.ItemIndex) + ''' ';
if (cbBCustList.Enabled) and (cbBCustList.ItemIndex > 0) then
begin
sCbcode := cbBCustListCd.Properties.Items[cbBCustList.ItemIndex];
sCbcode := Copy(sCbcode, 1, Pos(',', sCbcode) - 1);
sWhere := sWhere + ' AND CU.CB_CODE = ''' + sCbcode + ''' ';
end;
if edCustName01.Text <> '' then
sWhere := sWhere + ' AND CU.CMP_NM LIKE ''%' + Param_Filtering(edCustName01.Text) + '%'' ';
if edCustTel01.Text <> '' then
begin
if Length(edCustTel01.Text) = 4 then
sWhere := sWhere +
' AND CU.CU_SEQ IN (SELECT CU_SEQ FROM CDMS_CUSTOMER_TEL WHERE substr(CU_TEL,-4) = ''' + Param_Filtering(edCustTel01.Text) + ''') '
// ' AND CU.CU_SEQ IN (SELECT CU_SEQ FROM CDMS_CUSTOMER_TEL WHERE CU_TEL LIKE, ''%' + StringReplace(edCustTel01.Text, '-', '', [rfReplaceAll]) + ''') '
else
sWhere := sWhere +
' AND CU.CU_SEQ IN (SELECT CU_SEQ FROM CDMS_CUSTOMER_TEL WHERE CU_TEL LIKE ''' + StringReplace(Param_Filtering(edCustTel01.Text), '-', '', [rfReplaceAll]) + '%'') ';
end;
if cxTextEdit17.Text <> '' then
begin
if Length(cxTextEdit17.Text) = 4 then
sWhere := sWhere
+ 'AND cu.cu_seq IN (SELECT cu_seq FROM cdms_customer_tel tel, (SELECT v_phone, c_phone FROM virtual_number_0507 '
+ 'WHERE yn_sync = ''y'' AND substr(v_phone,-4) = ''' + Param_Filtering(cxTextEdit17.Text) + ''' '
+ ' AND c_type = ''3'') vnum WHERE tel.cu_tel = vnum.c_phone) '
else
sWhere := sWhere
+ 'AND cu.cu_seq IN (SELECT cu_seq FROM cdms_customer_tel tel, (SELECT v_phone, c_phone FROM virtual_number_0507 '
+ 'WHERE yn_sync = ''y'' AND v_phone LIKE ''' + StringReplace(Param_Filtering(cxTextEdit17.Text), '-', '', [rfReplaceAll]) + '%'' '
+ ' AND c_type = ''3'') vnum WHERE tel.cu_tel = vnum.c_phone) '
end;
if cxCheckBox9.Checked then
begin
if (de_6stDate.Text <> '') and (de_6edDate.Text <> '') then
sWhere := sWhere
+ 'AND cu.cu_seq IN (SELECT cu_seq FROM cdms_customer_tel tel, '
+ ' (SELECT v_phone, c_phone FROM virtual_number_0507 WHERE yn_sync = ''y'' '
+ 'AND allot_time BETWEEN TO_DATE( ''' + CallToStr(de_6stDate.Text) + '090000' + ''', ''YYYYMMDDHH24MISS'' ) '
+ ' AND TO_DATE( ''' + CallToStr(de_6edDate.Text) + '090000' + ''', ''YYYYMMDDHH24MISS'' ) '
+ 'AND c_type = ''3'') vnum WHERE tel.cu_tel = vnum.c_phone) ';
end;
if Rb_SetupA.Checked then
begin
sWhere := sWhere + ' AND CU.CU_SEQ = APP.CU_SEQ(+) ';
end else
if Rb_SetupY.Checked then
sWhere := sWhere + ' AND CU.CU_SEQ = APP.CU_SEQ ' +
' AND CU.CU_SEQ = APP.CU_SEQ(+) ' +
' AND APP.DEL_YN = ''n'' '
else
if Rb_SetupN.Checked then
sWhere := sWhere + ' AND CU.CU_SEQ NOT IN (SELECT CU_SEQ FROM CDMS_APP_USER WHERE DEL_YN = ''n'') ' + // 미사용
' AND CU.CU_SEQ = APP.CU_SEQ(+) ';
if CB_SetDate.Checked then
begin
sWhere := sWhere + Format(' AND APP.LAST_REG_DATE BETWEEN TRUNC( TO_DATE( %s, ''yyyymmdd'' ) ) ' +
' AND TRUNC( TO_DATE( %s, ''yyyymmdd'' ) + 1 ) ', [FormatDateTime('YYYYMMDD', de_1stDate.Date), FormatDateTime('YYYYMMDD', de_1edDate.Date)] ); // 등록일자
end;
if CB_DelDate.Checked then
begin
sWhere := sWhere + Format(' AND APP.DEL_YN = ''y'' ' +
' AND APP.LAST_DEL_DATE BETWEEN TRUNC( TO_DATE( %s, ''yyyymmdd'' ) ) ' +
' AND TRUNC( TO_DATE( %s, ''yyyymmdd'' ) + 1 ) ', [FormatDateTime('YYYYMMDD', de_3stDate.Date), FormatDateTime('YYYYMMDD', de_3edDate.Date)] ); // 삭제일자
end;
if CB_UseDate.Checked then
begin
sWhere := sWhere + Format(' AND APP.LAST_FINISH_DATE BETWEEN %s ' +
' AND %s ', [FormatDateTime('YYYYMMDD', de_2stDate.Date), FormatDateTime('YYYYMMDD', de_2edDate.Date + 1)] ); // 최종일자
end;
if edCuMilet01.Text = '' then edCuMilet01.Text := '0';
if edCuMilet02.Text = '' then edCuMilet02.Text := '0';
sTmp := RemoveComma(edCuMilet01.Text);
if StrToIntDef(sTmp, 0) > 0 then
sWhere := sWhere + ' AND CU.CU_MILEAGE >= ''' + Param_Filtering(sTmp) + ''' ' ;
sTmp := RemoveComma(edCuMilet02.Text);
if StrToIntDef(sTmp, 0) > 0 then
sWhere := sWhere + ' AND CU.CU_EXPIRE_MILEAGE >= ''' + Param_Filtering(sTmp) + ''' ' ;
ls_TxLoad := GTx_UnitXmlLoad('SEL02.XML');
fGet_BlowFish_Query(GSQ_CUST_MANAGE_SEARCH, sQueryTemp);
ls_TxQry := Format(sQueryTemp, [cxHdNo1.Text, sWhere]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', En_Coding(GT_USERIF.ID), [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', self.Caption + '2', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'PagingString', '500', [rfReplaceAll]);
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
cxPageControl1.Enabled := False;
// cxGroupBox1.Enabled := False;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
Frm_Flash.Hide;
// cxGroupBox1.Enabled := True;
cxPageControl1.Enabled := True;
end;
end;
procedure TFrm_CUT.proc_Cust_PhoneSel(Aidx: integer);
var XmlData, Param, ErrMsg: string;
ErrCode: Integer;
StrList, StrList1, StrList2: TStringList;
I, j, iRow, iChk: Integer;
tmpCnt: integer;
tmpCntStr: string;
k: Integer;
tmpStr: string;
ArrSt: array of string;
sBrNo : string;
begin
Screen.Cursor := crHourGlass;
sBrNo := cxBrNo5.Text;
if ((sBrNo <> 'B811') and (sBrNo <> 'G640') and (sBrNo <> 'B100') and (sBrNo <> 'C468')) or (GS_PRJ_AREA = 'O') then
begin
ShowMessage('안심번호 설정은 신청한 지사를 선택하셔야 합니다.' + #13#10 + #13#10
+ '문의사항은 콜마너 업무게시판에 등록해 주세요.');
Screen.Cursor := crDefault;
Exit;
end;
if (cbKeynumber05.ItemIndex < 0) or (cbKeynumber05.Text = '전체') then
begin
ShowMessage('대표번호를 선택하여 주십시오.');
cbKeynumber05.SetFocus;
Screen.Cursor := crDefault;
Exit;
end;
if length(strtocall(cxTextEdit18.Text)) < 7 then
begin
ShowMessage('전화번호를 모두 입력하신 뒤 검색하여 주십시오.');
cxTextEdit18.SetFocus;
Screen.Cursor := crDefault;
Exit;
end;
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxLabel240.Caption := '';
cxLabel251.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
iRow := cxGridDBTableView1.DataController.FocusedRecordIndex;
if Aidx = 0 then Param := sBrNo
else Param := cxGridDBTableView1.DataController.Values[iRow, 10];
Param := Param + '│' + CallToStr(cxTextEdit18.Text);
if cbKeynumber05.ItemIndex > -1 then
Param := Param + '│' + CallToStr(cbKeynumber05.Text)
else
Param := Param + '│' + '│';
if not RequestBase(GetSel05('GET_CUSTOMER_INFO_VIRTUAL', 'MNG_CUST.GET_CUSTOMER_INFO_VIRTUAL', '10',Param), XmlData, ErrCode, ErrMsg) then
begin
GMessageBox(Format('[%d] %s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
StrList := TStringList.Create;
StrList1 := TStringList.Create;
StrList2 := TStringList.Create;
try
if Pos('<Data Count="',xmlData)>0 then
begin
tmpCntStr:=Copy(XmlData,Pos('<Data Count="',xmlData)+13,100);
if Pos('"',tmpCntStr)>0 then tmpCntStr:=Copy(tmpCntStr,1,Pos('"',tmpCntStr)-1);
tmpCnt:=StrToIntDef(tmpCntStr,0);
end;
if tmpCnt<1 then
begin
if Aidx = 0 then
begin
pnl5.Visible := False;
Exit;
end;
iRow := cxGridDBTableView1.DataController.FocusedRecordIndex;
if iRow > -1 then
begin
if cxBrNo5.Text <> cxGridDBTableView1.DataController.Values[iRow, 10] then
begin
pnl5.Visible := True;
cxLabel252.Caption := Format('소속 선택지사(%s, %s)', [cxBrNo5.text, scb_BranchName[ scb_BranchCode.IndexOf(cxBrNo5.Text)]
+ ' - ' + cbKeynumber05.Text]);
cxLabel253.Caption := Format('리스트 선택지사(%s, %s)', [cxGridDBTableView1.DataController.Values[iRow, 10]
, cxGridDBTableView1.DataController.Values[iRow, 6]]);
cxTextEdit20.Enabled := false;
end
else pnl5.Visible := False;
Exit;
END;
end;
if tmpCnt > 1 then
begin
ShowMessage('동일한 고객번호가 2개 이상 존재합니다.' + #13#10 + '대표번호를 확인하세요');
Exit;
end;
SetLength(ArrSt,tmpCnt);
tmpStr:=xmlData;
tmpStr:=stringreplace(tmpStr,'"','',[rfReplaceAll]);
tmpStr:=stringreplace(tmpStr,#13,'',[rfReplaceAll]);
tmpStr:=stringreplace(tmpStr,#10,'',[rfReplaceAll]);
if Pos('<Result Value=',XmlData)>0 then
tmpStr:=Copy(XmlData,Pos('<Result Value=',XmlData),Length(XmlData)-Pos('<Result Value=',XmlData)+1);
if tmpCnt>0 then
begin
cxVirtureList.DataController.SetRecordCount(0);
cxVirtureList.BeginUpdate;
iChk := 0;
for k:=0 to tmpCnt-1 do
begin
ArrSt[k]:=tmpStr;
if Pos('/>',tmpStr)>0 then
begin
ArrSt[k]:=Copy(tmpStr,1,Pos('/>',tmpStr)-1);
if Pos('<Result Value=',ArrSt[k]) > 0 then
ArrSt[k] := Copy(ArrSt[k],Pos('<Result Value=',ArrSt[k])+14,Length(ArrSt[k])-Pos('<Result Value=',ArrSt[k])+14+1);
if Pos('/>',ArrSt[k]) > 0 then
ArrSt[k] := Copy(ArrSt[k],1,Pos('/>',ArrSt[k])-1);
ArrSt[k]:=StringReplace(ArrSt[k],'"','',[rfReplaceAll]);
tmpStr:=Copy(tmpStr,Pos('/>',tmpStr)+2,Length(tmpStr)-Pos('/>',tmpStr)+2+1);
StrList.Clear;
StrList1.Clear;
GetTextSeperationEx('│', ArrSt[k], StrList);
cxLabel251.Caption := StrList.Strings[0]; //고객일련번호
cxLabel243.Caption := StrList.Strings[1]; // 고객명
cxLabel245.Caption := StrList.Strings[2]; // 이용횟수
if length(StrList.Strings[3]) = 8 then
cxLabel247.Caption := copy(StrList.Strings[3], 1,4) + '-' + copy(StrList.Strings[3], 5,2) + '-' + copy(StrList.Strings[3], 7,2) // 최종이용일자
else cxLabel247.Caption := StrList.Strings[3];
cxTextEdit20.text := StrList.Strings[4]; // 메모
GetTextSeperationEx(',', StrList.Strings[5], StrList1);
for i := 0 to StrList1.Count - 1 do
begin
StrList2.Clear;
iRow := cxVirtureList.DataController.AppendRecord;
GetTextSeperationEx(';', StrList1[i], StrList2);
cxVirtureList.DataController.Values[iRow, 0] := False;
for j := 1 to StrList2.Count do
begin
cxVirtureList.DataController.Values[iRow, j] := strtocall(StrList2[j-1]);
if StrList2[1] <> '' then
begin
cxLabel240.Caption := strtocall(StrList2[1]);
cxLabel250.Caption := strtocall(StrList2[1]);
cxVirtureList.DataController.Values[iRow, 0] := True;
iChk := 1;
end;
end;
end;
if iChk = 1 then iFlag := 2
else iFlag := 1;
end;
end;
cxVirtureList.EndUpdate;
if iChk = 0 then
begin
for iRow := 0 to cxVirtureList.DataController.RecordCount -1 do
begin
if calltostr(cxVirtureList.DataController.Values[iRow, 1]) = cxTextEdit18.text then
begin
cxVirtureList.DataController.Values[iRow, 0] := True;
end;
end;
end;
pnl5.Visible := False;
cxTextEdit20.Enabled := True;
if cxGridDBTableView1.DataController.RowCount = 0 then proc_VirtureNum;
end;
finally
StrList.Free;
StrList1.Free;
StrList2.Free;
Screen.Cursor := crDefault;
end;
end;
function TFrm_CUT.func_Cust_Search(AHdNo, ABrNo, AKeyNumber, ASeq: string):Boolean;
var
ls_TxLoad, sNode, sHdNo, sBrNo, sKeyNumber: string;
ls_rxxml: WideString;
xdom: msDOMDocument;
lst_Node: IXMLDOMNodeList;
slReceive: TStringList;
rv_str: string;
ErrCode: integer;
lst_Result: IXMLDomNodeList;
i : integer;
begin
result := False;
if StrToIntDef(ASeq, -1) = -1 then
exit;
ls_rxxml := GTx_UnitXmlLoad('C034N1.XML');
xdom := ComsDOMDocument.Create;
try
if (not xdom.loadXML(ls_rxxml)) then
begin
Screen.Cursor := crDefault;
ShowMessage('전문 Error입니다. 다시조회하여주십시요.');
Exit;
end;
sNode := '/cdms/header/UserID';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Value').Text := En_Coding(GT_USERIF.ID);
sNode := '/cdms/header/ClientVer';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Value').Text := VERSIONINFO;
sNode := '/cdms/header/ClientKey';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Value').Text := 'CUT111';
sNode := '/cdms/Service/Customers';
lst_Node := xdom.documentElement.selectNodes(sNode);
sHdNo := Trim(AHdNo);
sBrNo := Trim(ABrNo);
sKeyNumber := Trim(AKeyNumber);
lst_Node.item[0].attributes.getNamedItem('action').Text := 'SELECT';
lst_Node.item[0].attributes.getNamedItem('CuSeq').Text := Trim(ASeq);
lst_Node.item[0].attributes.getNamedItem('HdNo').Text := sHdNo;
lst_Node.item[0].attributes.getNamedItem('BrNo').Text := sBrNo;
lst_Node.item[0].attributes.getNamedItem('KeyNumber').Text := sKeyNumber;
ls_TxLoad := '<?xml version="1.0" encoding="euc-kr"?>' + #13#10 + xDom.documentElement.xml;
ls_TxLoad := StringReplace(ls_TxLoad, 'InDate=""', 'InDate="" BrTelYN="" CuEmail=""', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'CuSmsYN=""', 'CuSmsYN="" CuSmsMiDate="" CuVirtualYn="" CuVirtualTel="" CuVirtualDate=""', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'InDate=""', 'InDate="" AppCode="" AppLastRegDate="" AppLastDelDate="" AppLastFinishDate=""', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'AppLastFinishDate=""', 'AppLastFinishDate="" AppCuArea="" AppTermModel="" AppTermOS="" AppDelYn="" CuMemo=""', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'AppDelYn=""', 'AppDelYn="" AppGroup="" AppVersion=""' , [rfReplaceAll]);
slReceive := TStringList.Create;
try
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False) then
begin
rv_str := slReceive[0];
if rv_str <> '' then
begin
ls_rxxml := rv_str;
Application.ProcessMessages;
xdom := ComsDomDocument.Create;
try
if not xdom.loadXML(ls_rxxml) then Exit;
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Customers/Customer');
FCuData.CuName := lst_Result.item[0].attributes.getNamedItem('CmpNm').Text;
FCuData.CuMemo := StringReplace(lst_Result.item[0].attributes.getNamedItem('CuPdaInfo').Text, '│', '|', [rfReplaceAll]);
FCuData.CuMemo := StringReplace(FCuData.CuMemo, '|', '¶', [rfReplaceAll]);
FCuData.CuArea := lst_Result.item[0].attributes.getNamedItem('CuArea5').Text;
// 출1/시도, 출2/시군구, 출3/읍면동
FCuData.CuStart1 := lst_Result.item[0].attributes.getNamedItem('CuArea').Text;
FCuData.CuStart2 := lst_Result.item[0].attributes.getNamedItem('CuArea2').Text;
FCuData.CuStart3 := lst_Result.item[0].attributes.getNamedItem('CuArea3').Text;
FCuData.CuAreaDetail := lst_Result.item[0].attributes.getNamedItem('CuArea4').Text;
FCuData.CuXval := lst_Result.item[0].attributes.getNamedItem('CuMapX').Text;
FCuData.CuYVal := lst_Result.item[0].attributes.getNamedItem('CuMapY').Text;
FCuData.CuTelList := '';
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Customers/TelNums');
if lst_Result.length > 0 then
begin
for i := 0 to lst_Result.length - 1 do
begin
if i = 0 then
FCuData.CuTelList := strtocall(lst_Result.item[i].attributes.getNamedItem('CuTel').Text)
else
FCuData.CuTelList := FCuData.CuTelList + '|' + strtocall(lst_Result.item[i].attributes.getNamedItem('CuTel').Text);
end;
end;
finally
result := True;
end;
end;
end;
finally
Frm_Flash.Hide;
FreeAndNil(slReceive);
end;
finally
xdom := Nil;
end;
end;
procedure TFrm_CUT.proc_DetailSearch;
var
ls_TxLoad, sWhere, sTemp, sTel1, sTel2, sCbcode: string;
slReceive: TStringList;
ErrCode: integer;
sms_use1, sms_use2: string;
sExcelAdd: string;
begin
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) >
2100) or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
if (GT_USERIF.LV = '10') and ((GT_SEL_BRNO.GUBUN <> '1') or (GT_SEL_BRNO.BrNo <> GT_USERIF.BR)) then
begin
GMessagebox('상담원 권한은 소속 지사만 조회할수 있습니다.', CDMSE);
Exit;
end;
if fGetChk_Search_HdBrNo('상세검색') then Exit;
if not chkCust04Type08.Checked then
begin
if CustView4.DataController.RecordCount > 0 then
Exit;
end;
//////////////////////////////////////////////////////////////////////////////
// 고객>상세검색]2000건/콜센터(통합)/대표번호:16886618/최종이용기간:XX~XX/신규등록기간:XX~XX/완료:0~10/취소:0~20/SMS수신
sExcelAdd := '';
if chkCust04Type01.Checked then
sExcelAdd := sExcelAdd + chkCust04Type01.Caption + ':' + cxDate4_1S.Text + '~' + cxDate4_1E.Text + '/';
if chkCust04Type02.Checked then
sExcelAdd := sExcelAdd + chkCust04Type02.Caption + ':' + cxDate4_2S.Text + '~' + cxDate4_2E.Text + '/';
if chkCust04Type09.Checked then
sExcelAdd := sExcelAdd + chkCust04Type09.Caption + ':' + cxDate4_3S.Text + '~' + cxDate4_3E.Text + '/';
if chkCust04Type04.Checked then
sExcelAdd := sExcelAdd + chkCust04Type04.Caption + ':' + edCust04Type01.Text + '~' + edCust04Type02.Text + '/';
if chkCust04Type05.Checked then
sExcelAdd := sExcelAdd + chkCust04Type05.Caption + ':' + edCust04Type03.Text + '~' + edCust04Type04.Text + '/';
FExcelDownDetail := Format('%s/대표번호:%s/%s%s',
[
GetSelBrInfo
, cbKeynumber04.Text
, sExcelAdd
, cbSmsUse04.Text
]);
//////////////////////////////////////////////////////////////////////////////
sWhere := '';
if cbCustLastNumber4.ItemIndex = 0 then
begin
sTel1 := '0000';
sTel2 := '9999';
end else
if (cbCustLastNumber4.ItemIndex > 0) then
begin
sTemp := cbCustLastNumber4.Text;
sTel1 := Copy(sTemp, 1, 4);
sTel2 := Copy(sTemp, 6, 4);
sWhere := sWhere + ' AND EXISTS (SELECT * FROM CDMS_CUSTOMER_TEL WHERE CU_SEQ = C.CU_SEQ AND SUBSTR(CU_TEL, LENGTH(CU_TEL)-3) BETWEEN '''
+ sTel1 + ''' AND ''' + sTel2 + ''') '
end;
if cxBrNo4.Text <> '' then
sWhere := sWhere + ' AND C.BR_NO = ''' + cxBrNo4.Text + ''' ';
FDetailKeyNum := '';
if (cbKeynumber04.Text <> '전체') and (cbKeynumber04.Text <> '') then
begin
sWhere := sWhere + ' AND C.KEY_NUMBER = ''' + StringReplace(cbKeynumber04.Text, '-', '', [rfReplaceAll]) + ''' ';
FDetailKeyNum := StringReplace(cbKeynumber04.Text, '-', '', [rfReplaceAll]);
end;
case cbGubun4_1.ItemIndex of
1: sWhere := sWhere + ' AND C.CU_TYPE = ''0'' ';
2: sWhere := sWhere + ' AND C.CU_TYPE = ''1'' ';
3: sWhere := sWhere + ' AND C.CU_TYPE = ''3'' ';
end;
// [hjf]
case cbSmsUse04.ItemIndex of
1:
begin
sms_use1 := 'y';
sms_use2 := '0';
end;
2:
begin
sms_use1 := '0';
sms_use2 := 'n';
end;
else
begin
sms_use1 := 'y';
sms_use2 := 'n';
end;
end;
if cbLevel04.ItemIndex > 0 then
sWhere := sWhere + ' AND C.CU_LEVEL_CD = ''' + SCboLevelSeq[cbLevel04.itemindex] + ''' ';
if cbOutBound4.ItemIndex > 0 then
sWhere := sWhere + ' AND C.CU_OUTBOUND = ''' + IntToStr(cbOutBound4.ItemIndex) + ''' ';
if chkCust04Type06.Checked then
sWhere := sWhere + ' AND C.CU_TYPE != ''3'' ';
if (chkCust04Type07.Checked) and (cbBCustList4.Enabled) and (cbBCustList4.ItemIndex > 0) then
begin
sCbcode := cbBCustList4Cd.Properties.Items[cbBCustList4.ItemIndex];
sCbcode := Copy(sCbcode, 1, Pos(',', sCbcode) - 1);
sWhere := sWhere + ' AND C.CB_CODE = ''' + sCbcode + ''' ';
end;
if chkCust04Type01.Checked then
begin
if cxDate4_1S.Enabled then
begin
if (cxDate4_1S.Text <> '') and (cxDate4_1E.Text <> '') then
sWhere := sWhere + Format(' AND C.CU_LAST_END BETWEEN ''%s'' AND ''%s'' ' , [formatdatetime('yyyymmdd', cxDate4_1S.Date),
Formatdatetime('yyyymmdd', cxDate4_1E.Date)])
else
if (cxDate4_1S.Text <> '') and (cxDate4_1E.Text = '') then
sWhere := sWhere + Format(' AND C.CU_LAST_END >= ''%s'' ', [formatdatetime('yyyymmdd', cxDate4_1S.Date)])
else
if (cxDate4_1S.Text = '') and (cxDate4_1E.Text <> '') then
sWhere := sWhere + Format(' AND ''%s'' >= C.CU_LAST_END ', [formatdatetime('yyyymmdd', cxDate4_1E.Date)]);
end;
end;
if chkCust04Type02.Checked then
begin
if cxDate4_2S.Enabled then
begin
if (cxDate4_2S.Text <> '') and (cxDate4_2E.Text <> '') then
sWhere := sWhere + Format(' AND C.IN_DATE BETWEEN TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') AND TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') '
, [Formatdatetime('yyyymmdd', cxDate4_2S.Date), Formatdatetime('yyyymmdd', cxDate4_2E.Date)])
else
if (cxDate4_2S.Text <> '') and (cxDate4_2E.Text = '') then
sWhere := sWhere +
format(' AND C.IN_DATE >= TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') ', [formatdatetime('yyyymmdd', cxDate4_2S.Date)])
else
if (cxDate4_2S.Text = '') and (cxDate4_2E.Text <> '') then
sWhere := sWhere +
format(' AND TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') >= C.IN_DATE ', [formatdatetime('yyyymmdd', cxDate4_2E.Date)]);
end;
end;
if chkCust04Type03.Checked then
begin
if rbCust04Type01.Checked then
begin
if (cbArea03.Text <> '지역전체') and (cbArea04.ItemIndex > 0) then
sWhere := sWhere + Format(' AND C.CU_AREA = ''%s'' AND C.CU_AREA2 = ''%s'' ', [cbArea03.Text, cbArea04.Text])
else
if (cbArea03.Text <> '지역전체') and (cbArea04.ItemIndex < 1) then
sWhere := sWhere + Format(' AND C.CU_AREA = ''%s'' ', [cbArea03.Text]);
end else
if rbCust04Type02.Checked then
begin
if (cbArea03.Text <> '지역전체') and (cbArea04.ItemIndex > 0) then
sWhere := sWhere + Format(' AND C.CU_EDAREA = ''%s'' AND C.CU_EDAREA2 = ''%s'' ', [cbArea03.Text, cbArea04.Text])
else if (cbArea03.Text <> '지역전체') and (cbArea04.ItemIndex < 1) then
sWhere := sWhere + Format(' AND C.CU_EDAREA = ''%s'' ', [cbArea03.Text]);
end;
end;
if chkCust04Type09.Checked then
begin
if chkCust04Type04.Checked then
begin
if (StrToIntDef(edCust04Type01.Text, -1) > -1) and (StrToIntDef(edCust04Type02.Text, -1) > -1) then
sWhere := sWhere + ' AND A01.CU_ENDCNT BETWEEN ''' + edCust04Type01.Text + ''' AND ''' + edCust04Type02.Text + ''' '
else if (StrToIntDef(edCust04Type01.Text, -1) > -1) and (StrToIntDef(edCust04Type02.Text, -1) = -1) then
sWhere := sWhere + ' AND A01.CU_ENDCNT >= ''' + edCust04Type01.Text + ''' '
else if (StrToIntDef(edCust04Type01.Text, -1) = -1) and (StrToIntDef(edCust04Type02.Text, -1) > -1) then
sWhere := sWhere + ' AND ''' + edCust04Type02.Text + ''' >= A01.CU_ENDCNT ';
end;
if chkCust04Type05.Checked then
begin
if (StrToIntDef(edCust04Type03.Text, -1) > -1) and (StrToIntDef(edCust04Type04.Text, -1) > -1) then
sWhere := sWhere + ' AND A01.CU_CANCELCNT BETWEEN ''' + edCust04Type03.Text + ''' AND ''' + edCust04Type04.Text + ''' '
else if (StrToIntDef(edCust04Type03.Text, -1) > -1) and (StrToIntDef(edCust04Type04.Text, -1) = -1) then
sWhere := sWhere + ' AND A01.CU_CANCELCNT >= ''' + edCust04Type03.Text + ''' '
else if (StrToIntDef(edCust04Type03.Text, -1) = -1) and (StrToIntDef(edCust04Type04.Text, -1) > -1) then
sWhere := sWhere + ' AND ''' + edCust04Type04.Text + ''' >= A01.CU_CANCELCNT ';
end;
end;
if (chkCust04Type04.Checked) and (not chkCust04Type09.Checked) then
begin
if (StrToIntDef(edCust04Type01.Text, -1) > -1) and
(StrToIntDef(edCust04Type02.Text, -1) > -1) then
sWhere := sWhere + ' AND C.CU_ENDCNT BETWEEN ''' + edCust04Type01.Text + ''' AND ''' + edCust04Type02.Text + ''' '
else if (StrToIntDef(edCust04Type01.Text, -1) > -1) and
(StrToIntDef(edCust04Type02.Text, -1) = -1) then
sWhere := sWhere + ' AND C.CU_ENDCNT >= ''' + edCust04Type01.Text + ''' '
else if (StrToIntDef(edCust04Type01.Text, -1) = -1) and
(StrToIntDef(edCust04Type02.Text, -1) > -1) then
sWhere := sWhere + ' AND ''' + edCust04Type02.Text + ''' >= C.CU_ENDCNT ';
end;
if (chkCust04Type05.Checked) and (not chkCust04Type09.Checked) then
begin
if (StrToIntDef(edCust04Type03.Text, -1) > -1) and (StrToIntDef(edCust04Type04.Text, -1) > -1) then
sWhere := sWhere + ' AND C.CU_CANCELCNT BETWEEN ''' + edCust04Type03.Text + ''' AND ''' + edCust04Type04.Text + ''' '
else if (StrToIntDef(edCust04Type03.Text, -1) > -1) and (StrToIntDef(edCust04Type04.Text, -1) = -1) then
sWhere := sWhere + ' AND C.CU_CANCELCNT >= ''' + edCust04Type03.Text + ''' '
else if (StrToIntDef(edCust04Type03.Text, -1) = -1) and (StrToIntDef(edCust04Type04.Text, -1) > -1) then
sWhere := sWhere + ' AND ''' + edCust04Type04.Text + ''' >= C.CU_CANCELCNT ';
end;
// 저장된 쿼리가 select ~~ from (select ~ from where [condition] 형식으로 저장되어 있음(우괄호 반드시 필요)
if edtCuEmail.Text <> '' then sWhere := sWhere + 'AND C.CU_EMAIL Like ''%' + Param_Filtering(edtCuEmail.Text) + '%'' ';
sWhere := sWhere + ')';
if chkCust04Type09.Checked then
ls_TxLoad := GetSel04(self.Caption + '7', 'CUSTOMER25', '', sWhere, [sTel1, sTel2, sms_use1, sms_use2, cxHdNo4.Text,
formatdatetime('yyyymmdd', cxDate4_3S.Date), formatdatetime('yyyymmdd', cxDate4_3E.Date), cxHdNo4.Text])
else
ls_TxLoad := GetSel04(self.Caption + '7', 'CUSTOMER21', '', sWhere, [sTel1, sTel2, sms_use1, sms_use2, cxHdNo4.Text]);
Screen.Cursor := crHourGlass;
cxPageControl1.Enabled := False;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
cxPageControl1.Enabled := True;
Frm_Flash.Hide;
end;
end;
procedure TFrm_CUT.proc_EventCnt_Init(iGuBun: Integer);
var
msg, sBrNo, sBrName, Param, sHdNo : string;
XmlData, ErrMsg: string;
ErrCode : Integer;
begin
try
sHdNo := cxHdNo8.Text;
sBrNo := cxBrNo8.Text;
if ((Formatdatetime('hhmm', Now) >= '2100') or (Formatdatetime('hhmm', Now) <= '0200')) then
begin
GMessagebox('오후 9시부터 오전 2시에는 이벤트 초기화를 할수 없습니다.', CDMSE);
Exit;
end;
if sBrNo = '' then
begin
GMessagebox('마일리지 설정은 지사를 선택하셔야 합니다.', CDMSE);
proc_init_mileage;
Exit;
end;
if (GT_USERIF.LV = '10') and (not IsPassedManagementCu(sBrNo)) then
begin
msg := '[%s(%s)] 지사에서 고객관련 관리권한 이관(콜센터 상담원)을 설정 하지 않았습니다.'
+ #13#10'(해당 지사관리자에게 관리권한 이관[회사>지사관리>상세설정]을 요청바랍니다.)';
sBrName := GetBrName(sBrNo);
GMessagebox(Format(msg, [sBrNo, sBrName]), CDMSE);
proc_init_mileage;
Exit;
end;
if fGetChk_Search_HdBrNo('마일리지설정') then Exit;
if GMessagebox('이벤트 횟수가 전체 초기화 됩니다.' + #13#10 +
'초기화 하시겠습니까?', CDMSQ) <> idok then Exit;
Param := sHdNo + '│' + sBrNo + '│' + IntToStr(iGubun);
if not RequestBase(GetCallable05('SET_BRANCH_EVENT_INIT', 'MNG_CUST.SET_BRANCH_EVENT_INIT', Param), XmlData, ErrCode, ErrMsg) then
begin
GMessagebox(Format('마일리지 설정 이벤트 횟수 초기화 중 오류발생'#13#10'[%d]%s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
GMessagebox('이벤트 횟수 초기화 완료 되었습니다.', CDMSI);
except
on e: exception do
begin
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_CUT.proc_GeneralSearch;
var
ls_TxQry, ls_TxLoad, sQueryTemp: string;
lg_sWhere, sBrNo, sClientKey: string;
sCGubun, sCName, sCTel, sCmemo, sSql: string;
slReceive: TStringList;
ErrCode: integer;
begin
if (GT_USERIF.LV = '10') and ((GT_SEL_BRNO.GUBUN <> '1') or (GT_SEL_BRNO.BrNo <> GT_USERIF.BR)) then
begin
GMessagebox('상담원 권한은 소속 지사만 조회할수 있습니다.', CDMSE);
Exit;
end;
if fGetChk_Search_HdBrNo('일반검색') then Exit;
if not chkCust02Type04.Checked then
begin
if CustView2.DataController.RecordCount > 0 then
Exit;
end;
//////////////////////////////////////////////////////////////////////////////
// 고객>일반검색]2000건/콜센터(통합)/이용내역/대표번호:16886618/기간:20100101~20100131/완료:1~10/취소:1~10/SMS전체
FExcelDownNormal := Format('%s/구분:%s/대표번호:%s/기간:%s~%s%s%s/%s',
[
GetSelBrInfo
, IfThen(rbAll01.Checked, '전체', IfThen(rbNew01.Checked, '신규등록', '이용내역'))
, cbKeynumber02.Text
, cxDate2_1S.Text, cxDate2_1E.Text
, IfThen(cb_S_Cnt1.Text + cb_S_Cnt2.Text = '', '', Format('/완료:%s~%s', [cb_S_Cnt1.Text, cb_S_Cnt2.Text]))
, IfThen(cb_S_CCnt1.Text + cb_S_CCnt2.Text = '', '', Format('/취소:%s~%s', [cb_S_CCnt1.Text, cb_S_CCnt2.Text]))
, cb_Sms_Gubun.Text
]);
//////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
// 전일이용고객
//------------------------------------------------------------------------------
if chk_Before.Checked then
proc_before_his
//------------------------------------------------------------------------------
// 전일완료고객
//------------------------------------------------------------------------------
else if chk_Before_Finish.Checked then
proc_before_comp
//------------------------------------------------------------------------------
// 전일 신규고객
//------------------------------------------------------------------------------
else if chk_Before_New.Checked then
proc_before_new
else
begin
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) >
2100) or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
lb_st_customer.Clear;
sBrNo := cxBrNo2.Text;
chk_All_Select.Checked := False;
chk_All_Select.OnClick(chk_All_Select);
lg_swhere := '';
if rg_SType.Tag in [0, 1] then
begin
if sBrNo <> '' then
lg_sWhere := Format(' AND A.HD_NO = ''%s'' AND A.BR_NO = ''%s'' ', [cxHdNo2.Text, sBrNo])
else
lg_sWhere := Format(' AND A.HD_NO = ''%s'' ', [cxHdNo2.Text]);
sCGubun := 'A.CU_TYPE';
sCName := 'A.CMP_NM';
sCTel := 'B.CU_TEL';
sCmemo := 'A.CU_INFO';
sClientKey := Self.Caption + '3';
fGet_BlowFish_Query(GSQ_CUSTOMER_LIST, sQueryTemp);
sSql := sQueryTemp;
if StrToIntDef(Trim(cb_S_Cnt1.Text), -1) > -1 then
lg_sWhere := lg_sWhere + format(' AND (A.CU_ENDCNT >= %s) ', [Trim(cb_S_Cnt1.Text)]);
if StrToIntDef(Trim(cb_S_Cnt2.Text), -1) > -1 then
lg_sWhere := lg_sWhere + format(' AND (%s >= A.CU_ENDCNT) ', [Trim(cb_S_Cnt2.Text)]);
if StrToIntDef(Trim(cb_S_CCnt1.Text), -1) > -1 then
lg_sWhere := lg_sWhere + format(' AND (A.CU_CANCELCNT >= %s) ', [Trim(cb_S_CCnt1.Text)]);
if StrToIntDef(Trim(cb_S_CCnt2.Text), -1) > -1 then
lg_sWhere := lg_sWhere + format(' AND (%s >= A.CU_CANCELCNT) ', [Trim(cb_S_CCnt2.Text)]);
if cb_S_Grad.ItemIndex > 0 then
lg_sWhere := lg_sWhere + ' AND A.CU_LEVEL_CD = ''' + SCboLevelSeq[cb_S_Grad.itemindex] + ''' ';
if cb_Sms_Gubun.ItemIndex = 1 then
lg_sWhere := lg_sWhere + ' AND (B.CU_SMSYN = ''y'') '
else if cb_Sms_Gubun.ItemIndex = 2 then
lg_sWhere := lg_sWhere + ' AND (B.CU_SMSYN = ''n'') ';
if cbOutBound1.ItemIndex > 0 then
lg_sWhere := lg_sWhere + ' AND A.CU_OUTBOUND = ''' + IntToStr(cbOutBound1.ItemIndex) + ''' ';
end else
if rg_SType.Tag = 2 then
begin
if sBrNo <> '' then
lg_sWhere := Format(' AND A.CONF_HEAD = ''%s'' AND A.CONF_BRCH = ''%s'' ', [cxHdNo2.Text, sBrNo])
else
lg_sWhere := Format(' AND A.CONF_HEAD = ''%s'' ', [cxHdNo2.Text]);
sCGubun := 'A.CONF_BAR';
sCName := 'A.CONF_USER';
sCTel := 'A.CONF_CUST_TEL';
sCmemo := 'A.CONF_MEMO';
sClientKey := Self.Caption + '4';
fGet_BlowFish_Query(GSQ_HISTORY_LIST, sQueryTemp);
sSql := sQueryTemp;
if cb_Sms_Gubun.ItemIndex > 0 then
begin
if (sg_notsms_list.DataController.RecordCount > 0) and
(sg_notsms_list.DataController.Values[0, 0] <> sBrno) then
proc_NotSMS(sBrNo);
end;
if rrb_st_comp.Checked then
lg_sWhere := lg_sWhere + ' AND A.CONF_STATUS = ''2'' '
else
lg_sWhere := lg_sWhere + ' AND A.CONF_STATUS IN (''2'', ''4'', ''8'') ';
if (cb_st_city.Text <> '지역전체') and (cb_st_ward.ItemIndex > 0) then
lg_sWhere := lg_sWhere + Format(' AND A.CONF_AREA = ''%s'' AND A.CONF_AREA2 = ''%s'' ', [cb_st_city.Text, cb_st_ward.Text])
else if (cb_st_city.Text <> '지역전체') and (cb_st_ward.ItemIndex < 1) then
lg_sWhere := lg_sWhere + Format(' AND A.CONF_AREA = ''%s'' ', [cb_st_city.Text]);
if cb_S_Grad.ItemIndex > 0 then
lg_sWhere := lg_sWhere + ' AND CU.CU_LEVEL_CD = ''' + SCboLevelSeq[cb_S_Grad.itemindex] + ''' ';
if cbOutBound1.ItemIndex > 0 then
lg_sWhere := lg_sWhere + ' AND CU.CU_OUTBOUND = ''' + IntToStr(cbOutBound1.ItemIndex) + ''' ';
if StrToIntDef(Trim(cb_S_Cnt1.Text), -1) > -1 then
lg_sWhere := lg_sWhere + format(' AND (A.USE_COUNT >= %s) ', [Trim(cb_S_Cnt1.Text)]);
if StrToIntDef(Trim(cb_S_Cnt2.Text), -1) > -1 then
lg_sWhere := lg_sWhere + format(' AND (%s >= A.USE_COUNT) ', [Trim(cb_S_Cnt2.Text)]);
end;
if (cbKeynumber02.Text <> '전체') and (cbKeynumber02.Text <> '') then
lg_sWhere := lg_sWhere + format(' AND (A.KEY_NUMBER = ''%s'') ', [StringReplace(cbKeynumber02.Text, '-', '', [rfReplaceAll])]);
if cxDate2_1S.Enabled then
begin
if (cxDate2_1S.Text <> '') and (cxDate2_1E.Text <> '') then
lg_sWhere := lg_sWhere + format(' AND A.IN_DATE BETWEEN TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') AND TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') '
, [formatdatetime('yyyymmdd', cxDate2_1S.Date), formatdatetime('yyyymmdd', cxDate2_1E.Date)])
else
if (cxDate2_1S.Text <> '') and (cxDate2_1E.Text = '') then
lg_sWhere := lg_sWhere + format(' AND A.IN_DATE >= TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') '
, [formatdatetime('yyyymmdd', cxDate2_1S.Date)])
else
if (cxDate2_1S.Text = '') and (cxDate2_1E.Text <> '') then
lg_sWhere := lg_sWhere + format(' AND TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') >= A.IN_DATE '
, [formatdatetime('yyyymmdd', cxDate2_1E.Date)]);
end;
case cbGubun2_1.ItemIndex of
1: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''0'' ';
2: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''1'' ';
3: lg_sWhere := lg_sWhere + ' AND ' + sCGubun + ' = ''3'' ';
end;
if Trim(edCustMemo01.Text) <> '' then
lg_sWhere := lg_sWhere + format(' AND (%s LIKE ''%s'' || ''%s'' || ''%s'') ', [sCmemo, '%',
trim(Param_Filtering(edCustMemo01.Text)), '%']);
if trim(edCustName02.Text) <> '' then
lg_sWhere := lg_sWhere + format(' AND (%s LIKE ''%s'' || ''%s'') ', [sCName, trim(Param_Filtering(edCustName02.Text)), '%']);
if trim(edCustTel02.Text) <> '' then
lg_sWhere := lg_sWhere + format(' AND (%s LIKE ''%s'' || ''%s'' || ''%s'') ', [sCTel, '%',
trim(StringReplace(Param_Filtering(edCustTel02.Text), '-', '', [rfReplaceAll])), '%']);
ls_TxQry := Format(sSql, [lg_sWhere]);
ls_TxLoad := GTx_UnitXmlLoad('SEL02.XML');
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', GT_USERIF.ID, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', sClientKey, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'PagingString', '5000', [rfReplaceAll]);
cxPageControl1.Enabled := False;
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
cxPageControl1.Enabled := True;
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
end;
end;
procedure TFrm_CUT.proc_HighSearch;
var
ls_TxLoad, sWhere, sTemp, sSms1, sSms2, sTel1, sTel2: string;
slReceive: TStringList;
ErrCode: integer;
MileType: string;
begin
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) >
2100) or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
if (GT_USERIF.LV = '10') and ((GT_SEL_BRNO.GUBUN <> '1') or (GT_SEL_BRNO.BrNo <> GT_USERIF.BR)) then
begin
GMessagebox('상담원 권한은 소속 지사만 조회할수 있습니다.', CDMSE);
Exit;
end;
if fGetChk_Search_HdBrNo('고급검색') then Exit;
if not chkCust03Type04.Checked then
begin
if CustView3.DataController.RecordCount > 0 then
Exit;
end;
//////////////////////////////////////////////////////////////////////////////
// 고객>고급검색]2000건/콜센터(통합)/대표번호:16886618/전체기간/마일리지:10~100점,1~3회지급/SMS수신
if rbCust03Type03.Checked then
begin
if edMlgScore01.Text + edMlgScore02.Text + edMlgCount01.Text + edMlgCount02.Text = '' then
MileType := ''
else
MileType := '/마일리지:'
+ IfThen(edMlgScore01.Text + edMlgScore02.Text = '', '', Format('%s~%s점', [edMlgScore01.Text, edMlgScore02.Text]))
+ IfThen(edMlgCount01.Text + edMlgCount02.Text = '', '', Format('%s~%s회지급', [edMlgCount01.Text, edMlgCount02.Text]))
;
end;
FExcelDownHigh := Format('%s/대표번호:%s/%s%s/%s',
[
GetSelBrInfo
, cbKeynumber03.Text
, IfThen(rbCust03Type01.Checked, '전체기간', Format('최초등록시간:%s~%s', [cxDate3_1S.Text, cxDate3_1E.Text]))
, IfThen(rbCust03Type04.Checked,
Format('전화뒷자리:%s', [cbCustLastNumber.Text]),
MileType)
, cbSmsUse03.Text
]);
//////////////////////////////////////////////////////////////////////////////
if cbSmsUse03.ItemIndex = 0 then
begin
sSms1 := 'y';
sSms2 := 'n';
end else
if cbSmsUse03.ItemIndex = 1 then
begin
sSms1 := 'y';
sSms2 := '0';
end else
begin
sSms1 := 'n';
sSms2 := '0';
end;
sWhere := '';
if cbCustLastNumber.ItemIndex = 0 then
begin
sTel1 := '0000';
sTel2 := '9999';
end else
if (rbCust03Type04.Checked) and (cbCustLastNumber.ItemIndex > 0) then
begin
sTemp := cbCustLastNumber.Text;
sTel1 := Copy(sTemp, 1, 4);
sTel2 := Copy(sTemp, 6, 4);
sWhere := sWhere +
' AND EXISTS (SELECT * FROM CDMS_CUSTOMER_TEL WHERE CU_SEQ = C.CU_SEQ AND SUBSTR(CU_TEL, LENGTH(CU_TEL)-3) BETWEEN ''' + sTel1
+ ''' AND ''' + sTel2 + ''') '
end;
if cxBrNo3.Text <> '' then
sWhere := sWhere + ' AND C.BR_NO = ''' + cxBrNo3.Text + ''' ';
if (cbKeynumber03.Text <> '전체') and (cbKeynumber03.Text <> '') then
sWhere := sWhere + ' AND C.KEY_NUMBER = ''' + StringReplace(cbKeynumber03.Text, '-', '', [rfReplaceAll]) + ''' ';
case cbGubun3_1.ItemIndex of
1: sWhere := sWhere + ' AND C.CU_TYPE = ''0'' ';
2: sWhere := sWhere + ' AND C.CU_TYPE = ''1'' ';
3: sWhere := sWhere + ' AND C.CU_TYPE = ''3'' ';
end;
if rbCust03Type02.Checked then
begin
if cxDate3_1S.Enabled then
begin
if (cxDate3_1S.Text <> '') and (cxDate3_1E.Text <> '') then
sWhere := sWhere +
format(' AND C.IN_DATE BETWEEN TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') AND TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') '
, [formatdatetime('yyyymmdd', cxDate3_1S.Date), formatdatetime('yyyymmdd', cxDate3_1E.Date)])
else
if (cxDate3_1S.Text <> '') and (cxDate3_1E.Text = '') then
sWhere := sWhere + format(' AND C.IN_DATE >= TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') '
, [formatdatetime('yyyymmdd', cxDate3_1S.Date)])
else
if (cxDate3_1S.Text = '') and (cxDate3_1E.Text <> '') then
sWhere := sWhere + format(' AND TO_DATE(''%s090000'', ''YYYYMMDDHH24MISS'') >= C.IN_DATE '
, [formatdatetime('yyyymmdd', cxDate3_1E.Date)]);
end;
end else
if rbCust03Type03.Checked then
begin
if (StrToIntDef(edMlgScore01.Text, -1) > -1) and
(StrToIntDef(edMlgScore02.Text, -1) > -1) then
sWhere := sWhere + ' AND C.CU_MILEAGE BETWEEN ''' + Param_Filtering(edMlgScore01.Text) + ''' AND ''' + Param_Filtering(edMlgScore02.Text) + ''' '
else if (StrToIntDef(edMlgScore01.Text, -1) > -1) and
(StrToIntDef(edMlgScore02.Text, -1) = -1) then
sWhere := sWhere + ' AND C.CU_MILEAGE >= ''' + Param_Filtering(edMlgScore01.Text) + ''' '
else if (StrToIntDef(edMlgScore01.Text, -1) = -1) and
(StrToIntDef(edMlgScore02.Text, -1) > -1) then
sWhere := sWhere + ' AND ''' + Param_Filtering(edMlgScore02.Text) + ''' >= C.CU_MILEAGE ';
if (StrToIntDef(edMlgCount01.Text, -1) > -1) and
(StrToIntDef(edMlgCount02.Text, -1) > -1) then
sWhere := sWhere + ' AND C.CU_PRIZE_CNT BETWEEN ''' + Param_Filtering(edMlgCount01.Text) + ''' AND ''' + Param_Filtering(edMlgCount02.Text) + ''' '
else if (StrToIntDef(edMlgScore01.Text, -1) > -1) and
(StrToIntDef(edMlgScore02.Text, -1) = -1) then
sWhere := sWhere + ' AND C.CU_PRIZE_CNT >= ''' + Param_Filtering(edMlgCount01.Text) + ''' '
else if (StrToIntDef(edMlgCount01.Text, -1) = -1) and (StrToIntDef(edMlgCount02.Text, -1) > -1) then
sWhere := sWhere + ' AND ''' + Param_Filtering(edMlgCount02.Text) + ''' >= C.CU_PRIZE_CNT ';
if (StrToIntDef(edMlgLost01.Text, -1) > -1) and (StrToIntDef(edMlgLost02.Text, -1) > -1) then
sWhere := sWhere + ' AND C.CU_EXPIRE_MILEAGE BETWEEN ''' + Param_Filtering(edMlgLost01.Text) + ''' AND ''' + Param_Filtering(edMlgLost02.Text) + ''' '
else if (StrToIntDef(edMlgLost01.Text, -1) > -1) and (StrToIntDef(edMlgLost02.Text, -1) = -1) then
sWhere := sWhere + ' AND C.CU_EXPIRE_MILEAGE >= ''' + Param_Filtering(edMlgLost01.Text) + ''' '
else if (StrToIntDef(edMlgLost01.Text, -1) = -1) and (StrToIntDef(edMlgLost02.Text, -1) > -1) then
sWhere := sWhere + ' AND ''' + Param_Filtering(edMlgLost02.Text) + ''' >= C.CU_EXPIRE_MILEAGE ';
end;
if rbCust03Type05.Checked then
begin
sWhere := sWhere + ' AND C.CU_SEQ = APP.CU_SEQ(+) ';
end else
if rbCust03Type06.Checked then
sWhere := sWhere + ' AND C.CU_SEQ = APP.CU_SEQ ' +
' AND C.CU_SEQ = APP.CU_SEQ(+) ' +
' AND APP.DEL_YN = ''n'' '
else
if rbCust03Type07.Checked then
sWhere := sWhere + ' AND C.CU_SEQ NOT IN (SELECT CU_SEQ FROM CDMS_APP_USER WHERE DEL_YN = ''n'') ' + // 미사용
' AND C.CU_SEQ = APP.CU_SEQ(+) ';
if cbOutBound3.ItemIndex > 0 then
sWhere := sWhere + ' AND C.CU_OUTBOUND = ''' + IntToStr(cbOutBound3.ItemIndex) + ''' ';
if chkCust03Type01.Checked then
begin
sWhere := sWhere + Format(' AND APP.LAST_REG_DATE BETWEEN TRUNC( TO_DATE( %s, ''yyyymmdd'' ) ) ' +
' AND TRUNC( TO_DATE( %s, ''yyyymmdd'' ) + 1 ) ', [FormatDateTime('YYYYMMDD', de_A31stDate.Date), FormatDateTime('YYYYMMDD', de_A31edDate.Date)] ); // 등록일자
end;
if chkCust03Type02.Checked then
begin
sWhere := sWhere + Format(' AND APP.DEL_YN = ''y'' ' +
' AND APP.LAST_DEL_DATE BETWEEN TRUNC( TO_DATE( %s, ''yyyymmdd'' ) ) ' +
' AND TRUNC( TO_DATE( %s, ''yyyymmdd'' ) + 1 ) ', [FormatDateTime('YYYYMMDD', de_A33stDate.Date), FormatDateTime('YYYYMMDD', de_A33edDate.Date)] ); // 삭제일자
end;
if chkCust03Type03.Checked then
begin
sWhere := sWhere + Format(' AND APP.LAST_FINISH_DATE BETWEEN TRUNC( TO_DATE( %s, ''yyyymmdd'' ) ) ' +
' AND TRUNC( TO_DATE( %s, ''yyyymmdd'' ) + 1 ) ', [FormatDateTime('YYYYMMDD', de_A32stDate.Date), FormatDateTime('YYYYMMDD', de_A32edDate.Date)] ); // 최종일자
end;
// 저장된 쿼리가 select ~~ from (select ~ from where [condition] 형식으로 저장되어 있음(우괄호 반드시 필요)
sWhere := sWhere + ')';
ls_TxLoad := GetSel04(self.Caption + '6', 'CUSTOMER12', '', sWhere, [sSms1, sSms2, sTel1, sTel2, cxHdNo3.Text]);
cxPageControl1.enabled := False;
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
cxPageControl1.enabled := True;
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
end;
procedure TFrm_CUT.proc_init;
var
i, iCol: Integer;
ln_env: TIniFile;
sTemp: string;
begin
proc_BrNameSet;
de_1stDate.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
de_1edDate.Date := de_1stDate.Date + 1;
de_2stDate.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
de_2edDate.Date := de_2stDate.Date + 1;
de_3stDate.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
de_3edDate.Date := de_3stDate.Date + 1;
de_4stDate.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
de_4edDate.Date := de_4stDate.Date + 1;
de_5stDate.Date := de_4stDate.Date;
de_5edDate.Date := de_4edDate.Date;
de_6stDate.Date := de_4stDate.Date;
de_6edDate.Date := de_4edDate.Date;
cxCheckBox9.Checked := False;
cxCheckBox9Click(cxCheckBox9);
rbFirstUseDate01Click(rbUseDate01);
edCustName01.Text := '';
edCustTel01.Text := '';
cbSmsUse01.ItemIndex := 0;
cbGubun1_1.ItemIndex := 0;
cbLevel01.ItemIndex := 0;
chkBubinName.Checked := False;
chkBubinCust.Checked := False;
lbCount01.Caption := '총 000명';
chkSearchAdd.Checked := False;
cxCheckBox4.Checked := False;
// 고객관리 그리드 초기화
// proc_CustCounsel_Title;
for i := 1 to CustView1.ColumnCount - 1 do
CustView1.Columns[i].DataBinding.ValueType := 'String';
CustView1.BeginUpdate;
ln_Env := TIniFile.Create(ENVPATHFILE);
try
CustView1.DataController.SetRecordCount(0);
for i := 0 to CustView1.ColumnCount - 1 do
begin
sTemp := ln_env.ReadString('CustCounsel', IntToStr(i), '');
if lbCustCounselTitle.Items.IndexOf(sTemp) < 0 then
begin
sTemp := '';
end;
if sTemp <> '' then
begin
iCol := CustView1.GetColumnByFieldName(sTemp).Index;
if iCol = -1 then iCol := i;
end
else
iCol := i;
CustView1.Columns[iCol].Index := i;
if CustView1.Columns[iCol].Tag = 0 then
CustView1.Columns[iCol].Visible := False;
end;
finally
CustView1.EndUpdate;
FreeAndNil(ln_Env);
end;
if TCK_USER_PER.SMS_Advertisement <> '1' then //대량SMS발송권한이 없을경우 버튼 비활성화
begin
btn_1_1.enabled := False;
btn_2_5.enabled := False;
btn_3_5.enabled := False;
btn_4_6.enabled := False;
btn_6_9.enabled := False;
btn_9_4.enabled := False;
end;
iCol := CustView1.GetColumnByFieldName('No').Index;
CustView1.Columns[iCol].DataBinding.ValueType := 'Integer';
iCol := CustView1.GetColumnByFieldName('이용횟수').Index;
CustView1.Columns[iCol].DataBinding.ValueType := 'Integer';
iCol := CustView1.GetColumnByFieldName('완료횟수').Index;
CustView1.Columns[iCol].DataBinding.ValueType := 'Integer';
iCol := CustView1.GetColumnByFieldName('마일리지').Index;
CustView1.Columns[iCol].DataBinding.ValueType := 'Currency';
iCol := CustView1.GetColumnByFieldName('hdno').Index;
CustView1.Columns[iCol].Visible := False;
/////////////////////////////////////sheet1////////////////////////////////////////////////////
//2//
cxDate2_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
cxDate2_1E.Date := cxDate2_1S.Date + 1;
rbNew01.Checked := True;
rbAll01Click(rbNew01);
cbGubun2_1.ItemIndex := 0;
edCustName02.Text := '';
edCustTel02.Text := '';
cb_Sms_Gubun.ItemIndex := 1;
edCustTel02.Text := '';
edCustMemo01.Text := '';
cb_S_Cnt1.Text := '';
cb_S_Cnt2.Text := '';
cb_S_CCnt1.Text := '';
cb_S_CCnt2.Text := '';
cb_S_Grad.ItemIndex := 0;
cb_st_city.Properties.Items.Clear;
cb_st_city.Properties.Items.Assign(slstLocalMapOrder);
cb_st_city.Properties.Items.Insert(0, '지역전체');
cb_st_city.Tag := 0;
cb_st_city.ItemIndex := 0;
cb_st_cityPropertiesChange(cb_st_city);
cb_st_ward.ItemIndex := 0;
lbCount02.Caption := '총 0명';
chkCust02Type04.Checked := False;
chk_All_Select.Checked := False;
CustView2.Columns[0].DataBinding.ValueType := 'Integer';
for i := 1 to CustView2.ColumnCount - 1 do
CustView2.Columns[i].DataBinding.ValueType := 'String';
CustView2.Columns[23].DataBinding.ValueType := 'Currency';
for i := 0 to sg_notsms_list.ColumnCount - 1 do
sg_notsms_list.Columns[i].DataBinding.ValueType := 'String';
//2//
//3//
cxDate3_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
cxDate3_1E.Date := cxDate3_1S.Date + 1;
de_A31stDate.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
de_A31edDate.Date := de_A31stDate.Date + 1;
de_A32stDate.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
de_A32edDate.Date := de_A32stDate.Date + 1;
de_A33stDate.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
de_A33edDate.Date := de_A33stDate.Date + 1;
lbCount01.Caption := '총 000명';
cbGubun3_1.ItemIndex := 0;
edCustName03.Text := '';
rbCust03Type01.Checked := True;
rbCust03Type01Click(rbCust03Type01);
rbCust03Type03.Checked := true;
rbCust03Type03Click(rbCust03Type03);
chkCust03Type04.Checked := False;
chkCust03Type07.Checked := false;
CustView3.Columns[0].DataBinding.ValueType := 'Integer';
for i := 1 to CustView3.ColumnCount - 1 do
CustView3.Columns[i].DataBinding.ValueType := 'String';
CustView3.Columns[11].DataBinding.valuetype := 'Currency';
CustView3.Columns[12].DataBinding.valuetype := 'Integer';
//3//
//4//
cxDate4_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
cxDate4_1E.Date := cxDate4_1S.Date + 1;
cxDate4_2S.Date := cxDate4_1S.Date;
cxDate4_2E.Date := cxDate4_1E.Date;
cxDate4_3S.Date := cxDate4_1S.Date;
cxDate4_3E.Date := cxDate4_1E.Date;
cbGubun4_1.ItemIndex := 0;
cbLevel04.ItemIndex := 0;
chkCust04Type06.Checked := False;
lbCount04.Caption := '총 00명';
chkCust04Type01.Checked := False;
chkCust04Type01Click(chkCust04Type01);
chkCust04Type02.Checked := False;
chkCust04Type02Click(chkCust04Type02);
chkCust04Type03.Checked := False;
chkCust04Type03Click(chkCust04Type03);
chkCust04Type07.Checked := False;
chkCust04Type07Click(chkCust04Type07);
chkCust04Type09.Checked := False;
chkCust04Type09Click(chkCust04Type09);
chkCust04Type04.Checked := False;
chkCust04Type04Click(chkCust04Type04);
chkCust04Type05.Checked := False;
chkCust04Type05Click(chkCust04Type05);
cbCustLastNumber4.ItemIndex := 0;
edCust04Type01.Text := '';
edCust04Type02.Text := '';
edCust04Type03.Text := '';
edCust04Type04.Text := '';
chkCust04Type08.Checked := False;
cbArea03.Properties.Items.Clear;
cbArea03.Properties.Items.Assign(slstLocalMapOrder);
cbArea03.Properties.Items.Insert(0, '전체');
cbArea03.ItemIndex := 0;
CustView4.Columns[0].DataBinding.ValueType := 'Integer';
for i := 1 to CustView4.ColumnCount - 1 do
CustView4.Columns[i].DataBinding.ValueType := 'String';
CustView4.Columns[18].DataBinding.valuetype := 'Currency';
//4//
//5//
for i := 0 to cxGridDBTableView1.ColumnCount - 1 do
begin
cxGridDBTableView1.Columns[i].DataBinding.ValueType := 'String';
end;
cxGridDBTableView1.Columns[0].DataBinding.ValueType := 'Integer';
cxGridDBTableView1.Columns[4].DataBinding.ValueType := 'Integer';
cxGridDBTableView1.DataController.SetRecordCount(0);
for i := 0 to cxVirtureList.ColumnCount - 1 do
begin
cxVirtureList.Columns[i].DataBinding.ValueType := 'String';
end;
cxVirtureList.DataController.SetRecordCount(0);
//5//
//6//
cbGubun6_1.ItemIndex := 0;
cbLevel06.ItemIndex := 0;
chkCust06Type02.Checked := False;
lbCount06.Caption := '총 00명';
rbCust06Type01.Checked := True;
rbCust06Type01Click(rbCust06Type01);
chkCust06Type03.Checked := False;
cxDate6_1.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 30;
CustView6.Columns[0].DataBinding.ValueType := 'Integer';
for i := 1 to CustView6.ColumnCount - 1 do
CustView6.Columns[i].DataBinding.ValueType := 'String';
CustView6.Columns[16].DataBinding.valuetype := 'Currency';
//6//
//7//
cxPageControl2.ActivePageIndex := 0;
//7//
//8//
cxRadioButton10.Checked := True;
cxRadioButton10Click(cxRadioButton10);
rbPEventN.Checked := True;
cxRadioButton13.Checked := True;
cxRadioButton13Click(cxRadioButton13);
rbUEventN.Checked := True;
cxRadioButton16.Checked := True;
cxRadioButton16Click(cxRadioButton16);
rbBEventN.Checked := True;
cxRadioButton19.Checked := True;
cxRadioButton19Click(cxRadioButton19);
pnl_CUTA8.Enabled := False;
//8//
//9//
cxDate9_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
cxDate9_1E.Date := cxDate9_1S.Date + 1;
cxDate9_2S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
cxDate9_2E.Date := cxDate9_2S.Date + 1;
chkCust09Type02.Checked := True;
chkCust09Type02Click(chkCust09Type02);
edEvent01.Value := 0;
edMileage01.Value := 0;
cbGubun9_1.ItemIndex := 0;
edCustName09.Text := '';
edSupplyEnd01.Value := 0;
lbCount09.Caption := '총 00명';
chkCust09Type01.Checked := False;
CustView9.Columns[0].DataBinding.ValueType := 'Integer';
for i := 1 to CustView9.ColumnCount - 1 do
CustView9.Columns[i].DataBinding.ValueType := 'String';
CustView9.Columns[8].DataBinding.ValueType := 'Currency';
CustView9.Columns[9].DataBinding.ValueType := 'Currency';
CustView9.Columns[10].DataBinding.ValueType := 'Integer';
CustView9.Columns[18].DataBinding.ValueType := 'Currency';
CustView9.Columns[19].DataBinding.ValueType := 'Integer';
CustView9.Columns[20].DataBinding.ValueType := 'Integer';
//9//
//10//
cxDate10_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
cxDate10_1E.Date := cxDate10_1S.Date + 1;
chkCust10Type02.Checked := True;
chkCust10Type02Click(chkCust10Type02);
cbGubun10_1.ItemIndex := 0;
edCustName03.Text := '';
edCustTel03.Text := '';
lbCount10.Caption := '총 00명';
cxedCuSEQ.Text := '';
CustView10.Columns[0].DataBinding.ValueType := 'Integer';
for i := 1 to CustView10.ColumnCount - 1 do
CustView10.Columns[i].DataBinding.ValueType := 'String';
CustView10.Columns[10].DataBinding.ValueType := 'Currency';
CustView10.Columns[11].DataBinding.ValueType := 'Currency';
//10//
//11//
dtOKCStDate.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
dtOKCEdDate.Date := dtOKCStDate.Date + 1;
for I := 0 to cxViewOKC.ColumnCount - 1 do
begin
case I of
6, 9, 10:
begin
cxViewOKC.Columns[I].DataBinding.ValueTypeClass := TcxCurrencyValueType;
end;
else
cxViewOKC.Columns[I].DataBinding.ValueTypeClass := TcxStringValueType;
end;
end;
//11//
//12//
cxDate12_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8)));
cxDate12_1E.Date := cxDate12_1S.Date + 1;
for I := 0 to cxViewRCMD.ColumnCount - 1 do
begin
case I of
0, 4:
begin
cxViewRCMD.Columns[I].DataBinding.ValueTypeClass := TcxCurrencyValueType;
end;
else
cxViewRCMD.Columns[I].DataBinding.ValueTypeClass := TcxStringValueType;
end;
end;
for I := 0 to cxViewRCMD_D.ColumnCount - 1 do
begin
case I of
0, 3, 4:
begin
cxViewRCMD_D.Columns[I].DataBinding.ValueTypeClass := TcxCurrencyValueType;
end;
else
cxViewRCMD_D.Columns[I].DataBinding.ValueTypeClass := TcxStringValueType;
end;
end;
//12//
end;
procedure TFrm_CUT.proc_init_mileage;
begin
cxRadioButton10.Checked := True;
cxRadioButton10Click(cxRadioButton10);
rbPEventN.Checked := True;
cxRadioButton13.Checked := True;
cxRadioButton13Click(cxRadioButton13);
rbUEventN.Checked := True;
cxRadioButton16.Checked := True;
cxRadioButton16Click(cxRadioButton16);
rbBEventN.Checked := True;
cxRadioButton19.Checked := True;
cxRadioButton19Click(cxRadioButton19);
pnl_CUTA8.Enabled := False;
end;
procedure TFrm_CUT.proc_MileageAcc;
var
ls_TxLoad, sNode, sWhere, sTemp, sTel1, sTel2, sCbcode, strTemp: string;
ls_rxxml: WideString;
lst_Node: IXMLDOMNodeList;
lst_clon: IXMLDOMNode;
slReceive: TStringList;
XmlData, Param, ErrMsg, ls_MSG_Err : string;
ErrCode, iRow, i, j, iIdx : Integer;
xdom: msDomDocument;
lst_Result : IXMLDomNodeList;
ls_Rcrd, slList : TStringList;
sHdNo, sBrNo, sEndDate : string ;
begin
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) > 2100) or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
if CustView9.DataController.RecordCount > 0 then
Exit;
if (GT_USERIF.LV = '10') and ((GT_SEL_BRNO.GUBUN <> '1') or (GT_SEL_BRNO.BrNo <> GT_USERIF.BR)) then
begin
GMessagebox('상담원 권한은 소속 지사만 조회할수 있습니다.', CDMSE);
Exit;
end;
if fGetChk_Search_HdBrNo('마일리지현황') then Exit;
Try
//////////////////////////////////////////////////////////////////////////////
// 고객>마일리지현황]20000건/콜센터(통합)/대표번호:전체/등록기간:20100101~20100131/마일리지11이상/지급완료24이상
FExcelDownMile := Format('%s/대표번호:%s%s%s%s',
[
GetSelBrInfo
, cbKeynumber09.Text
, IfThen(chkCust09Type02.Checked, Format('/등록기간:%s~%s', [cxDate10_1S.Text, cxDate10_1E.Text]), '')
, IfThen(StrToIntDef(edMileage01.Text, -1) = -1, '', Format('/마일리지%s이상', [edMileage01.Text]))
, IfThen(StrToIntDef(edSupplyEnd01.Text, -1) = -1, '', Format('/지급완료%s이상', [edSupplyEnd01.Text]))
]);
//////////////////////////////////////////////////////////////////////////////
Param := '';
if (chkCust09Type02.checked) or ((Not chkCust09Type02.checked) and (Not chkCust09Type03.checked)) then Param := '0'
else if chkCust09Type03.checked then Param := '1';
if (GT_SEL_BRNO.GUBUN <> '1') then
begin
if (GT_USERIF.LV = '60') then
begin
if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB
sHdNo := GT_SEL_BRNO.HDNO
else
sHdNo := GT_USERIF.HD;
end else
begin
sHdNo := GT_USERIF.HD;
sBrNo := GT_USERIF.BR;
end
end else
begin
sHdNo := GT_USERIF.HD;
sBrNo := GT_SEL_BRNO.BrNo;
end;
Param := Param + '│' + sHdNo + '│' + sBrNo; //본사, 지사코드
if chkCust09Type02.Checked then
begin
if cxDate9_1S.Enabled then
begin
if (cxDate9_1S.Text <> '') and (cxDate9_1E.Text <> '') then
begin
Param := Param + '│' + formatdatetime('yyyymmdd', cxDate9_1S.Date);
Param := Param + '│' + formatdatetime('yyyymmdd', cxDate9_1E.Date);
end else
if (cxDate9_1S.Text <> '') and (cxDate9_1E.Text = '') then
begin
Param := Param + '│' + formatdatetime('yyyymmdd', cxDate9_1S.Date);
Param := Param + '│' + '';
end else
if (cxDate9_1S.Text = '') and (cxDate9_1E.Text <> '') then
begin
Param := Param + '│' + '';
Param := Param + '│' + formatdatetime('yyyymmdd', cxDate9_1E.Date);
end;
end else
begin
Param := Param + '│' + '';
Param := Param + '│' + '';
end;
end else
if chkCust09Type03.Checked then
begin
Param := Param + '│' + formatdatetime('yyyymmdd', cxDate9_2S.Date);
Param := Param + '│' + formatdatetime('yyyymmdd', cxDate9_2E.Date);
end else
begin
Param := Param + '│' + '';
Param := Param + '│' + '';
end;
if (cbKeynumber09.Text = '전체') Or (cbKeynumber09.ItemIndex = 0) then
Param := Param + '│'
else
Param := Param + '│' + StringReplace(cbKeynumber09.Text, '-', '', [rfReplaceAll]);
case cbGubun9_1.ItemIndex of
0: Param := Param + '│' + '';
1: Param := Param + '│' + '0';
2: Param := Param + '│' + '1';
3: Param := Param + '│' + '3';
end;
Param := Param + '│' + Param_Filtering(edCustName09.Text); //고객명
strTemp := RemoveComma(edMileage01.Text);
Param := Param + '│' + strTemp; //마일리지
strTemp := RemoveComma(edSupplyEnd01.Text);
Param := Param + '│' + strTemp; //지급완료
strTemp := RemoveComma(edCouponM01.Text);
Param := Param + '│' + strTemp; //쿠폰마일
strTemp := RemoveComma(edEvent01.Text);
Param := Param + '│' + strTemp; //이벤트횟수
strTemp := RemoveComma(edMileageLost01.Text);
Param := Param + '│' + strTemp; //소멸예정마일리지
slList := TStringList.Create;
Screen.Cursor := crHourGlass;
Try
if not RequestBasePaging(GetSel06('GET_LIST_CUST_MILEAGE', 'CUSTOMER.GET_LIST_CUST_MILEAGE', '1000', Param), slList, ErrCode, ErrMsg) then
begin
Frm_Flash.hide;
Application.ProcessMessages;
GMessagebox(Format('마일리지(고객별) 조회 중 오류발생'#13#10'[%d]%s', [ErrCode, ErrMsg]), CDMSE);
Frm_Main.Enabled := True;
Screen.Cursor := crDefault;
Exit;
end;
xdom := ComsDomDocument.Create;
try
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
CustView9.DataController.SetRecordCount(0);
CustView9.BeginUpdate;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
xmlData := slList.Strings[j];
xdom.loadXML(XmlData);
ls_MSG_Err := GetXmlErrorCode(XmlData);
if ('0000' = ls_MSG_Err) then
begin
if (0 < GetXmlRecordCount(XmlData)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
Application.ProcessMessages;
iRow := CustView9.DataController.AppendRecord;
CustView9.DataController.Values[iRow, 0] := iRow + 1;
CustView9.DataController.Values[iRow, 1] := ls_rcrd[0];
CustView9.DataController.Values[iRow, 2] := ls_rcrd[1];
iIdx := scb_BranchCode.IndexOf(ls_rcrd[1]);
if iIdx >= 0 then
CustView9.DataController.Values[iRow, 3] := scb_BranchName[iIdx]
else
CustView9.DataController.Values[iRow, 3] := '';
CustView9.DataController.Values[iRow, 4] := strtocall(ls_rcrd[2]);
case StrToIntDef(ls_rcrd[3], 0) of
0: CustView9.DataController.Values[iRow, 5] := '일반';
1: CustView9.DataController.Values[iRow, 5] := '업소';
3: CustView9.DataController.Values[iRow, 5] := '법인';
4: CustView9.DataController.Values[iRow, 5] := '주말골프';
end;
CustView9.DataController.Values[iRow, 6] := ls_rcrd[4];
CustView9.DataController.Values[iRow, 7] := strtocall(ls_rcrd[5]);
if StrToIntDef(ls_Rcrd[6], 0) = 0 then
ls_Rcrd[6] := '0';
if StrToIntDef(ls_Rcrd[7], 0) = 0 then
ls_Rcrd[7] := '0';
if StrToIntDef(ls_Rcrd[8], 0) = 0 then
ls_Rcrd[8] := '0';
CustView9.DataController.Values[iRow, 8] := ls_rcrd[6];
CustView9.DataController.Values[iRow, 9] := ls_rcrd[7];
CustView9.DataController.Values[iRow, 10] := ls_rcrd[8];
if ls_rcrd[9] = 'y' then
CustView9.DataController.Values[iRow, 11] := '인증'
else
CustView9.DataController.Values[iRow, 11] := '미인증';
CustView9.DataController.Values[iRow, 12] := ls_rcrd[10];
sEndDate := ls_rcrd[11];
if Trim(sEndDate) <> '' then
CustView9.DataController.Values[iRow, 13] := copy(sEndDate, 1, 4) + '-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView9.DataController.Values[iRow, 13] := '';
sEndDate := ls_rcrd[12];
if Trim(sEndDate) <> '' then
CustView9.DataController.Values[iRow, 14] := copy(sEndDate, 1, 4) + '-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView9.DataController.Values[iRow, 14] := '';
CustView9.DataController.Values[iRow, 15] := ls_rcrd[13];
CustView9.DataController.Values[iRow, 16] := ls_rcrd[14];
CustView9.DataController.Values[iRow, 17] := ls_rcrd[15];
if StrToIntDef(ls_Rcrd[16], 0) = 0 then
ls_Rcrd[16] := '0';
CustView9.DataController.Values[iRow, 18] := ls_rcrd[16];
CustView9.DataController.Values[iRow, 19] := ls_rcrd[17];
if ls_rcrd.Count > 18 then
CustView9.DataController.Values[iRow, 20] := StrToFloatDef(ls_rcrd[18], 0);
if ls_Rcrd[19] = '' then
CustView9.DataController.Values[iRow, 21] := '0' //소멸예정마일리지
else
CustView9.DataController.Values[iRow, 21] := formatfloat('#,##0', StrToFloatDef(ls_Rcrd[19], 0)); //소멸예정마일리지
CustView9.DataController.Values[iRow, 22] := GetStrToDateTimeGStr(ls_Rcrd[20], 4); //소멸예정일
if ls_rcrd[21] = 'y' then CustView9.DataController.Values[iRow, 23] := '수신'
else CustView9.DataController.Values[iRow, 23] := '거부';
if ls_rcrd.Count > 22 then
begin
CustView9.DataController.Values[iRow, 24] := StrToFloatDef(ls_rcrd[22], 0); //적립합계
CustView9.DataController.Values[iRow, 25] := StrToFloatDef(ls_rcrd[23], 0); //지급합계
end;
end;
finally
ls_Rcrd.Free;
end;
end else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
lbCount09.Caption := '총 ' + IntToStr(CustView9.DataController.RecordCount) + '명';
frm_Main.sbar_Message.Panels[4].Text := '';
Screen.Cursor := crDefault;
end
else
begin
Frm_Flash.hide;
Application.ProcessMessages;
GMessagebox('검색된 내용이 없습니다', CDMSE);
end;
end;
finally
CustView9.EndUpdate;
xdom := Nil;
end;
Finally
frm_Main.proc_SocketWork(True);
Screen.Cursor := crDefault;
Frm_Flash.hide;
Frm_Main.Enabled := True;
End;
except
Frm_Flash.hide;
Frm_Main.Enabled := True;
Screen.Cursor := crDefault;
End;
end;
procedure TFrm_CUT.proc_MileageDetail;
var
slList, StrList : TStringList;
XmlData, Param, ErrMsg : string;
ls_TxLoad, sNode, sWhere, sTel1, sTel2, sCbcode, sEndDate: string;
i, j, iCnt, iRow, iIdx : Integer;
ErrCode: integer;
tmpCnt: integer;
tmpCntStr: string;
k: Integer;
tmpStr: string;
ArrSt: array of string;
begin
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) > 2100) or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
// if CustView10.DataController.RecordCount > 0 then Exit;
if (GT_USERIF.LV = '10') and ((GT_SEL_BRNO.GUBUN <> '1') or (GT_SEL_BRNO.BrNo <> GT_USERIF.BR)) then
begin
GMessagebox('상담원 권한은 소속 지사만 조회할수 있습니다.', CDMSE);
Exit;
end;
if fGetChk_Search_HdBrNo('마일리지상세') then Exit;
//////////////////////////////////////////////////////////////////////////////
// 고객>마일리지상세]2000건/콜센터(통합)/전체/기간:XXXX~XXXX
FExcelDownMileDetail := Format('%s/종류:%s%s',
[
GetSelBrInfo
, IfThen(rbCust10Type01.Checked, '전체', IfThen(rbCust10Type02.Checked, '적립', '지급'))
, IfThen(chkCust10Type02.Checked, Format('/기간:%s~%s', [cxDate10_1S.Text, cxDate10_1E.Text]), '')
]);
//////////////////////////////////////////////////////////////////////////////
param := cxedCuSEQ.Text;
Param := Param + '│' + cxBrNo10.Text;
if chkCust10Type02.Checked then Param := Param + '│' + '1'
else Param := Param + '│' + '0';
Param := Param + '│' + FormatDateTime('yyyymmdd090000', cxDate10_1S.Date);
Param := Param + '│' + FormatDateTime('yyyymmdd090000', cxDate10_1E.Date);
Param := Param + '│' + IntToStr(0);
if (cbKeynumber06.Text = '전체') Or (cbKeynumber06.ItemIndex = 0) then
Param := Param + '│'
else
Param := Param + '│' + StringReplace(cbKeynumber06.Text, '-', '', [rfReplaceAll]);
case cbGubun10_1.ItemIndex of
1: Param := Param + '│0';
2: Param := Param + '│1';
3: Param := Param + '│3';
else Param := Param + '│';
end;
Param := Param + '│' + Param_Filtering(edCustName03.Text);
sTel1 := Param_Filtering(edCustTel03.Text);
sTel1 := StringReplace(sTel1, '-', '', [rfReplaceAll]);
sTel1 := StringReplace(sTel1, ' ', '', [rfReplaceAll]);
Param := Param + '│' + sTel1;
if rbCust10Type01.Checked then Param := Param + '│' + '0' else
if rbCust10Type02.Checked then Param := Param + '│' + '1' else
if rbCust10Type03.Checked then Param := Param + '│' + '2';
Param := Param + '│' + cxHdNo9.Text;
Param := Param + '│' + IntToStr(cxCbMileGubun.ItemIndex);
slList := TStringList.Create;
cxPageControl1.Enabled := False;
Screen.Cursor := crHourGlass;
try
if not RequestBasePaging(GetSel05('LIST_MILEAGE_SEARCH', 'MNG_CUST.LIST_MILEAGE_SEARCH', '1000', Param), slList, ErrCode, ErrMsg) then
begin
GMessagebox(Format('마일리지 조회 중 오류발생'#13#10'[%d]%s', [ErrCode, ErrMsg]), CDMSE);
cxPageControl1.Enabled := True;
Screen.Cursor := crDefault;
Exit;
end;
iCnt := 1;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
xmlData := slList.Strings[j];
if Pos('<Data Count="',xmlData)>0 then
begin
tmpCntStr:=Copy(XmlData,Pos('<Data Count="',xmlData)+13,100);
if Pos('"',tmpCntStr)>0 then tmpCntStr:=Copy(tmpCntStr,1,Pos('"',tmpCntStr)-1);
tmpCnt:=StrToIntDef(tmpCntStr,0);
end;
if tmpCnt < 1 then
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
Exit;
end;
CustView10.BeginUpdate;
StrList := TStringList.Create;
try
SetLength(ArrSt,tmpCnt);
tmpStr:=xmlData;
tmpStr:=stringreplace(tmpStr,'"','',[rfReplaceAll]);
tmpStr:=stringreplace(tmpStr,#13,'',[rfReplaceAll]);
tmpStr:=stringreplace(tmpStr,#10,'',[rfReplaceAll]);
if Pos('<Result Value=',XmlData)>0 then
tmpStr:=Copy(XmlData,Pos('<Result Value=',XmlData),Length(XmlData)-Pos('<Result Value=',XmlData)+1);
for k:=0 to tmpCnt-1 do
begin
ArrSt[k]:=tmpStr;
if Pos('/>',tmpStr)>0 then
begin
ArrSt[k]:=Copy(tmpStr,1,Pos('/>',tmpStr)-1);
if Pos('<Result Value=',ArrSt[k]) > 0 then
ArrSt[k] := Copy(ArrSt[k],Pos('<Result Value=',ArrSt[k])+14,Length(ArrSt[k])-Pos('<Result Value=',ArrSt[k])+14+1);
if Pos('/>',ArrSt[k]) > 0 then
ArrSt[k] := Copy(ArrSt[k],1,Pos('/>',ArrSt[k])-1);
ArrSt[k]:=StringReplace(ArrSt[k],'"','',[rfReplaceAll]);
tmpStr:=Copy(tmpStr,Pos('/>',tmpStr)+2,Length(tmpStr)-Pos('/>',tmpStr)+2+1);
StrList.Clear;
GetTextSeperationEx('│', ArrSt[k], StrList);
iRow := CustView10.DataController.AppendRecord;
CustView10.DataController.Values[iRow, 0] := iRow + 1;
CustView10.DataController.Values[iRow, 1] := StrList.Strings[0];
CustView10.DataController.Values[iRow, 2] := StrList.Strings[1];
iIdx := scb_BranchCode.IndexOf(StrList.Strings[1]);
if iIdx >= 0 then
CustView10.DataController.Values[iRow, 3] := scb_BranchName[iIdx]
else
CustView10.DataController.Values[iRow, 3] := '';
CustView10.DataController.Values[iRow, 4] := strtocall(StrList.Strings[2]);
case StrToIntDef(StrList.Strings[3], 0) of
0: CustView10.DataController.Values[iRow, 5] := '일반';
1: CustView10.DataController.Values[iRow, 5] := '업소';
3: CustView10.DataController.Values[iRow, 5] := '법인';
4: CustView10.DataController.Values[iRow, 5] := '주말골프';
end;
CustView10.DataController.Values[iRow, 6] := StrList.Strings[4];
CustView10.DataController.Values[iRow, 7] := strtocall(StrList.Strings[5]);
if StrList.Strings[6] = 'y' then
CustView10.DataController.Values[iRow, 8] := '인증'
else
CustView10.DataController.Values[iRow, 8] := '미인증';
sEndDate := StrList.Strings[7];
if Trim(sEndDate) <> '' then
CustView10.DataController.Values[iRow, 9] := copy(sEndDate, 1, 4) +
'-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView10.DataController.Values[iRow, 9] := '';
if StrToIntDef(StrList.Strings[8], 0) = 0 then
StrList.Strings[8] := '0';
if StrToIntDef(StrList.Strings[9], 0) = 0 then
StrList.Strings[9] := '0';
CustView10.DataController.Values[iRow, 10] := StrList.Strings[8];
CustView10.DataController.Values[iRow, 11] := StrList.Strings[9];
CustView10.DataController.Values[iRow, 12] := StrList.Strings[10];
CustView10.DataController.Values[iRow, 13] := StrList.Strings[11];
CustView10.DataController.Values[iRow, 14] := StrList.Strings[12];
CustView10.DataController.Values[iRow, 15] := StrList.Strings[13];
if StrList.Count > 14 then
CustView10.DataController.Values[iRow, 16] := StrList.Strings[14];
end;
end;
finally
CustView10.EndUpdate;
StrList.Free;
end;
end;
lbCount10.Caption := '총 ' + IntToStr(CustView10.DataController.RecordCount) + '명';
frm_Main.sbar_Message.Panels[4].Text := '';
finally
slList.Free;
Screen.Cursor := crDefault;
cxPageControl1.Enabled := True;
Frm_Flash.Hide;
end;
end;
procedure TFrm_CUT.proc_MileageSet;
var
msg, sBrNo, sBrName, Param : string;
XmlData, ErrMsg: string;
xdom: msDomDocument;
lst_Count, lst_Result: IXMLDomNodeList;
ls_Rcrd: TStringList;
I, ErrCode : Integer;
begin
try
sBrNo := cxBrNo8.Text;
if sBrNo = '' then
begin
GMessagebox('마일리지 설정은 지사를 선택하셔야 합니다.', CDMSE);
proc_init_mileage;
Exit;
end;
if (GT_USERIF.LV = '10') and (not IsPassedManagementCu(sBrNo)) then
begin
msg := '[%s(%s)] 지사에서 고객관련 관리권한 이관(콜센터 상담원)을 설정 하지 않았습니다.'
+ #13#10'(해당 지사관리자에게 관리권한 이관[회사>지사관리>상세설정]을 요청바랍니다.)';
sBrName := GetBrName(sBrNo);
GMessagebox(Format(msg, [sBrNo, sBrName]), CDMSE);
proc_init_mileage;
Exit;
end;
if fGetChk_Search_HdBrNo('마일리지설정') then Exit;
Pnl_CUTA8.Enabled := True;
Param := sBrNo;
if not RequestBase(GetSel05('GET_BRANCH_MLG', 'MNG_CUST.GET_BRANCH_MLG', '100', Param), XmlData, ErrCode, ErrMsg) then
begin
GMessagebox(Format('마일리지 설정 조회 중 오류발생'#13#10'[%d]%s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
xdom := ComsDomDocument.Create;
try
xdom.loadXML(XmlData);
lst_Count := xdom.documentElement.selectNodes('/cdms/Service/Data');
if StrToIntDef(lst_Count.item[0].attributes.getNamedItem('Count').Text,0) > 0 then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for I := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
if ls_Rcrd[0] = '0' then cxRadioButton10.Checked := True else
if ls_Rcrd[0] = '1' then cxRadioButton11.Checked := True else
if ls_Rcrd[0] = '2' then cxRadioButton12.Checked := True;
cxTextEdit1.Value := StrToIntDef(ls_Rcrd[1], 0);
cxTextEdit2.Value := StrToIntDef(ls_Rcrd[2], 0);
cxTextEdit3.Text := ls_Rcrd[3];
if ls_Rcrd[4] = '0' then cxRadioButton13.Checked := True else
if ls_Rcrd[4] = '1' then cxRadioButton14.Checked := True else
if ls_Rcrd[4] = '2' then cxRadioButton15.Checked := True;
cxTextEdit4.Value := StrToIntDef(ls_Rcrd[5], 0);
cxTextEdit5.Value := StrToIntDef(ls_Rcrd[6], 0);
cxTextEdit6.Text := ls_Rcrd[7];
if ls_Rcrd[8] = '0' then cxRadioButton16.Checked := True else
if ls_Rcrd[8] = '1' then cxRadioButton17.Checked := True else
if ls_Rcrd[8] = '2' then cxRadioButton18.Checked := True;
cxTextEdit7.Value := StrToIntDef(ls_Rcrd[9], 0);
cxTextEdit8.Value := StrToIntDef(ls_Rcrd[10], 0);
cxTextEdit9.Text := ls_Rcrd[11];
if ls_Rcrd[12] = '0' then cxRadioButton19.Checked := True else
if ls_Rcrd[12] = '1' then cxRadioButton20.Checked := True else
if ls_Rcrd[12] = '2' then cxRadioButton21.Checked := True;
cxTextEdit10.Value := StrToIntDef(ls_Rcrd[13], 0);
cxTextEdit11.Value := StrToIntDef(ls_Rcrd[14], 0);
cxTextEdit12.Text := ls_Rcrd[15];
if ls_Rcrd[16] = 'y' then chkCDNoMile.Checked := False //후불(카드)고객 마일리지 적립안함
else chkCDNoMile.Checked := True;
if ls_Rcrd[17] = 'y' then chkLTNoMile.Checked := False //후불고객 마일리지 적립안함
else chkLTNoMile.Checked := True;
if ls_Rcrd[18] = 'y' then chkReceipNoMile.Checked := False //현금영수증고객 마일리지 적립안함
else chkReceipNoMile.Checked := True;
if ls_Rcrd[19] = 'y' then cxCheckBox5.Checked := True
else cxCheckBox5.Checked := False;
cxCurrencyEdit1.Text := ls_Rcrd[20];
if ls_Rcrd[21] = 'y' then cxCheckBox6.Checked := True
else cxCheckBox6.Checked := False;
cxCurrencyEdit2.Text := ls_Rcrd[22];
if ls_Rcrd[23] = 'y' then cxCheckBox7.Checked := True
else cxCheckBox7.Checked := False;
cxCurrencyEdit3.Text := ls_Rcrd[24];
if ls_Rcrd[25] = 'y' then cxCheckBox8.Checked := True
else cxCheckBox8.Checked := False;
cxCurrencyEdit4.Text := ls_Rcrd[26];
CEMiOver1.Value := StrToIntDef(ls_Rcrd[27], 0);
CEMiOver2.Value := StrToIntDef(ls_Rcrd[28], 0);
CEMiOver3.Value := StrToIntDef(ls_Rcrd[29], 0);
CEMiOver4.Value := StrToIntDef(ls_Rcrd[30], 0);
if ls_Rcrd.Count > 31 then
begin
if ls_Rcrd[31] = 'y' then rbPEventY.Checked := True
else rbPEventY.Checked := False;
if ls_Rcrd[32] = 'y' then rbUEventY.Checked := True
else rbUEventY.Checked := False;
if ls_Rcrd[33] = 'y' then rbBEventY.Checked := True
else rbBEventY.Checked := False;
// ls_Rcrd[34] = 'y' 불량고객 사용 않함
end;
if ls_Rcrd.Count > 35 then // 35 : 금액, 36 : 고객구분yyy, 37 : 없음/정액/정률-0/1/2
begin
//////////////////////후불(마일) + 후불(카드) 마일리지 별도적립 사용 20161129 KHS
if StrToFloatDef(ls_Rcrd[35], 0) = 0 then
begin
cxCheckBox3.Checked := False;
rb_Straight.Enabled := False;
rb_Declining.Enabled := False;
cxCurrencyEdit6.Enabled := False;
cxLabel190.Enabled := False;
cxCheckBox2.Enabled := False;
cxCheckBox10.Enabled := False;
cxCheckBox11.Enabled := False;
cxCurrencyEdit6.value := StrToFloatDef(ls_Rcrd[35], 0);
cxCheckBox2.checked := False;
cxCheckBox10.checked := False;
cxCheckBox11.checked := False;
end else
if ls_Rcrd[37] = '1' then //정액
begin
cxCheckBox3.Checked := True;
rb_Straight.Enabled := True;
rb_Declining.Enabled := True;
rb_Straight.checked := True;
cxCurrencyEdit6.Enabled := True;
cxLabel190.Enabled := True;
cxCheckBox2.Enabled := True;
cxCheckBox10.Enabled := True;
cxCheckBox11.Enabled := True;
cxCurrencyEdit6.value := StrToFloatDef(ls_Rcrd[35], 0);
cxLabel190.Caption := '원';
if copy(ls_Rcrd[36],1,1) = 'y' then cxCheckBox2.checked := True else cxCheckBox2.checked := False;
if copy(ls_Rcrd[36],2,1) = 'y' then cxCheckBox2.checked := True else cxCheckBox10.checked := False;
if copy(ls_Rcrd[36],3,1) = 'y' then cxCheckBox2.checked := True else cxCheckBox11.checked := False;
end else
if ls_Rcrd[37] = '2' then //정률
begin
cxCheckBox3.Checked := True;
rb_Straight.Enabled := True;
rb_Declining.Enabled := True;
rb_Declining.checked := True;
cxCurrencyEdit6.Enabled := True;
cxLabel190.Enabled := True;
cxCheckBox2.Enabled := True;
cxCheckBox10.Enabled := True;
cxCheckBox11.Enabled := True;
cxCurrencyEdit6.value := StrToFloatDef(ls_Rcrd[35], 0);
cxLabel190.Caption := '%';
if copy(ls_Rcrd[36],1,1) = 'y' then cxCheckBox2.checked := True else cxCheckBox2.checked := False;
if copy(ls_Rcrd[36],2,1) = 'y' then cxCheckBox2.checked := True else cxCheckBox10.checked := False;
if copy(ls_Rcrd[36],3,1) = 'y' then cxCheckBox2.checked := True else cxCheckBox11.checked := False;
end else
begin
cxCheckBox3.Checked := False;
rb_Straight.Enabled := False;
rb_Declining.Enabled := False;
cxCurrencyEdit6.Enabled := False;
cxLabel190.Enabled := False;
cxCheckBox2.Enabled := False;
cxCheckBox10.Enabled := False;
cxCheckBox11.Enabled := False;
cxCurrencyEdit6.value := StrToFloatDef(ls_Rcrd[35], 0);
cxCheckBox2.checked := False;
cxCheckBox10.checked := False;
cxCheckBox11.checked := False;
end;
end;
// 38 : 마일리지 소멸기간
if ls_Rcrd.Count > 38 then
begin
if ls_Rcrd[38] <> '' then
lbMileLostMonth.Caption := ls_Rcrd[38] + '개월'
else
lbMileLostMonth.Caption := '- 개월'
end;
if ls_Rcrd[39] = 'y' then chkMileSaveCash.checked := True else chkMileSaveCash.checked := False; //"후불(마일)" 결제 시 현금액 마일리지 적립
if ls_Rcrd[40] = 'y' then chkMileSaveMile.checked := True else chkMileSaveMile.checked := False; //"후불(마일)" 결제 시 마일리지액 마일리지 적립
end;
finally
ls_Rcrd.Free;
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
end;
finally
xdom := Nil;
end;
except
on e: exception do
begin
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_CUT.proc_New_his(iType: Integer);
begin
chk_Before.Checked := False;
chk_Before_New.Checked := False;
chk_Before_Finish.Checked := False;
cbGubun2_1.ItemIndex := 0;
case iType of
2:
begin
cb_st_city.Enabled := True;
cb_st_ward.Enabled := True;
// cb_S_Cnt1.Enabled := False;
// cb_S_Cnt2.Enabled := False;
cb_S_CCnt1.Enabled := False;
cb_S_CCnt2.Enabled := False;
cb_S_Grad.Enabled := False;
GroupBox4.Enabled := True;
rrb_st_all.Checked := True;
rrb_st_all.Enabled := True;
rrb_st_comp.Enabled := True;
rrb_st_cancel.Enabled := True;
rrb_st_req.Enabled := True;
end;
0, 1:
begin
cb_st_city.Enabled := False;
cb_st_ward.Enabled := False;
cbKeynumber02.ItemIndex := 0;
cbGubun2_1.ItemIndex := 0;
cb_Sms_Gubun.ItemIndex := 0;
cb_S_Grad.ItemIndex := 0;
cb_Sms_Gubun.Enabled := True;
cb_S_Cnt1.Enabled := True;
cb_S_Cnt2.Enabled := True;
cb_S_CCnt1.Enabled := True;
cb_S_CCnt2.Enabled := True;
cb_S_Grad.Enabled := True;
GroupBox4.Enabled := False;
rrb_st_all.Checked := True;
rrb_st_comp.Checked := False;
rrb_st_cancel.Checked := False;
rrb_st_req.Checked := False;
rrb_st_all.Enabled := False;
rrb_st_comp.Enabled := False;
rrb_st_cancel.Enabled := False;
rrb_st_req.Enabled := False;
end;
end;
end;
procedure TFrm_CUT.proc_NotSMS(Br_no: string);
var
ls_TxQry, ls_TxLoad, sQueryTemp : string;
sWhere: string;
slReceive: TStringList;
ErrCode: integer;
begin
sg_notsms_list.DataController.SetRecordCount(0);
sg_notsms_list.DataController.AppendRecord;
swhere := '';
if Br_no <> '' then
begin
sg_notsms_list.DataController.Values[0, 0] := Br_no;
sWhere := 'AND B.HD_NO = ''' + cxHdNo1.Text + ''' AND B.BR_NO = ''' + Br_no + ''' ';
end else
begin
sg_notsms_list.DataController.Values[0, 0] := cxHdNo1.Text;
sWhere := 'AND B.HD_NO = ''' + cxHdNo1.Text + ''' ';
end;
ls_TxLoad := GTx_UnitXmlLoad('SEL02.XML');
fGet_BlowFish_Query(GSQ_BRANCH_SMS, sQueryTemp);
ls_TxQry := Format(sQueryTemp, [sWhere]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', GT_USERIF.ID, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', 'NOSM0002', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'PagingString', '20000', [rfReplaceAll]);
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
func_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
end;
procedure TFrm_CUT.proc_OKCashBack;
var
ls_TxLoad, sNode, sWhere, sBrNo, sBrName, msg: string;
ls_rxxml: WideString;
xdom: msDomDocument;
lst_Node: IXMLDOMNodeList;
lst_clon: IXMLDOMNode;
slReceive: TStringList;
ErrCode: integer;
begin
sBrNo := cxBrNo11.Text;
if sBrNo = '' then
begin
GMessagebox('OK 캐쉬백 현황 조회는 지사를 선택하셔야 합니다.', CDMSE);
Exit;
end;
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) > 2100) or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
if (GT_USERIF.LV = '10') and (not IsPassedManagementCu(sBrNo)) then
begin
msg := '[%s(%s)] 지사에서 고객관련 관리권한 이관(콜센터 상담원)을 설정 하지 않았습니다.'
+ #13#10'(해당 지사관리자에게 관리권한 이관[회사>지사관리>상세설정]을 요청바랍니다.)';
sBrName := GetBrName(sBrNo);
GMessagebox(Format(msg, [sBrNo, sBrName]), CDMSE);
Exit;
end;
ls_rxxml := GTx_UnitXmlLoad('SEL04.XML');
xdom := ComsDomDocument.Create;
try
if (not xdom.loadXML(ls_rxxml)) then
begin
Screen.Cursor := crDefault;
ShowMessage('전문 Error입니다. 다시조회하여주십시요.');
Exit;
end;
sWhere := '';
sNode := '/cdms/header/UserID';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Value').Text :=
En_Coding(GT_USERIF.ID);
sNode := '/cdms/header/ClientVer';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Value').Text := VERSIONINFO;
sNode := '/cdms/header/ClientKey';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Value').Text := self.Caption + '80';
sNode := '/cdms/Service/Data/Query';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Key').Text := 'OKCBLOG01';
lst_Node.item[0].attributes.getNamedItem('Backward').Text := sWhere;
sNode := '/cdms/Service/Data/Query/Param';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_clon := lst_node.item[0].cloneNode(True);
sNode := '/cdms/Service/Data/Query';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].appendChild(lst_clon);
sNode := '/cdms/Service/Data/Query/Param';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_clon := lst_node.item[0].cloneNode(True);
sNode := '/cdms/Service/Data/Query';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].appendChild(lst_clon);
sNode := '/cdms/Service/Data/Query/Param';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Seq').Text := '1';
lst_Node.item[0].attributes.getNamedItem('Value').Text := cxBrNo11.Text;
lst_Node.item[1].attributes.getNamedItem('Seq').Text := '2';
lst_Node.item[1].attributes.getNamedItem('Value').Text := RemoveDatetimeSeparator(dtOKCStDate.Text) + '090000';
lst_Node.item[2].attributes.getNamedItem('Seq').Text := '3';
lst_Node.item[2].attributes.getNamedItem('Value').Text := RemoveDatetimeSeparator(dtOKCEdDate.Text) + '085959';
ls_TxLoad := '<?xml version="1.0" encoding="euc-kr"?>' + #13#10 + xDom.documentElement.xml;
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
finally
xdom := Nil;
end;
end;
procedure TFrm_CUT.proc_recieve(slList: TStringList);
var
xdom: msDomDocument;
ls_ClientKey, ClientKey, ls_Msg_Err, sMsg, sEndDate, sTmp, sBrNo, sPerMMCode, sTmep, sRate, sTel, sNoSms: string;
lst_Result: IXMLDomNodeList;
ls_Rcrd, sList, slTmp : TStringList;
icomCnt, iCanCnt, iTotal, iCanRate, i, j, k, iHp, iRegDate, iSNum, iTel, iRow, iIndate, iBrNo, iId, iIdx, iCnt : Integer;
Node: TcxTreeListNode;
bCheck: Boolean;
ls_rxxml: WideString;
ErrDesc: string;
iCuTitle: array[0..37] of integer;
sSmsYn1, sTel1, sSmsYn2, sTel2, sSmsYn3, sTel3 : string;
begin
try
xdom := ComsDomDocument.Create;
Screen.Cursor := crHourGlass;
try
ls_rxxml := slList[0];
if not xdom.loadXML(ls_rxxml) then
begin
Exit;
end;
ls_MSG_Err := GetXmlErrorCode(ls_rxxml);
if ('0000' = ls_MSG_Err) then
begin
frm_Main.sbar_Message.Panels[4].Text := '';
ls_ClientKey := GetXmlClientKey(ls_rxxml);
ClientKey := ls_ClientKey;
ls_ClientKey := Copy(ls_ClientKey, 6, Length(ls_ClientKey) - 5);
if ClientKey = 'GetCustGroup' then ResponseCustLevel(ls_rxxml)
else if ClientKey = 'GetGroupLevel' then ResponseCustGroup(ls_rxxml)
else if ClientKey = 'GetLevelFromGroupSeq' then ResponseLevelFromGroupSeq(ls_rxxml)
else
case StrToIntDef(ls_ClientKey, 1) of
2:
begin
CustView1.BeginUpdate;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
//- frm_Main.sbar_Message.Panels[4].Text := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
ls_rxxml := slList.Strings[j];
if not xdom.loadXML(ls_rxxml) then
begin
Continue;
end;
ls_MSG_Err := GetXmlErrorCode(ls_rxxml);
if ('0000' <> ls_MSG_Err) then
begin
Continue;
end;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
for i := 0 to lbCustCounselTitle.Items.Count - 1 do
iCuTitle[i] := CustView1.GetColumnByFieldName(lbCustCounselTitle.Items.Strings[i]).Index;
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
slTmp := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
sTmp := ls_Rcrd[4];
sSmsYn1 := ''; sTel1 := ''; sSmsYn2 := ''; sTel2 := ''; sSmsYn3 := ''; sTel3 := '';
slTmp.Clear;
slTmp.Delimiter := ',';
slTmp.DelimitedText := sTmp;
if slTmp.Count = 1 then //연락처가 1개일경우 나머지는 빈값처리
begin
sSmsYn2 := ''; sTel2 := ''; sSmsYn3 := ''; sTel3 := '';
end;
for k := 0 to slTmp.Count -1 do
begin
if k = 0 then
begin
sTel1 := Copy(slTmp[k], 1, pos('/', slTmp[k]) - 1);
sSmsYn1 := Copy(slTmp[k], Length(slTmp[k]), 1);
end else
if k = 1 then
begin
sTel2 := Copy(slTmp[k], 1, pos('/', slTmp[k]) - 1);
sSmsYn2 := Copy(slTmp[k], Length(slTmp[k]), 1);
end else
if k = 2 then
begin
sTel3 := Copy(slTmp[k], 1, pos('/', slTmp[k]) - 1);
sSmsYn3 := Copy(slTmp[k], Length(slTmp[k]), 1);
end;
end;
//전화번호 및 SMS수신관련 옵션은 3개 생성후 처리 20181001 KHS
if chkNmlPhoneOut01.Checked then
begin
if (not CheckHPType(sTel1, ErrDesc)) and (not CheckHPType(sTel2, ErrDesc)) and (not CheckHPType(sTel3, ErrDesc))then
begin
Continue; //3개 모두 False면
end;
end;
if sSmsYn1 = '' then sSmsYn1 := 'n';
if cbSmsUse01.ItemIndex = 1 then
begin
if sSmsYn1 <> 'y' then Continue;
end else
if cbSmsUse01.ItemIndex = 2 then
begin
if sSmsYn1 <> 'n' then Continue;
end;
// if sTel1 <> '' then //2,3은 설정값(변수)으로 그리드 추가
begin
ls_Rcrd[4] := sTel1;
if sSmsYn1 = 'y' then ls_Rcrd.Insert(15, '수신')
else ls_Rcrd.Insert(15, '거부');
end;
iRow := CustView1.DataController.AppendRecord;
ls_Rcrd.Insert(0, IntToStr(iRow + 1));
//----------------------------------------------------------------------------------------------
// 고객등급 생성(지사별 설정값 반영)
//----------------------------------------------------------------------------------------------
iTotal := StrToIntDef(ls_rcrd[8], 0);
iComCnt := StrToIntDef(ls_rcrd[9], 0);
iCanCnt := iTotal - icomCnt;
if iTotal = 0 then
iCanRate := 0
else
iCanRate := Round((iCanCnt / iTotal * 100));
sRate := IntToStr(iCanRate) + '%';
ls_Rcrd.Insert(10, sRate);
//-----------------------------------------------------------------------------------------------
CustView1.DataController.Values[iRow, iCuTitle[0]] := ls_Rcrd[0];
CustView1.DataController.Values[iRow, iCuTitle[1]] := ls_Rcrd[1];
CustView1.DataController.Values[iRow, iCuTitle[2]] := ls_Rcrd[2];
CustView1.DataController.Values[iRow, iCuTitle[3]] := strtocall(ls_Rcrd[3]);
CustView1.DataController.Values[iRow, iCuTitle[4]] := ls_Rcrd[4];
CustView1.DataController.Values[iRow, iCuTitle[5]] := strtocall(ls_Rcrd[5]);//전화번호
CustView1.DataController.Values[iRow, iCuTitle[6]] := strtocall(ls_Rcrd[22]); //virtureTel
CustView1.DataController.Values[iRow, iCuTitle[7]] := ls_Rcrd[23];
CustView1.DataController.Values[iRow, iCuTitle[8]] := ls_Rcrd[6];
CustView1.DataController.Values[iRow, iCuTitle[9]] := ls_Rcrd[7];
CustView1.DataController.Values[iRow, iCuTitle[10]] := ls_Rcrd[8];
CustView1.DataController.Values[iRow, iCuTitle[11]] := ls_Rcrd[9];
CustView1.DataController.Values[iRow, iCuTitle[12]] := ls_Rcrd[10];
CustView1.DataController.Values[iRow, iCuTitle[13]] := ls_Rcrd[11];
CustView1.DataController.Values[iRow, iCuTitle[14]] := func_buninSearch(ls_Rcrd[19], ls_Rcrd[3], ls_Rcrd[12]);
CustView1.DataController.Values[iRow, iCuTitle[15]] := ls_Rcrd[13];
CustView1.DataController.Values[iRow, iCuTitle[16]] := ls_Rcrd[14];
CustView1.DataController.Values[iRow, iCuTitle[17]] := StringReplace(ls_Rcrd[15], '/', '', [rfReplaceAll]);
CustView1.DataController.Values[iRow, iCuTitle[18]] := StringReplace(ls_Rcrd[16], '/', '', [rfReplaceAll]);
CustView1.DataController.Values[iRow, iCuTitle[19]] := ls_Rcrd[17];
CustView1.DataController.Values[iRow, iCuTitle[20]] := ls_Rcrd[18];
CustView1.DataController.Values[iRow, iCuTitle[21]] := ls_Rcrd[19];
CustView1.DataController.Values[iRow, iCuTitle[22]] := ls_Rcrd[20];
sEndDate := ls_rcrd[21];
if Trim(sEndDate) <> '' then
CustView1.DataController.Values[iRow, iCuTitle[23]] := copy(sEndDate, 1, 4) +
'-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView1.DataController.Values[iRow, iCuTitle[23]] := '';
sEndDate := ls_rcrd[24];
if Trim(sEndDate) <> '' then
CustView1.DataController.Values[iRow, iCuTitle[24]] := copy(sEndDate, 1, 4) +
'-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView1.DataController.Values[iRow, iCuTitle[24]] := '';
sEndDate := ls_rcrd[25];
if Trim(sEndDate) <> '' then
CustView1.DataController.Values[iRow, iCuTitle[25]] := copy(sEndDate, 1, 4) +
'-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView1.DataController.Values[iRow, iCuTitle[25]] := '';
sEndDate := ls_rcrd[26];
if Trim(sEndDate) <> '' then
CustView1.DataController.Values[iRow, iCuTitle[26]] := copy(sEndDate, 1, 4) +
'-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView1.DataController.Values[iRow, iCuTitle[26]] := '';
CustView1.DataController.Values[iRow, iCuTitle[27]] := ls_Rcrd[27];
CustView1.DataController.Values[iRow, iCuTitle[28]] := ls_Rcrd[28]; //hdno
if Trim(ls_rcrd[30]) <> '' then //고객등록일자
CustView1.DataController.Values[iRow, iCuTitle[29]] := copy(ls_rcrd[30], 1, 4) +
'-' + copy(ls_rcrd[30], 5, 2) + '-' + copy(ls_rcrd[30], 7, 2)
else
CustView1.DataController.Values[iRow, iCuTitle[29]] := '';
CustView1.DataController.Values[iRow, iCuTitle[30]] := GetStrToDateTimeGStr(ls_Rcrd[29], 3); //콜벨등록일
if ls_Rcrd[31] = '' then
CustView1.DataController.Values[iRow, iCuTitle[31]] := '0' //소멸예정마일리지
else
CustView1.DataController.Values[iRow, iCuTitle[31]] := ls_Rcrd[31]; //소멸예정마일리지
if CustView1.DataController.Values[iRow, iCuTitle[31]] <> '0' then
CustView1.DataController.Values[iRow, iCuTitle[32]] := copy(ls_Rcrd[32], 1,10)
else
CustView1.DataController.Values[iRow, iCuTitle[32]] := ''; //소멸예정일
CustView1.DataController.Values[iRow, iCuTitle[33]] := StrToCall(sTel2); //고객번호2
CustView1.DataController.Values[iRow, iCuTitle[34]] := StrToCall(sTel3); //고객번호3
CustView1.DataController.Values[iRow, iCuTitle[35]] := sSmsYn2; //SMS수신거부2
CustView1.DataController.Values[iRow, iCuTitle[36]] := sSmsYn3; //SMS수신거부3
CustView1.DataController.Values[iRow, iCuTitle[37]] := ls_Rcrd[33]; //직책
end;
finally
slTmp.Free;
ls_Rcrd.Free;
end;
end else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
end;
CustView1.EndUpdate;
lbCount01.Caption := '총 ' + IntToStr(CustView1.DataController.RecordCount) + '명';
Screen.Cursor := crDefault;
frm_Main.sbar_Message.Panels[4].Text := '';
end;
3:
begin
sNoSms := '';
for i := 0 to sg_notsms_list.DataController.RecordCount - 1 do
sNoSms := sNoSms + ',' + sg_notsms_list.DataController.Values[i, 2];
CustView2.BeginUpdate;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
ls_rxxml := slList.Strings[j];
if not xdom.loadXML(ls_rxxml) then
begin
Continue;
end;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
Application.ProcessMessages;
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
sEndDate := ls_rcrd[10];
//----------------------------------------------------------------------------------------------
// 대표번호 길이가 8보다 큰경우만 생성
//----------------------------------------------------------------------------------------------
if (trim(ls_rcrd[1]) <> '') then
begin
iRow := CustView2.DataController.FindRecordIndexByText(0, 18 + 1, ls_rcrd[1] + ls_rcrd[3], True, True, True);
//----------------------------------------------------------------------------------------------
// 대표번호 + 고객번호가 같은게 없을때만 생성
//----------------------------------------------------------------------------------------------
if (irow < 0) then
begin
iRow := CustView2.DataController.FindRecordIndexByText(0, 14 + 1, ls_rcrd[0], True, True, True);
//----------------------------------------------------------------------------------------------
// 고객순번이 중복이면 생략
//----------------------------------------------------------------------------------------------
if iRow > 0 then
continue;
if chkNmlPhoneOut02.Checked then
begin
if not CheckHPType(ls_rcrd[3], ErrDesc) then
Continue;
end;
iRow := CustView2.DataController.AppendRecord;
CustView2.DataController.Values[iRow, 19 + 1] := ls_rcrd[1] + ls_rcrd[3];
CustView2.DataController.Values[iRow, 18 + 1] := ls_rcrd[12];
CustView2.DataController.Values[iRow, 16 + 1] := ls_rcrd[11];
CustView2.DataController.Values[iRow, 10 + 1] := ls_rcrd[13];
CustView2.DataController.Values[iRow, 11 + 1] := ls_rcrd[14];
CustView2.DataController.Values[iRow, 1 + 1] := strtocall(ls_rcrd[1]);
CustView2.DataController.Values[iRow, 2 + 1] := ls_rcrd[2];
CustView2.DataController.Values[iRow, 3 + 1] := strtocall(ls_rcrd[3]);
CustView2.DataController.Values[iRow, 4 + 1] := ls_rcrd[4];
CustView2.DataController.Values[iRow, 5 + 1] := ls_rcrd[19];
//----------------------------------------------------------------------------------------------
// 고객등급 생성(지사별 설정값 반영)
//----------------------------------------------------------------------------------------------
iComCnt := StrToIntDef(ls_rcrd[5], 0);
iCanCnt := StrToIntDef(ls_rcrd[6], 0);
iTotal := iComcnt + iCanCnt;
if iTotal = 0 then
iCanRate := 0
else
iCanRate := Round((iCanCnt / iTotal * 100));
CustView2.DataController.Values[iRow, 6 + 1] := IntToStr(iComCnt) + '/' + IntToStr(iCanCnt);
CustView2.DataController.Values[iRow, 7 + 1] := intToStr(iCanRate) + '%';
CustView2.DataController.Values[iRow, 8 + 1] := ls_rcrd[7];
CustView2.DataController.Values[iRow, 9 + 1] := ls_rcrd[8];
CustView2.DataController.Values[iRow, 12 + 1] := ls_rcrd[15];
if Trim(sEndDate) <> '' then
CustView2.DataController.Values[iRow, 13 + 1] := copy(sEndDate, 1, 4) + '-'
+ copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView2.DataController.Values[iRow, 13 + 1] := '';
CustView2.DataController.Values[iRow, 14 + 1] := ls_rcrd[9];
CustView2.DataController.Values[iRow, 15 + 1] := ls_rcrd[0];
CustView2.DataController.Values[iRow, 16 + 1] := '';
if rg_SType.Tag in [0, 1] then
CustView2.DataController.Values[iRow, 20 + 1] := '0'
else
CustView2.DataController.Values[iRow, 20 + 1] := '1';
CustView2.DataController.Values[iRow, 21 + 1] := func_buninSearch(ls_rcrd[9], ls_rcrd[1], ls_rcrd[16]);
iIdx := scb_BranchCode.IndexOf(ls_rcrd[9]);
if iIdx >= 0 then
CustView2.DataController.Values[iRow, 1] := scb_BranchName[iIdx]
else
CustView2.DataController.Values[iRow, 1] := '';
CustView2.DataController.Values[iRow, 22 + 1] := ls_rcrd[17];
CustView2.DataController.Values[iRow, 23 + 1] := ls_rcrd[18];
end;
end;
end;
finally
ls_Rcrd.Free;
end;
end else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
end;
CustView2.EndUpdate;
CustView2.BeginUpdate;
for i := 0 to CustView2.DataController.RecordCount - 1 do
CustView2.DataController.Values[i, 0] := i + 1;
CustView2.EndUpdate;
lbCount02.Caption := '총 ' + IntToStr(CustView2.DataController.RecordCount) + '명';
Screen.Cursor := crDefault;
frm_Main.sbar_Message.Panels[4].Text := '';
end;
4:
begin
for i := 0 to sg_notsms_list.DataController.RecordCount - 1 do
sNoSms := sNoSms + ',' + sg_notsms_list.DataController.Values[i, 2];
CustView2.BeginUpdate;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
ls_rxxml := slList.Strings[j];
if not xdom.loadXML(ls_rxxml) then
begin
Continue;
end;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
Application.ProcessMessages;
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
sEndDate := ''; // ls_rcrd[10];
if (trim(ls_rcrd[1]) <> '') and (length(ls_rcrd[1]) >= 8) then
begin
iRow :=
CustView2.DataController.FindRecordIndexByText(0, 18
+ 1, ls_rcrd[1] + ls_rcrd[3], True, True, True);
if (irow < 0) then
begin
if cb_Sms_Gubun.ItemIndex in [1, 2] then
begin
iRow := pos(ls_rcrd[1] + ls_rcrd[3], sNoSms);
if (cb_Sms_Gubun.ItemIndex = 1) and (iRow > 0) then
continue;
if (cb_Sms_Gubun.ItemIndex = 2) and (iRow = 0) then
continue;
end;
if rrb_st_cancel.Checked then
begin
if lb_st_customer.IndexOf(ls_rcrd[1] + ls_rcrd[3]) > 0 then
begin
iRow := CustView2.DataController.FindRecordIndexByText(0, 18 + 1,
ls_rcrd[1] + ls_rcrd[3], True, True, True);
if iRow >= 0 then
CustView2.DataController.DeleteRecord(iRow);
continue;
end else
begin
if ls_rcrd[12] <> '8' then
begin
lb_st_customer.Add(ls_rcrd[1] + ls_rcrd[3]);
continue;
end;
end;
end else
if rrb_st_req.Checked then
begin
if lb_st_customer.IndexOf(ls_rcrd[1] + ls_rcrd[3]) > 0 then
begin
iRow := CustView2.DataController.FindRecordIndexByText(0, 18 + 1,
ls_rcrd[1] + ls_rcrd[3], True, True, True);
if iRow >= 0 then
CustView2.DataController.DeleteRecord(iRow);
continue;
end else
begin
if ls_rcrd[12] <> '4' then
begin
lb_st_customer.Add(ls_rcrd[1] + ls_rcrd[3]);
continue;
end;
end;
end;
if chkNmlPhoneOut02.Checked then
begin
if not CheckHPType(ls_rcrd[3], ErrDesc) then
Continue;
end;
iRow := CustView2.DataController.AppendRecord;
CustView2.DataController.Values[iRow, 19 + 1] := ls_rcrd[1] + ls_rcrd[3];
CustView2.DataController.Values[iRow, 18 + 1] := ls_Rcrd[17]; // [hjf] SMS수신여부 추가
CustView2.DataController.Values[iRow, 17 + 1] := ls_Rcrd[11];
CustView2.DataController.Values[iRow, 10 + 1] := ls_Rcrd[13];
CustView2.DataController.Values[iRow, 11 + 1] := ls_Rcrd[14];
CustView2.DataController.Values[iRow, 1 + 1] := strtocall(ls_rcrd[1]);
CustView2.DataController.Values[iRow, 2 + 1] := ls_rcrd[2];
CustView2.DataController.Values[iRow, 3 + 1] := strtocall(ls_rcrd[3]);
CustView2.DataController.Values[iRow, 4 + 1] := ls_rcrd[4];
CustView2.DataController.Values[iRow, 5 + 1] := ls_rcrd[19];
iComCnt := StrToIntDef(ls_rcrd[5], 0);
iCanCnt := StrToIntDef(ls_rcrd[6], 0);
iTotal := iComcnt + iCanCnt;
if iTotal = 0 then
iCanRate := 0
else
iCanRate := Round((iCanCnt / iTotal * 100));
CustView2.DataController.Values[iRow, 6 + 1] := IntToStr(iComCnt) + '/' +
IntToStr(iCanCnt);
CustView2.DataController.Values[iRow, 7 + 1] := intToStr(iCanRate) + '%';
CustView2.DataController.Values[iRow, 8 + 1] := ls_rcrd[7];
CustView2.DataController.Values[iRow, 9 + 1] := ls_rcrd[8];
CustView2.DataController.Values[iRow, 12 + 1] := ls_rcrd[10];
if Trim(sEndDate) <> '' then
CustView2.DataController.Values[iRow, 13 + 1] := copy(sEndDate, 1, 4)
+ '-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView2.DataController.Values[iRow, 13 + 1] := '';
CustView2.DataController.Values[iRow, 14 + 1] := ls_rcrd[9];
CustView2.DataController.Values[iRow, 15 + 1] := ls_rcrd[0];
if rg_SType.Tag in [0, 1] then
CustView2.DataController.Values[iRow, 20 + 1] := '0'
else
CustView2.DataController.Values[iRow, 20 + 1] := '1';
if ls_Rcrd[12] = 'A' then
CustView2.DataController.Values[iRow, 16 + 1] := lb_Status.Items.Strings[10]
else
if ls_Rcrd[12] = 'D' then
CustView2.DataController.Values[iRow, 16 + 1] := lb_Status.Items.Strings[14]
else
if ls_Rcrd[12] = 'B' then
CustView2.DataController.Values[iRow, 16 + 1] := lb_Status.Items.Strings[1]
else
if ls_Rcrd[12] = 'R' then
CustView2.DataController.Values[iRow, 16 + 1] := lb_Status.Items.Strings[11]
else
if ls_Rcrd[12] = 'L' then
CustView2.DataController.Values[iRow, 16 + 1] := lb_Status.Items.Strings[12]
else
if ls_Rcrd[12] = 'U' then
CustView2.DataController.Values[iRow, 16 + 1] := lb_Status.Items.Strings[13]
else
CustView2.DataController.Values[iRow, 16 + 1] := lb_Status.Items.Strings[StrToIntDef(ls_Rcrd[12], 0)];
CustView2.DataController.Values[iRow, 21 + 1] := func_buninSearch(ls_rcrd[9], ls_rcrd[1], ls_rcrd[16]);
iIdx := scb_BranchCode.IndexOf(ls_rcrd[9]);
if iIdx >= 0 then
CustView2.DataController.Values[iRow, 1] := scb_BranchName[iIdx]
else
CustView2.DataController.Values[iRow, 1] := '';
end;
end;
end;
finally
ls_Rcrd.Free;
end;
end else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
end;
CustView2.EndUpdate;
CustView2.BeginUpdate;
for i := 0 to CustView2.DataController.RecordCount - 1 do
CustView2.DataController.Values[i, 0] := i + 1;
CustView2.EndUpdate;
lbCount02.Caption := '총 ' + IntToStr(CustView2.DataController.RecordCount) + '명';
frm_Main.sbar_Message.Panels[4].Text := '';
end;
5:
begin
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
ls_rxxml := slList.Strings[j];
if not xdom.loadXML(ls_rxxml) then
begin
Continue;
end;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
for i := 0 to lst_Result.length - 1 do
begin
Application.ProcessMessages;
lbNoSms.Add(GetTextSeperationFirst('│', lst_Result.item[i].attributes.getNamedItem('Value').Text));
end;
end;
end;
if rg_SType.Tag = 2 then
cb_Sms_Gubun.ItemIndex := 0;
sList := TStringList.Create;
sList.Sorted := True;
sList.Duplicates := dupignore;
if FileExists(DBDIRECTORY + 'SMS_NOT_ARGEE.TXT') then
sLIst.LoadFromFile(DBDIRECTORY + 'SMS_NOT_ARGEE.TXT');
Application.ProcessMessages;
sList.AddStrings(lbNoSms);
if sList.IndexOf('0100') = -1 then
begin
sList.Add('0100');
sList.Add('0101');
sList.Add('0102');
sList.Add('0103');
sList.Add('0104');
sList.Add('0105');
sList.Add('0106');
sList.Add('0107');
sList.Add('0108');
sList.Add('0109');
sList.Add('0110');
sList.Add('0160');
sList.Add('0170');
sList.Add('0180');
sList.Add('0190');
sList.Add('0200');
end;
if sList.IndexOf('0100') > 0 then
begin
while sList.Strings[0] <> '0100' do
begin
sList.Delete(0);
end;
end;
sList.SaveToFile(DBDIRECTORY + 'SMS_NOT_ARGEE.TXT');
sList.Free;
lbNoSms.Clear;
frm_Main.sbar_Message.Panels[4].Text := '';
Screen.Cursor := crDefault;
end;
6:
begin
CustView3.BeginUpdate;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
ls_rxxml := slList.Strings[j];
if not xdom.loadXML(ls_rxxml) then
begin
continue;
end;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
Application.ProcessMessages;
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
sEndDate := ls_rcrd[12];
if chkCust03Type05.Checked then
begin
if not CheckHPType(ls_rcrd[4], ErrDesc) then
Continue;
end;
if ls_rcrd[4] = '' then
Continue;
iRow := CustView3.DataController.AppendRecord;
CustView3.DataController.Values[iRow, 0] := iRow + 1;
CustView3.DataController.Values[iRow, 1] := ls_rcrd[0];
CustView3.DataController.Values[iRow, 2] := ls_rcrd[1];
CustView3.DataController.Values[iRow, 3] := strtocall(ls_rcrd[2]);
CustView3.DataController.Values[iRow, 4] := ls_rcrd[3];
CustView3.DataController.Values[iRow, 5] := strtocall(ls_rcrd[4]);
CustView3.DataController.Values[iRow, 6] := ls_rcrd[5];
CustView3.DataController.Values[iRow, 7] := ls_rcrd[6];
CustView3.DataController.Values[iRow, 8] := ls_rcrd[7] + '%';
CustView3.DataController.Values[iRow, 9] := ls_rcrd[8];
CustView3.DataController.Values[iRow, 10] := ls_rcrd[9];
CustView3.DataController.Values[iRow, 11] := ls_rcrd[10];
CustView3.DataController.Values[iRow, 12] := ls_rcrd[11];
if Trim(sEndDate) <> '' then
CustView3.DataController.Values[iRow, 13] := Copy(sEndDate, 1, 4) + '-' +
Copy(sEndDate, 5, 2) + '-' +
Copy(sEndDate, 7, 2)
else
CustView3.DataController.Values[iRow, 13] := '';
CustView3.DataController.Values[iRow, 14] := ls_rcrd[13];
CustView3.DataController.Values[iRow, 15] := ls_rcrd[14];
CustView3.DataController.Values[iRow, 16] := ls_rcrd[15];
if ls_rcrd.Count > 16 then
CustView3.DataController.Values[iRow, 17] := ls_rcrd[16];
if ls_Rcrd[17] = '' then
CustView3.DataController.Values[iRow, 18] := '0' //소멸예정마일리지
else
CustView3.DataController.Values[iRow, 18] := formatfloat('#,##0', StrToFloatDef(ls_Rcrd[17], 0)); //소멸예정마일리지
CustView3.DataController.Values[iRow, 19] := GetStrToDateTimeGStr(ls_Rcrd[18], 4); //소멸예정일
end;
finally
ls_Rcrd.Free;
end;
end else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
end;
CustView3.EndUpdate;
lbCount03.Caption := '총 ' + IntToStr(CustView3.DataController.RecordCount) + '명';
frm_Main.sbar_Message.Panels[4].Text := '';
Screen.Cursor := crDefault;
end;
7:
begin
CustView4.BeginUpdate;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
ls_rxxml := slList.Strings[j];
if not xdom.loadXML(ls_rxxml) then
begin
continue;
end;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
Application.ProcessMessages;
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
if chkCust04Type10.Checked then
begin
if not CheckHPType(ls_rcrd[4], ErrDesc) then Continue;
end;
sEndDate := ls_rcrd[13];
if ls_rcrd[4] = '' then Continue;
iRow := CustView4.DataController.AppendRecord;
CustView4.DataController.Values[iRow, 0] := iRow + 1;
CustView4.DataController.Values[iRow, 1] := ls_rcrd[0];
CustView4.DataController.Values[iRow, 2] := ls_rcrd[1];
CustView4.DataController.Values[iRow, 3] := strtocall(ls_rcrd[2]);
CustView4.DataController.Values[iRow, 4] := ls_rcrd[3];
CustView4.DataController.Values[iRow, 5] := strtocall(ls_rcrd[4]);
CustView4.DataController.Values[iRow, 6] := ls_rcrd[5];
CustView4.DataController.Values[iRow, 7] := ls_rcrd[6];
CustView4.DataController.Values[iRow, 8] := ls_rcrd[7];
CustView4.DataController.Values[iRow, 9] := ls_rcrd[8] + '%';
CustView4.DataController.Values[iRow, 10] := ls_rcrd[9];
CustView4.DataController.Values[iRow, 11] := ls_rcrd[10];
CustView4.DataController.Values[iRow, 12] := ls_rcrd[11];
CustView4.DataController.Values[iRow, 13] := ls_rcrd[12];
if Trim(sEndDate) <> '' then
CustView4.DataController.Values[iRow, 14] := Copy(sEndDate, 1, 4) + '-' +
Copy(sEndDate, 5, 2) + '-' +
Copy(sEndDate, 7, 2)
else
CustView4.DataController.Values[iRow, 14] := '';
CustView4.DataController.Values[iRow, 15] := ls_rcrd[14];
CustView4.DataController.Values[iRow, 16] := ls_rcrd[15];
CustView4.DataController.Values[iRow, 17] := ls_rcrd[16];
CustView4.DataController.Values[iRow, 18] := ls_rcrd[17];
CustView4.DataController.Values[iRow, 19] := ls_rcrd[18];
if ls_rcrd.Count > 19 then
CustView4.DataController.Values[iRow, 20] := ls_rcrd[19];
end;
finally
ls_Rcrd.Free;
end;
end else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
end;
CustView4.EndUpdate;
lbCount04.Caption := '총 ' + IntToStr(CustView4.DataController.RecordCount) + '명';
frm_Main.sbar_Message.Panels[4].Text := '';
Screen.Cursor := crDefault;
end;
8:
begin
CustView6.BeginUpdate;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
//- frm_Main.sbar_Message.Panels[4].Text := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
ls_rxxml := slList.Strings[j];
if not xdom.loadXML(ls_rxxml) then
begin
continue;
end;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
Application.ProcessMessages;
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
if chkCust06Type06.Checked then
begin
if not CheckHPType(ls_rcrd[4], ErrDesc) then
Continue;
end;
if ls_rcrd[4] = '' then
Continue;
sEndDate := ls_rcrd[11];
iRow := CustView6.DataController.AppendRecord;
CustView6.DataController.Values[iRow, 0] := iRow + 1;
CustView6.DataController.Values[iRow, 1] := ls_rcrd[0];
CustView6.DataController.Values[iRow, 2] := ls_rcrd[1];
CustView6.DataController.Values[iRow, 3] := strtocall(ls_rcrd[2]);
CustView6.DataController.Values[iRow, 4] := ls_rcrd[3];
CustView6.DataController.Values[iRow, 5] := strtocall(ls_rcrd[4]);
CustView6.DataController.Values[iRow, 6] := ls_rcrd[5];
CustView6.DataController.Values[iRow, 7] := ls_rcrd[6];
CustView6.DataController.Values[iRow, 8] := ls_rcrd[7];
CustView6.DataController.Values[iRow, 9] := ls_rcrd[8] + '%';
CustView6.DataController.Values[iRow, 10] := ls_rcrd[9];
CustView6.DataController.Values[iRow, 11] := ls_rcrd[10];
CustView6.DataController.Values[iRow, 13] := ls_rcrd[12];
CustView6.DataController.Values[iRow, 14] := ls_rcrd[13];
CustView6.DataController.Values[iRow, 15] := ls_rcrd[14];
CustView6.DataController.Values[iRow, 16] := ls_rcrd[15];
if Trim(sEndDate) <> '' then
CustView6.DataController.Values[iRow, 12] := copy(sEndDate, 1, 4) +
'-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView6.DataController.Values[iRow, 12] := '';
end;
finally
ls_Rcrd.Free;
end;
end else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
end;
CustView6.EndUpdate;
lbCount06.Caption := '총 ' + IntToStr(CustView6.DataController.RecordCount) + '명';
frm_Main.sbar_Message.Panels[4].Text := '';
Screen.Cursor := crDefault;
end;
10:
begin
GMessagebox('마일리지를 설정하였습니다.', CDMSI);
end;
11: //sel06으로 대체 후 사용안함 20190420 KHS
begin
CustView9.BeginUpdate;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
//-- frm_Main.sbar_Message.Panels[4].Text := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
ls_rxxml := slList.Strings[j];
if not xdom.loadXML(ls_rxxml) then
begin
continue;
end;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
Application.ProcessMessages;
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
iRow := CustView9.DataController.AppendRecord;
CustView9.DataController.Values[iRow, 0] := iRow + 1;
CustView9.DataController.Values[iRow, 1] := ls_rcrd[0];
CustView9.DataController.Values[iRow, 2] := ls_rcrd[1];
iIdx := scb_BranchCode.IndexOf(ls_rcrd[1]);
if iIdx >= 0 then
CustView9.DataController.Values[iRow, 3] := scb_BranchName[iIdx]
else
CustView9.DataController.Values[iRow, 3] := '';
CustView9.DataController.Values[iRow, 4] := strtocall(ls_rcrd[2]);
case StrToIntDef(ls_rcrd[3], 0) of
0: CustView9.DataController.Values[iRow, 5] := '일반';
1: CustView9.DataController.Values[iRow, 5] := '업소';
3: CustView9.DataController.Values[iRow, 5] := '법인';
4: CustView9.DataController.Values[iRow, 5] := '주말골프';
end;
CustView9.DataController.Values[iRow, 6] := ls_rcrd[4];
CustView9.DataController.Values[iRow, 7] := strtocall(ls_rcrd[5]);
if StrToIntDef(ls_Rcrd[6], 0) = 0 then
ls_Rcrd[6] := '0';
if StrToIntDef(ls_Rcrd[7], 0) = 0 then
ls_Rcrd[7] := '0';
if StrToIntDef(ls_Rcrd[8], 0) = 0 then
ls_Rcrd[8] := '0';
CustView9.DataController.Values[iRow, 8] := ls_rcrd[6];
CustView9.DataController.Values[iRow, 9] := ls_rcrd[7];
CustView9.DataController.Values[iRow, 10] := ls_rcrd[8];
if ls_rcrd[9] = 'y' then
CustView9.DataController.Values[iRow, 11] := '인증'
else
CustView9.DataController.Values[iRow, 11] := '미인증';
CustView9.DataController.Values[iRow, 12] := ls_rcrd[10];
sEndDate := ls_rcrd[11];
if Trim(sEndDate) <> '' then
CustView9.DataController.Values[iRow, 13] := copy(sEndDate, 1, 4) + '-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView9.DataController.Values[iRow, 13] := '';
sEndDate := ls_rcrd[12];
if Trim(sEndDate) <> '' then
CustView9.DataController.Values[iRow, 14] := copy(sEndDate, 1, 4) + '-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView9.DataController.Values[iRow, 14] := '';
CustView9.DataController.Values[iRow, 15] := ls_rcrd[13];
CustView9.DataController.Values[iRow, 16] := ls_rcrd[14];
CustView9.DataController.Values[iRow, 17] := ls_rcrd[15];
if StrToIntDef(ls_Rcrd[16], 0) = 0 then
ls_Rcrd[16] := '0';
CustView9.DataController.Values[iRow, 18] := ls_rcrd[16];
CustView9.DataController.Values[iRow, 19] := ls_rcrd[17];
if ls_rcrd.Count > 18 then
CustView9.DataController.Values[iRow, 20] := StrToFloatDef(ls_rcrd[18], 0);
if ls_Rcrd[19] = '' then
CustView9.DataController.Values[iRow, 21] := '0' //소멸예정마일리지
else
CustView9.DataController.Values[iRow, 21] := formatfloat('#,##0', StrToFloatDef(ls_Rcrd[19], 0)); //소멸예정마일리지
CustView9.DataController.Values[iRow, 22] := GetStrToDateTimeGStr(ls_Rcrd[20], 4); //소멸예정일
if ls_rcrd[21] = 'y' then CustView9.DataController.Values[iRow, 23] := '수신'
else CustView9.DataController.Values[iRow, 23] := '거부';
if ls_rcrd.Count > 22 then
begin
CustView9.DataController.Values[iRow, 24] := StrToFloatDef(ls_rcrd[22], 0); //적립합계
CustView9.DataController.Values[iRow, 25] := StrToFloatDef(ls_rcrd[23], 0); //지급합계
end;
end;
finally
ls_Rcrd.Free;
end;
end else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
end;
CustView9.EndUpdate;
lbCount09.Caption := '총 ' + IntToStr(CustView9.DataController.RecordCount) + '명';
frm_Main.sbar_Message.Panels[4].Text := '';
Screen.Cursor := crDefault;
end;
12:
begin
CustView10.BeginUpdate;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
//- frm_Main.sbar_Message.Panels[4].Text := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
ls_rxxml := slList.Strings[j];
if not xdom.loadXML(ls_rxxml) then
begin
continue;
end;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
Application.ProcessMessages;
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
iRow := CustView10.DataController.AppendRecord;
CustView10.DataController.Values[iRow, 0] := iRow + 1;
CustView10.DataController.Values[iRow, 1] := ls_rcrd[0];
CustView10.DataController.Values[iRow, 2] := ls_rcrd[1];
iIdx := scb_BranchCode.IndexOf(ls_rcrd[1]);
if iIdx >= 0 then
CustView10.DataController.Values[iRow, 3] := scb_BranchName[iIdx]
else
CustView10.DataController.Values[iRow, 3] := '';
CustView10.DataController.Values[iRow, 4] := strtocall(ls_rcrd[2]);
case StrToIntDef(ls_rcrd[3], 0) of
0: CustView10.DataController.Values[iRow, 5] := '일반';
1: CustView10.DataController.Values[iRow, 5] := '업소';
3: CustView10.DataController.Values[iRow, 5] := '법인';
4: CustView10.DataController.Values[iRow, 5] := '주말골프';
end;
CustView10.DataController.Values[iRow, 6] := ls_rcrd[4];
CustView10.DataController.Values[iRow, 7] := strtocall(ls_rcrd[5]);
if ls_rcrd[6] = 'y' then
CustView10.DataController.Values[iRow, 8] := '인증'
else
CustView10.DataController.Values[iRow, 8] := '미인증';
sEndDate := ls_rcrd[7];
if Trim(sEndDate) <> '' then
CustView10.DataController.Values[iRow, 9] := copy(sEndDate, 1, 4) +
'-' + copy(sEndDate, 5, 2) + '-' + copy(sEndDate, 7, 2)
else
CustView10.DataController.Values[iRow, 9] := '';
if StrToIntDef(ls_Rcrd[8], 0) = 0 then
ls_Rcrd[8] := '0';
if StrToIntDef(ls_Rcrd[9], 0) = 0 then
ls_Rcrd[9] := '0';
CustView10.DataController.Values[iRow, 10] := ls_rcrd[8];
CustView10.DataController.Values[iRow, 11] := ls_rcrd[9];
CustView10.DataController.Values[iRow, 12] := ls_rcrd[10];
CustView10.DataController.Values[iRow, 13] := ls_rcrd[11];
CustView10.DataController.Values[iRow, 14] := ls_rcrd[12];
CustView10.DataController.Values[iRow, 15] := ls_rcrd[13];
end;
finally
ls_Rcrd.Free;
end;
end else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
end;
CustView10.EndUpdate;
lbCount10.Caption := '총 ' + IntToStr(CustView10.DataController.RecordCount) + '명';
frm_Main.sbar_Message.Panels[4].Text := '';
end;
80:
begin
cxViewOKC.BeginUpdate;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
//- frm_Main.sbar_Message.Panels[4].Text := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
ls_rxxml := slList.Strings[j];
if not xdom.loadXML(ls_rxxml) then
begin
continue;
end;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
cxViewOKC.DataController.SetRecordCount(0);
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
Application.ProcessMessages;
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
iRow := cxViewOKC.DataController.AppendRecord;
cxViewOKC.DataController.Values[iRow, 0] := iRow + 1;
cxViewOKC.DataController.Values[iRow, 1] := GetStrToLongDateTimeStr(ls_rcrd[0]);
cxViewOKC.DataController.Values[iRow, 2] := ls_rcrd[1];
cxViewOKC.DataController.Values[iRow, 3] := strtocall(ls_rcrd[2]);
cxViewOKC.DataController.Values[iRow, 4] := GetOKCashBackStr(ls_rcrd[3]);
cxViewOKC.DataController.Values[iRow, 5] := ls_rcrd[4];
cxViewOKC.DataController.Values[iRow, 6] := StrToIntDef(ls_rcrd[5], 0);
cxViewOKC.DataController.Values[iRow, 7] := ls_rcrd[6];
cxViewOKC.DataController.Values[iRow, 8] := ls_rcrd[7];
cxViewOKC.DataController.Values[iRow, 9] := StrToIntDef(ls_rcrd[8], 0);
cxViewOKC.DataController.Values[iRow, 10] := StrToIntDef(ls_rcrd[9], 0);
cxViewOKC.DataController.Values[iRow, 11] := GetStrToLongDateTimeStr(ls_rcrd[10]);
cxViewOKC.DataController.Values[iRow, 12] := ls_rcrd[11];
end;
finally
ls_Rcrd.Free;
end;
end else
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
end;
end;
cxViewOKC.EndUpdate;
frm_Main.sbar_Message.Panels[4].Text := '';
end;
end;
end else
begin
Screen.Cursor := crDefault;
GMessagebox(MSG012 + CRLF + ls_MSG_Err, CDMSE);
end;
finally
Screen.Cursor := crDefault;
xdom := Nil;
end;
except
cxPageControl1.Enabled := True;
{ cxGroupBox1.Enabled := True;
cxGroupBox11.Enabled := True;
cxGroupBox17.Enabled := True;
cxGroupBox16.Enabled := True;
cxGroupBox28.Enabled := True;
cxGroupBox37.Enabled := True;
cxGroupBox30.Enabled := True;
cxGroupBox46.Enabled := True;
cxGroupBox50.Enabled := True; }
Screen.Cursor := crDefault;
end;
end;
procedure TFrm_CUT.proc_SleepSearch;
var
ls_TxLoad, sWhere: string;
slReceive: TStringList;
ErrCode: integer;
sms_use1, sms_use2: string;
begin
dt_sysdate2 := frm_main.func_sysdate;
if Trim(dt_sysdate2) = '' then
begin
GMessagebox('조회중입니다. 잠시만 기다려주세요', CDMSE);
Exit;
end;
if (length(dt_sysdate2) <> 14) or ((StrToInt(copy(dt_sysdate2, 9, 4)) > 2100) or (StrToInt(copy(dt_sysdate2, 9, 4)) < 100)) then
begin
GMessagebox('오후 9시부터 오전 1시 사이에는 고객을 검색할 수 없습니다.', CDMSE);
Exit;
end;
if (GT_USERIF.LV = '10') and ((GT_SEL_BRNO.GUBUN <> '1') or (GT_SEL_BRNO.BrNo <> GT_USERIF.BR)) then
begin
GMessagebox('상담원 권한은 소속 지사만 조회할수 있습니다.', CDMSE);
Exit;
end;
if fGetChk_Search_HdBrNo('휴먼고객') then Exit;
if not chkCust06Type03.Checked then
begin
if CustView6.DataController.RecordCount > 0 then
Exit;
end;
//////////////////////////////////////////////////////////////////////////////
// 고객>휴면고객]10000건/콜마너/대표번호:전체/최종이용:XXXXXXXX/SMS수신
FExcelDownSleep := Format('%s/대표번호:%s/%s/%s',
[
GetSelBrInfo
, cbKeynumber06.Text
, IfThen(rbCust06Type01.Checked,
Format('최종이용일:%s', [cxDate6_1.Text]),
Format('기간내미사용:%s~%s', [cxDate14.Text, cxDate15.Text]))
, cbSmsUse06.Text
]);
//////////////////////////////////////////////////////////////////////////////
sWhere := '';
if cxBrNo6.Text <> '' then
sWhere := sWhere + ' AND C.BR_NO = ''' + cxBrNo6.Text + ''' ';
if (cbKeynumber06.Text <> '전체') and (cbKeynumber06.Text <> '') then
sWhere := sWhere + ' AND C.KEY_NUMBER = ''' + StringReplace(cbKeynumber06.Text, '-', '', [rfReplaceAll]) + ''' ';
case cbGubun6_1.ItemIndex of
1: sWhere := sWhere + ' AND C.CU_TYPE = ''0'' ';
2: sWhere := sWhere + ' AND C.CU_TYPE = ''1'' ';
3: sWhere := sWhere + ' AND C.CU_TYPE = ''3'' ';
end;
// [hjf]
case cbSmsUse06.ItemIndex of
1:
begin
sms_use1 := 'y';
sms_use2 := '0';
end;
2:
begin
sms_use1 := '0';
sms_use2 := 'n';
end;
else
begin
sms_use1 := 'y';
sms_use2 := 'n';
end;
end;
if cbLevel06.ItemIndex > 0 then
sWhere := sWhere + ' AND C.CU_LEVEL_CD = ''' + SCboLevelSeq[cbLevel06.itemindex] + ''' ';
if chkCust06Type02.Checked then
sWhere := sWhere + ' AND C.CU_TYPE != ''3'' ';
if rbCust06Type01.Checked then
begin
if cxDate6_1.Enabled then
begin
if (cxDate6_1.Text <> '') then
begin
if chkCust06Type01.Checked then
sWhere := sWhere + format(' AND (''%s'' >= C.CU_LAST_END or C.CU_LAST_END is null) ' , [formatdatetime('yyyymmdd', cxDate6_1.Date)])
else
sWhere := sWhere + format(' AND ''%s'' >= C.CU_LAST_END ' , [formatdatetime('yyyymmdd', cxDate6_1.Date)]);
end;
end;
if chkCust06Type01.Checked then
begin
sWhere := sWhere + ' AND C.CU_ENDCNT = 0 ';
end;
end else
if rbCust06Type02.Checked then
begin
if cxDate14.Enabled then
begin
if (cxDate14.Text <> '') and (cxDate15.Text <> '') then
sWhere := sWhere + format(' AND C.CU_LAST_END NOT BETWEEN ''%s'' AND ''%s'' ' , [formatdatetime('yyyymmdd', cxDate14.Date),
formatdatetime('yyyymmdd', cxDate15.Date)])
else if (cxDate14.Text <> '') and (cxDate15.Text = '') then
sWhere := sWhere + format(' AND ''%s'' >= C.CU_LAST_END ' , [formatdatetime('yyyymmdd', cxDate14.Date)])
else if (cxDate14.Text = '') and (cxDate15.Text <> '') then
sWhere := sWhere + format(' AND C.CU_LAST_END >= ''%s'' ' , [formatdatetime('yyyymmdd', cxDate15.Date)]);
end;
end;
// 최근 6개월 이내 이용고객만 조회
sWhere := sWhere + Format(' AND C.CU_LAST_END > ''%s'' ', [FormatDateTime('yyyymmdd', IncMonth(Now, -6))]);
// 저장된 쿼리가 select ~~ from (select ~ from where [condition] 형식으로 저장되어 있음(우괄호 반드시 필요)
sWhere := sWhere + ')';
ls_TxLoad := GetSel04(self.Caption + '8', 'CUSTOMER23', '', sWhere, [sms_use1, sms_use2, cxHdNo6.Text]);
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
cxPageControl1.Enabled := False;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
cxPageControl1.Enabled := True;
Frm_Flash.Hide;
end;
end;
procedure TFrm_CUT.proc_SND_SMS(sGrid: TcxGridDBTableView; ASubscribe: Boolean);
var
i, iBrNo, iCustTel, iCustName, iKeyNum, iCnt, RowIdx, iRow, KeyRow, ikey_cnt, iMile, iSmsYn: Integer;
sCustTel, sSmsYn: string;
slTmp : THashedStringList;
begin
GS_CUTSMS := True;
if sGrid.Name = 'CustView9' then
begin
iBrNo := sGrid.GetColumnByFieldName('지사코드').Index;
iCustTel := sGrid.GetColumnByFieldName('고객번호').Index;
iCustName := sGrid.GetColumnByFieldName('고객명').Index;
iKeyNum := sGrid.GetColumnByFieldName('대표번호').Index;
iMile := sGrid.GetColumnByFieldName('현재마일리지').Index;
iSmsYn := sGrid.GetColumnByFieldName('SMS수신거부').Index;
end else
begin
iBrNo := sGrid.GetColumnByFieldName('지사코드').Index;
iCustTel := sGrid.GetColumnByFieldName('고객번호').Index;
iCustName := sGrid.GetColumnByFieldName('고객명').Index;
iKeyNum := sGrid.GetColumnByFieldName('대표번호').Index;
iMile := sGrid.GetColumnByFieldName('마일리지').Index;
iSmsYn := sGrid.GetColumnByFieldName('SMS수신거부').Index;
end;
iCnt := 0;
Frm_Main.procMenuCreateActive(1001, 'SMS발송');
Frm_SMS.chkBalsin.Enabled := True;
Frm_SMS.cxViewSms.DataController.SetRecordCount(0);
Frm_SMS.cxViewKeyNum.DataController.SetRecordCount(0);
Frm_SMS.cxViewSms.BeginUpdate;
Frm_SMS.cxViewKeyNum.BeginUpdate;
slTmp := THashedStringList.Create;
Try
Screen.Cursor := crHourGlass;
for I := 0 to sGrid.DataController.RecordCount - 1 do
begin
if sGrid.ViewData.Records[i].Selected then
begin
sCustTel := StringReplace(sGrid.ViewData.Records[I].Values[iCustTel], '-', '', [rfreplaceAll]);
if slTmp.IndexOf(sCustTel) > -1 then Continue;
slTmp.add(sCustTel);
if ASubscribe and (iSmsYn <> -1) then
sSmsYn := sGrid.ViewData.Records[I].Values[iSmsYn]
else
sSmsYn := 'y';
if (Copy(sCustTel, 1, 2) = '01') and (Length(sCustTel) in [10, 11]) and
((sSmsYn = 'y') or (sSmsYn = '수신')) then
begin
// 전송내역 구성
RowIdx := Frm_SMS.cxViewSms.DataController.AppendRecord;
// 0, 지사코드
Frm_SMS.cxViewSms.DataController.Values[RowIdx, 0] := sGrid.ViewData.Records[I].Values[iBrNo];
// 1, 대표번호
Frm_SMS.cxViewSms.DataController.Values[RowIdx, 1] := StringReplace(sGrid.ViewData.Records[I].Values[iKeyNum], '-', '', [rfreplaceAll]);
// 2, 고객번호
Frm_SMS.cxViewSms.DataController.Values[RowIdx, 2] := StringReplace(sGrid.ViewData.Records[I].Values[iCustTel], '-', '', [rfreplaceAll]);
// 3, 고객명
Frm_SMS.cxViewSms.DataController.Values[RowIdx, 3] := sGrid.ViewData.Records[I].Values[iCustName];
// 4, 마일리지
Frm_SMS.cxViewSms.DataController.Values[RowIdx, 6] := sGrid.ViewData.Records[I].Values[iMile];
Inc(icnt);
// 대표전화별 전송수 카운팅
iRow := Frm_SMS.cxViewKeyNum.DataController.FindRecordIndexByText(0, 1,
Frm_SMS.cxViewSms.DataController.Values[RowIdx, 1], True, True, True);
if iRow = -1 then
begin
KeyRow := Frm_SMS.cxViewKeyNum.DataController.AppendRecord;
Frm_SMS.cxViewKeyNum.DataController.Values[KeyRow, 0] := Frm_SMS.cxViewSms.DataController.Values[RowIdx, 0];
Frm_SMS.cxViewKeyNum.DataController.Values[KeyRow, 1] := Frm_SMS.cxViewSms.DataController.Values[RowIdx, 1];
Frm_SMS.cxViewKeyNum.DataController.Values[KeyRow, 2] := 1;
end else
begin
ikey_cnt := Integer(Frm_SMS.cxViewKeyNum.DataController.Values[iRow, 2]);
Inc(ikey_cnt);
Frm_SMS.cxViewKeyNum.DataController.SetValue(iRow, 2, ikey_cnt);
end;
end;
end;
end;
Frm_SMS.cxViewSms.EndUpdate;
Frm_SMS.cxViewKeyNum.EndUpdate;
Frm_SMS.cxViewSms.Columns[1].SortOrder := soAscending;
Frm_SMS.mmoAfter.Text := IntToStr(iCnt);
// 외부에서 호출함수
Frm_SMS.proc_branch_sms;
Frm_SMS.Show;
Frm_SMS.cxBtnHelp.Click;
Finally
Screen.Cursor := crDefault;
slTmp.Free;
End;
end;
procedure TFrm_CUT.proc_VirtureNum;
var Param, XmlData, ErrMsg: string;
ErrCode, iCnt : Integer;
slList, StrList: TStringList;
j : Integer;
tmpCnt: integer;
tmpCntStr: string;
k: Integer;
tmpStr: string;
ArrSt: array of string;
iRow: integer;
sBrNo : string;
begin
sBrNo := cxBrNo5.Text;
Screen.Cursor := crHourGlass;
if ((sBrNo <> 'B811') and (sBrNo <> 'G640') and (sBrNo <> 'B100') and (sBrNo <> 'C468')) or (GS_PRJ_AREA = 'O') then
begin
ShowMessage('안심번호 설정은 신청한 지사를 선택하셔야 합니다.' + #13#10 + #13#10
+ '문의사항은 콜마너 업무게시판에 등록해 주세요.');
Screen.Cursor := crDefault;
cxGridDBTableView1.DataController.SetRecordCount(0);
Exit;
end;
Param := '';
slList := TStringList.Create;
try
if not RequestBasePaging(GetSel05('GET_VIRTUAL_TEL_LIST', 'MNG_CUST.GET_VIRTUAL_TEL_LIST', '1000',Param), slList, ErrCode, ErrMsg) then
begin
ShowMessage(Format('[%d] %s', [ErrCode, ErrMsg]));
Screen.Cursor := crDefault;
Exit;
end;
cxGridDBTableView1.DataController.SetRecordCount(0);
iCnt := 1;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
xmlData := slList.Strings[j];
if Pos('<Data Count="',xmlData)>0 then
begin
tmpCntStr:=Copy(XmlData,Pos('<Data Count="',xmlData)+13,100);
if Pos('"',tmpCntStr)>0 then tmpCntStr:=Copy(tmpCntStr,1,Pos('"',tmpCntStr)-1);
tmpCnt:=StrToIntDef(tmpCntStr,0);
end;
if tmpCnt < 1 then
begin
GMessagebox('검색된 내용이 없습니다.', CDMSE);
Exit;
end;
cxGridDBTableView1.BeginUpdate;
StrList := TStringList.Create;
try
SetLength(ArrSt,tmpCnt);
tmpStr:=xmlData;
tmpStr:=stringreplace(tmpStr,'"','',[rfReplaceAll]);
tmpStr:=stringreplace(tmpStr,#13,'',[rfReplaceAll]);
tmpStr:=stringreplace(tmpStr,#10,'',[rfReplaceAll]);
if Pos('<Result Value=',XmlData)>0 then
tmpStr:=Copy(XmlData,Pos('<Result Value=',XmlData),Length(XmlData)-Pos('<Result Value=',XmlData)+1);
for k:=0 to tmpCnt-1 do
begin
ArrSt[k]:=tmpStr;
if Pos('/>',tmpStr)>0 then
begin
ArrSt[k]:=Copy(tmpStr,1,Pos('/>',tmpStr)-1);
if Pos('<Result Value=',ArrSt[k]) > 0 then
ArrSt[k] := Copy(ArrSt[k],Pos('<Result Value=',ArrSt[k])+14,Length(ArrSt[k])-Pos('<Result Value=',ArrSt[k])+14+1);
if Pos('/>',ArrSt[k]) > 0 then
ArrSt[k] := Copy(ArrSt[k],1,Pos('/>',ArrSt[k])-1);
ArrSt[k]:=StringReplace(ArrSt[k],'"','',[rfReplaceAll]);
tmpStr:=Copy(tmpStr,Pos('/>',tmpStr)+2,Length(tmpStr)-Pos('/>',tmpStr)+2+1);
StrList.Clear;
GetTextSeperationEx('│', ArrSt[k], StrList);
iRow := cxGridDBTableView1.DataController.AppendRecord;
cxGridDBTableView1.DataController.Values[iRow, 0] := IntToStr(iCnt);
cxGridDBTableView1.DataController.Values[iRow, 1] := StrToCall(StrList.Strings[0]);
if (IsPassedManagementWk(StrList.Strings[5])) Or ( StrList.Strings[5] = '' ) then
begin
cxGridDBTableView1.DataController.Values[iRow, 2] := StrToCall(StrList.Strings[1]);
cxGridDBTableView1.DataController.Values[iRow, 3] := StrList.Strings[2];
cxGridDBTableView1.DataController.Values[iRow, 4] := StrToIntDef(StrList.Strings[3], 0);
if length(StrList.Strings[4]) = 8 then
cxGridDBTableView1.DataController.Values[iRow, 5] := copy(StrList.Strings[4], 1,4) + '-' + copy(StrList.Strings[4], 5,2) + '-' + copy(StrList.Strings[4], 7,2) // 최종이용일자
else cxGridDBTableView1.DataController.Values[iRow, 5] := StrList.Strings[4];
if StrList.Strings[9] <> '' then
cxGridDBTableView1.DataController.Values[iRow, 6] := StrList.Strings[9] + ' - ' + StrList.Strings[8]
else cxGridDBTableView1.DataController.Values[iRow, 6] := StrList.Strings[9];
cxGridDBTableView1.DataController.Values[iRow, 7] := StrList.Strings[6];
cxGridDBTableView1.DataController.Values[iRow, 8] := StrList.Strings[7];
cxGridDBTableView1.DataController.Values[iRow, 9] := copy(StrList.Strings[0],8,4);
cxGridDBTableView1.DataController.Values[iRow, 10] := StrList.Strings[5];
cxGridDBTableView1.DataController.Values[iRow, 11] := RightStr(StrList.Strings[1],4);
end else
begin
cxGridDBTableView1.DataController.Values[iRow, 2] := '***-****-****';
cxGridDBTableView1.DataController.Values[iRow, 3] := '***';
cxGridDBTableView1.DataController.Values[iRow, 4] := 0;
cxGridDBTableView1.DataController.Values[iRow, 5] := '****-**-**';
cxGridDBTableView1.DataController.Values[iRow, 6] := '*******';
cxGridDBTableView1.DataController.Values[iRow, 7] := '타업체에서 사용중입니다';
cxGridDBTableView1.DataController.Values[iRow, 8] := '*******';
cxGridDBTableView1.DataController.Values[iRow, 9] := '****';
cxGridDBTableView1.DataController.Values[iRow, 10] := '****';
cxGridDBTableView1.DataController.Values[iRow, 11] := '****';
end;
Inc(iCnt);
end;
end;
finally
cxGridDBTableView1.endupdate;
StrList.Free;
end;
end;
finally
slList.Free;
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
end;
procedure TFrm_CUT.proc_VirtureNum_init;
begin
cxTextEdit18.Text := '';
cxTextEdit19.Text := '';
cxTextEdit20.Text := '';
cxLabel243.Caption := '';
cxLabel245.Caption := '';
cxLabel247.Caption := '';
cxLabel250.Caption := '';
cxVirtureList.DataController.SetRecordCount(0);
pnl5.visible := False;
end;
procedure TFrm_CUT.rbAll01Click(Sender: TObject);
begin
rg_SType.Tag := TcxRadioButton(Sender).Tag;
if rg_SType.Tag = 0 then
begin
cxDate2_1S.Enabled := False;
cxDate2_1E.Enabled := False;
end else
begin
cxDate2_1S.Enabled := True;
cxDate2_1E.Enabled := True;
end;
proc_New_his(rg_SType.Tag);
cb_Sms_Gubun.ItemIndex := 1;
end;
procedure TFrm_CUT.RbButton1MouseDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
pm_Date.Popup(Mouse.CursorPos.X, Mouse.CursorPos.y);
end;
procedure TFrm_CUT.chk_Before_FinishClick(Sender: TObject);
begin
if bTag_Page2 then exit;
if chk_Before_Finish.Checked then
begin
// chk_Before_Finish.Checked := True;
cxDate2_1S.Enabled := False;
cxDate2_1E.Enabled := False;
cxDate2_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 1;
cxDate2_1E.Date := cxDate2_1S.Date + 1;
//////////////////////////체크박스 연동안되도록 //////////////////////////
bTag_Page2 := True;
chk_Before.Checked := False;
chk_Before_New.Checked := False;
bTag_Page2 := False;
//////////////////////////체크박스 연동안되도록 //////////////////////////
GroupBox4.Enabled := False;
cb_st_city.Enabled := False;
cb_st_ward.Enabled := False;
cb_S_Cnt1.Text := '';
cb_S_Cnt2.Text := '';
cb_s_CCnt1.Text := '';
cb_s_CCnt2.Text := '';
cb_S_Cnt1.Enabled := False;
cb_S_Cnt2.Enabled := False;
cb_S_CCnt1.Enabled := False;
cb_S_CCnt2.Enabled := False;
cb_S_Grad.Enabled := False;
rg_SType.Enabled := False;
rrb_st_all.Checked := True;
rrb_st_comp.Checked := False;
rrb_st_cancel.Checked := False;
rrb_st_req.Checked := False;
end else
begin
// chk_Before_Finish.Checked := False;
cxDate2_1S.Enabled := True;
cxDate2_1E.Enabled := True;
cxDate2_1S.Date := StrToDate(Date8to10(copy(StartDateTime('yyyymmddhhmmss'), 1, 8))) - 1;
cxDate2_1E.Date := cxDate2_1S.Date + 1;
//////////////////////////체크박스 연동안되도록 //////////////////////////
bTag_Page2 := True;
chk_Before.Checked := False;
chk_Before_New.Checked := False;
bTag_Page2 := False;
//////////////////////////체크박스 연동안되도록 //////////////////////////
GroupBox4.Enabled := True;
cb_st_city.Enabled := True;
cb_st_ward.Enabled := True;
cb_S_Cnt1.Text := '';
cb_S_Cnt2.Text := '';
cb_s_CCnt1.Text := '';
cb_s_CCnt2.Text := '';
cb_S_Cnt1.Enabled := True;
cb_S_Cnt2.Enabled := True;
cb_S_CCnt1.Enabled := True;
cb_S_CCnt2.Enabled := True;
cb_S_Grad.Enabled := True;
rg_SType.Enabled := True;
rrb_st_all.Checked := True;
rrb_st_comp.Checked := False;
rrb_st_cancel.Checked := False;
rrb_st_req.Checked := False;
cbGubun2_1.ItemIndex := 0;
if rbUseList01.Checked then
begin
cb_st_city.Enabled := True;
cb_st_ward.Enabled := True;
cb_S_Cnt1.Enabled := False;
cb_S_Cnt2.Enabled := False;
cb_S_CCnt1.Enabled := False;
cb_S_CCnt2.Enabled := False;
cb_S_Grad.Enabled := False;
GroupBox4.Enabled := True;
rrb_st_all.Checked := True;
end else
begin
cb_st_city.Enabled := False;
cb_st_ward.Enabled := False;
cbKeynumber02.ItemIndex := 0;
cbGubun2_1.ItemIndex := 0;
cb_Sms_Gubun.ItemIndex := 0;
cb_S_Grad.ItemIndex := 0;
cb_Sms_Gubun.Enabled := True;
cb_S_Cnt1.Enabled := True;
cb_S_Cnt2.Enabled := True;
cb_S_CCnt1.Enabled := True;
cb_S_CCnt2.Enabled := True;
cb_S_Grad.Enabled := True;
GroupBox4.Enabled := False;
rrb_st_all.Checked := True;
rrb_st_comp.Checked := False;
rrb_st_cancel.Checked := False;
rrb_st_req.Checked := False;
end;
end;
end;
procedure TFrm_CUT.rbCust03Type01Click(Sender: TObject);
begin
if rbCust03Type01.Checked then
begin
cxDate3_1S.Enabled := False;
cxDate3_1E.Enabled := False;
btn_Date3_1.Enabled := False;
end;
end;
procedure TFrm_CUT.rbCust03Type02Click(Sender: TObject);
begin
if rbCust03Type02.Checked then
begin
cxDate3_1S.Enabled := True;
cxDate3_1E.Enabled := True;
btn_Date3_1.Enabled := True;
end;
end;
procedure TFrm_CUT.rbCust03Type03Click(Sender: TObject);
begin
if rbCust03Type03.Checked then
begin
rbCust03Type01.Checked := True;
rbCust03Type01Click(rbCust03Type01);
end;
edMlgScore01.Enabled := True;
edMlgScore02.Enabled := True;
edMlgCount01.Enabled := True;
edMlgCount02.Enabled := True;
cbCustLastNumber.Enabled := False;
end;
procedure TFrm_CUT.rbCust03Type04Click(Sender: TObject);
begin
edMlgScore01.Enabled := False;
edMlgScore02.Enabled := False;
edMlgCount01.Enabled := False;
edMlgCount02.Enabled := False;
cbCustLastNumber.Enabled := True;
end;
procedure TFrm_CUT.rbCust06Type01Click(Sender: TObject);
begin
if rbCust06Type01.Checked then
begin
cxDate6_1.Enabled := True;
btn_6_1.Enabled := True;
btn_6_2.Enabled := True;
btn_6_3.Enabled := True;
btn_6_4.Enabled := True;
btn_6_5.Enabled := True;
chkCust06Type01.Enabled := True;
cxDate14.Enabled := False;
cxDate15.Enabled := False;
end else
begin
cxDate6_1.Enabled := False;
btn_6_1.Enabled := False;
btn_6_2.Enabled := False;
btn_6_3.Enabled := False;
btn_6_4.Enabled := False;
btn_6_5.Enabled := False;
chkCust06Type01.Enabled := False;
cxDate14.Enabled := True;
cxDate15.Enabled := True;
end;
end;
procedure TFrm_CUT.rbCust06Type02Click(Sender: TObject);
begin
if rbCust06Type01.Checked then
begin
cxDate6_1.Enabled := True;
btn_6_1.Enabled := True;
btn_6_2.Enabled := True;
btn_6_3.Enabled := True;
btn_6_4.Enabled := True;
btn_6_5.Enabled := True;
chkCust06Type01.Enabled := True;
cxDate14.Enabled := False;
cxDate15.Enabled := False;
end else
begin
cxDate6_1.Enabled := False;
btn_6_1.Enabled := False;
btn_6_2.Enabled := False;
btn_6_3.Enabled := False;
btn_6_4.Enabled := False;
btn_6_5.Enabled := False;
chkCust06Type01.Enabled := False;
cxDate14.Enabled := True;
cxDate15.Enabled := True;
end;
end;
procedure TFrm_CUT.rbFirstUseDate01Click(Sender: TObject);
begin
de_4stDate.Enabled := False;
de_4edDate.Enabled := False;
btn_Date1_5.Enabled := False;
de_5stDate.Enabled := False;
de_5edDate.Enabled := False;
btn_Date1_6.Enabled := False;
edUseCnt01.Enabled := False;
edUseCnt02.Enabled := False;
case TcxRadioButton(Sender).Tag of
0:
begin
de_4stDate.Enabled := True;
de_4edDate.Enabled := True;
btn_Date1_5.Enabled := True;
end;
1:
begin
de_5stDate.Enabled := True;
de_5edDate.Enabled := True;
btn_Date1_6.Enabled := True;
end;
2:
begin
edUseCnt01.Enabled := True;
edUseCnt02.Enabled := True;
end;
end;
end;
procedure TFrm_CUT.rb_StraightClick(Sender: TObject);
begin
case TcxRadioButton(Sender).Tag of
0 : cxLabel190.Caption := '원';
1 : cxLabel190.Caption := '%';
end;
end;
procedure TFrm_CUT.RequestData(AData: string);
var
ReceiveStr: string;
StrList: TStringList;
ErrCode: integer;
begin
StrList := TStringList.Create;
Screen.Cursor := crHandPoint;
try
if dm.SendSock(AData, StrList, ErrCode, False) then
begin
ReceiveStr := StrList[0];
if trim(ReceiveStr) <> '' then
begin
Application.ProcessMessages;
proc_recieve(StrList);
end;
end;
finally
Screen.Cursor := crDefault;
StrList.Free;
Frm_Flash.Hide;
end;
end;
procedure TFrm_CUT.RequestDataCustLevel;
var
Param: string;
begin
if GT_SEL_BRNO.GUBUN <> '1' then
begin
GMessagebox(PChar('고객등급관리는 [좌측 상단 지사선택 메뉴에서] 지사를 선택하셔야 합니다.'), CDMSE);
if cxPageControl1.ActivePageIndex = 6 then
begin
cxViewCustGroup.DataController.SetRecordCount(0);
cxViewCustLevel.DataController.SetRecordCount(0);
cxViewGroupLevel.DataController.SetRecordCount(0);
end;
Exit;
end;
Param := GT_SEL_BRNO.BrNo;
RequestData(GetSel05('GetCustGroup', 'cust_level.lv_select_ext', '100', GT_SEL_BRNO.BrNo+'│1'));
RequestData(GetSel05('GetGroupLevel', 'cust_level.lv_select_ext', '100', GT_SEL_BRNO.BrNo+'│2'));
end;
procedure TFrm_CUT.RequestDataLevelFromGroupSeq(AGroupSeq: string);
var
Param: string;
begin
Param := AGroupSeq;
RequestData(GetSel05('GetLevelFromGroupSeq', 'cust_level.lv_select', '100', Param));
end;
procedure TFrm_CUT.ResponseBATCH_CUST_MLG(AXmlStr: WideString);
var
xdom: msDomDocument;
lst_Result: IXMLDomNodeList;
I, j, jj: Integer;
ls_Rcrd: TStringList;
sErrorList : TStringList;
iCustTel, iNo, iCutNM, iSeq : Integer;
begin
xdom := ComsDomDocument.Create;
try
if not xdom.loadXML(AXmlStr) then
Exit;
iSeq := CustView1.GetColumnByFieldName('SEQ').Index;
iNo := CustView1.GetColumnByFieldName('NO').Index;
iCustTel := CustView1.GetColumnByFieldName('고객번호').Index;
iCutNM := CustView1.GetColumnByFieldName('고객명').Index;
sErrorList := TStringList.Create;
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
for I := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
sErrorList.Delimiter := ',';
sErrorList.DelimitedText := ls_Rcrd[0];
mmoMilelistError.Lines.Add('[오류고객정보]');
for j := 0 to sErrorList.Count -1 do
begin
for jj := 0 to CustView1.DataController.RecordCount - 1 do
begin
if (CustView1.ViewData.Records[jj].Selected) then
begin
if CustView1.ViewData.Records[jj].Values[iSeq] = sErrorList[j] then
begin
//오류 고객 정보 메모에 추가
mmoMilelistError.Lines.Add('NO : ' + inttostr(CustView1.ViewData.Records[jj].Values[iNO]) + ', ' +
'고객명 : ' + CustView1.ViewData.Records[jj].Values[iCutNM] + ', ' +
'고객번호 : ' + CustView1.ViewData.Records[jj].Values[iCustTel] + ', ');
end;
end;
end;
end;
end;
finally
sErrorList.Free;
xdom := Nil;
end;
end;
procedure TFrm_CUT.ResponseCustGroup(AXmlStr: WideString);
var
xdom: msDomDocument;
lst_Result: IXMLDomNodeList;
I, Row, Idx: Integer;
ls_Rcrd: TStringList;
sOneYear : String;
begin
xdom := ComsDomDocument.Create;
try
if not xdom.loadXML(AXmlStr) then
Exit;
Idx := cxViewCustGroup.DataController.FocusedRecordIndex;
cxViewCustGroup.DataController.SetRecordCount(0);
if (0 < GetXmlRecordCount(AXmlStr)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for I := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
if ls_Rcrd[11] = 'y' then sOneYear := ' [최근 1년 유지]'
else sOneYear := '';
Row := cxViewCustGroup.DataController.AppendRecord;
cxViewCustGroup.DataController.Values[Row, cxColCGGroupName.Index] := '[' + Lpad(ls_Rcrd[9], '0', 4) + ']' + ls_Rcrd[0] + sOneYear; // 그룹명
cxViewCustGroup.DataController.Values[Row, cxColCGSortNo.Index] := ls_Rcrd[1]; // 정렬
cxViewCustGroup.DataController.Values[Row, cxColCGLevelName.Index] := ls_Rcrd[2]; // 등급명
cxViewCustGroup.DataController.Values[Row, cxColCGMileage.Index] := IfThen(ls_Rcrd[3] = '0', '', IfThen(StrToIntDef(ls_Rcrd[3], 0) > 100, StrToMoney(ls_Rcrd[3]) + ' 원', ls_Rcrd[3] + '%')); // 마일리지
cxViewCustGroup.DataController.Values[Row, cxColCGColor.Index] := ls_Rcrd[4]; // 색상
if (UpperCase(ls_Rcrd[7]) = 'Y') Or (UpperCase(ls_Rcrd[11]) = 'Y') then
cxViewCustGroup.DataController.Values[Row, cxColCGLevelUpDesc.Index] := Format('%s건이상/%s%%이하', [ls_Rcrd[5], ls_Rcrd[6]])
else
cxViewCustGroup.DataController.Values[Row, cxColCGLevelUpDesc.Index] := '';
cxViewCustGroup.DataController.Values[Row, cxColCGDefaultYN.Index] := ls_Rcrd[8];
cxViewCustGroup.DataController.Values[Row, cxColCGGroupSeq.Index] := ls_Rcrd[9];
cxViewCustGroup.DataController.Values[Row, cxColCGLevelSeq.Index] := ls_Rcrd[10];
end;
finally
ls_Rcrd.Free;
end;
cxGridCustGroup.FocusedView.DataController.Groups.FullExpand;
if cxViewCustGroup.DataController.RecordCount > Idx then
cxViewCustGroup.DataController.FocusedRecordIndex := Idx;
end;
finally
xdom := Nil;
end;
end;
procedure TFrm_CUT.ResponseCustLevel(AXmlStr: WideString);
var
xdom: msDomDocument;
lst_Result: IXMLDomNodeList;
I, Row: Integer;
ls_Rcrd: TStringList;
begin
xdom := ComsDomDocument.Create;
try
if not xdom.loadXML(AXmlStr) then
Exit;
cxViewCustLevel.DataController.SetRecordCount(0);
if (0 < GetXmlRecordCount(AXmlStr)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for I := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
Row := cxViewCustLevel.DataController.AppendRecord;
cxViewCustLevel.DataController.Values[Row, 0] := ls_Rcrd[0];
cxViewCustLevel.DataController.Values[Row, 1] := ls_Rcrd[1];
cxViewCustLevel.DataController.Values[Row, 2] := IfThen(UpperCase(ls_Rcrd[2]) = 'Y', '사용', '미사용');
cxViewCustLevel.DataController.Values[Row, 3] := ls_Rcrd[3];
end;
finally
ls_Rcrd.Free;
end;
end;
finally
xdom := Nil;
end;
end;
procedure TFrm_CUT.ResponseLevelFromGroupSeq(AXmlStr: WideString);
var
xdom: msDomDocument;
lst_Result: IXMLDomNodeList;
I, Row, Idx: Integer;
ls_Rcrd: TStringList;
begin
xdom := ComsDomDocument.Create;
try
if not xdom.loadXML(AXmlStr) then
Exit;
Idx := cxViewGroupLevel.DataController.FocusedRecordIndex;
cxViewGroupLevel.DataController.SetRecordCount(0);
if (0 < GetXmlRecordCount(AXmlStr)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for I := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
Row := cxViewGroupLevel.DataController.AppendRecord;
cxViewGroupLevel.DataController.Values[Row, cxColGLSortNo.Index] := ls_Rcrd[1]; // 정렬
cxViewGroupLevel.DataController.Values[Row, cxColGLLevelName.Index] := ls_Rcrd[2]; // 등급명
cxViewGroupLevel.DataController.Values[Row, cxColGLMileage.Index] := IfThen(ls_Rcrd[3] = '0', '', IfThen(StrToIntDef(ls_Rcrd[3], 0) > 100, StrToMoney(ls_Rcrd[3]) + ' 원', ls_Rcrd[3] + '%')); // 마일리지
cxViewGroupLevel.DataController.Values[Row, cxColGLColor.Index] := ls_Rcrd[4]; // 색상
if (UpperCase(ls_Rcrd[7]) = 'Y') then
cxViewGroupLevel.DataController.Values[Row, cxColGLLevelUpDesc.Index] := Format('%s건이상/%s%%이하', [ls_Rcrd[5], ls_Rcrd[6]])
else
cxViewGroupLevel.DataController.Values[Row, cxColGLLevelUpDesc.Index] := '';
cxViewGroupLevel.DataController.Values[Row, cxColGLDefaultYN.Index] := ls_Rcrd[8];
end;
finally
ls_Rcrd.Free;
end;
cxGridGroupLevel.FocusedView.DataController.Groups.FullExpand;
if cxViewGroupLevel.DataController.RecordCount > Idx then
cxViewGroupLevel.DataController.FocusedRecordIndex := Idx;
end;
finally
xdom := Nil;
end;
end;
procedure TFrm_CUT.ShowCustLevelWindow(AGroupName, AGroupSeq: string;
AOneYear: Boolean; ALevelSeq: string);
begin
if ( not Assigned(Frm_CUT02) ) Or ( Frm_CUT02 = Nil ) then Frm_CUT02 := TFrm_CUT02.Create(Self);
Frm_CUT02.SetData(GT_SEL_BRNO.BrNo, AGroupName, AGroupSeq, AOneYear, ALevelSeq);
Frm_CUT02.OnRefreshEvent := OnRefreshCustLevel;
Frm_CUT02.Left := (Screen.Width - Frm_CUT02.Width ) div 2;
Frm_CUT02.Top := (Screen.Height - Frm_CUT02.Height) div 2;
if Frm_CUT02.top <= 10 then Frm_CUT02.top := 10;
Frm_CUT02.Show;
end;
procedure TFrm_CUT._retenTel01KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = vk_Return then
btn_1_4Click(nil);
end;
procedure TFrm_CUT.btnAll1Click(Sender: TObject);
var iCol : integer;
begin
case cxPageControl1.ActivePageIndex of
0 : begin
Frm_Main.sgExcel := '고객_고객관리.xls';
Frm_Main.sgRpExcel := Format('고객>고객관리]%s건/%s', [GetMoneyStr(CustView1.DataController.RecordCount), FExcelDownMng]);
Frm_Main.cxGridExcel := cxGrid1;
Frm_Main.cxGridDBViewExcel := CustView1;
if RdExcel1.Checked then Frm_Main.bgExcelOPT := False else
if RdExcel2.Checked then Frm_Main.bgExcelOPT := True;
if GS_XLS_DTypeUse then
begin
iCol := CustView1.GetColumnByFieldName('No').Index;
CustView1.Columns[iCol].PropertiesClassName := 'TcxCalcEditProperties';
CustView1.Columns[iCol].Properties := Frm_Main.gCalHCProperties;
iCol := CustView1.GetColumnByFieldName('이용횟수').Index;
CustView1.Columns[iCol].PropertiesClassName := 'TcxCalcEditProperties';
CustView1.Columns[iCol].Properties := Frm_Main.gCalHCProperties;
iCol := CustView1.GetColumnByFieldName('완료횟수').Index;
CustView1.Columns[iCol].PropertiesClassName := 'TcxCalcEditProperties';
CustView1.Columns[iCol].Properties := Frm_Main.gCalHCProperties;
end else
begin
iCol := CustView1.GetColumnByFieldName('No').Index;
CustView1.Columns[iCol].PropertiesClassName := 'TcxLabelProperties';
CustView1.Columns[iCol].Properties := Frm_Main.gLblProperties;
iCol := CustView1.GetColumnByFieldName('이용횟수').Index;
CustView1.Columns[iCol].PropertiesClassName := 'TcxLabelProperties';
CustView1.Columns[iCol].Properties := Frm_Main.gLblProperties;
iCol := CustView1.GetColumnByFieldName('완료횟수').Index;
CustView1.Columns[iCol].PropertiesClassName := 'TcxLabelProperties';
CustView1.Columns[iCol].Properties := Frm_Main.gLblProperties;
end;
end;
1 :
begin
Frm_Main.sgExcel := '고객_일반검색.xls';
Frm_Main.sgRpExcel := Format('고객>일반검색]%s건/%s', [GetMoneyStr(CustView2.DataController.RecordCount), FExcelDownNormal]);
Frm_Main.cxGridExcel := cxGrid2;
Frm_Main.cxGridDBViewExcel := CustView2;
if RdExcel1.Checked then Frm_Main.bgExcelOPT := False else
if RdExcel2.Checked then Frm_Main.bgExcelOPT := True;
if GS_XLS_DTypeUse then
begin
CustView2.Columns[0].PropertiesClassName := 'TcxCalcEditProperties';
CustView2.Columns[0].Properties := Frm_Main.gCalHCProperties;
end else
begin
CustView2.Columns[0].PropertiesClassName := 'TcxLabelProperties';
CustView2.Columns[0].Properties := Frm_Main.gLblProperties;
end;
end;
2 :
begin
Frm_Main.sgExcel := '고객_고급검색.xls';
Frm_Main.sgRpExcel := Format('고객>고급검색]%s건/%s', [GetMoneyStr(CustView3.DataController.RecordCount), FExcelDownHigh]);
Frm_Main.cxGridExcel := cxGrid3;
Frm_Main.cxGridDBViewExcel := CustView3;
if RdExcel1.Checked then Frm_Main.bgExcelOPT := False else
if RdExcel2.Checked then Frm_Main.bgExcelOPT := True;
if GS_XLS_DTypeUse then
begin
CustView3.Columns[0].PropertiesClassName := 'TcxCalcEditProperties';
CustView3.Columns[0].Properties := Frm_Main.gCalHCProperties;
CustView3.Columns[12].PropertiesClassName := 'TcxCalcEditProperties';
CustView3.Columns[12].Properties := Frm_Main.gCalHCProperties;
end else
begin
CustView3.Columns[0].PropertiesClassName := 'TcxLabelProperties';
CustView3.Columns[0].Properties := Frm_Main.gLblProperties;
CustView3.Columns[12].PropertiesClassName := 'TcxLabelProperties';
CustView3.Columns[12].Properties := Frm_Main.gLblProperties;
end;
end;
3 :
begin
Frm_Main.sgExcel := '고객_상세검색.xls';
Frm_Main.sgRpExcel := Format('고객>상세검색]%s건/%s', [GetMoneyStr(CustView4.DataController.RecordCount), FExcelDownDetail]);
Frm_Main.cxGridExcel := cxGrid4;
Frm_Main.cxGridDBViewExcel := CustView4;
if RdExcel1.Checked then Frm_Main.bgExcelOPT := False else
if RdExcel2.Checked then Frm_Main.bgExcelOPT := True;
if GS_XLS_DTypeUse then
begin
CustView4.Columns[0].PropertiesClassName := 'TcxCalcEditProperties';
CustView4.Columns[0].Properties := Frm_Main.gCalHCProperties;
end else
begin
CustView4.Columns[0].PropertiesClassName := 'TcxLabelProperties';
CustView4.Columns[0].Properties := Frm_Main.gLblProperties;
end;
end;
4 :
begin
Frm_Main.sgExcel := '고객_안심번호.xls';
Frm_Main.sgRpExcel := Format('고객>안심번호]%s건/%s', [GetMoneyStr(cxGridDBTableView1.DataController.RecordCount), FExcelDownSleep]);
Frm_Main.cxGridExcel := cxGrid14;
Frm_Main.cxGridDBViewExcel := cxGridDBTableView1;
if RdExcel1.Checked then Frm_Main.bgExcelOPT := False else
if RdExcel2.Checked then Frm_Main.bgExcelOPT := True;
if GS_XLS_DTypeUse then
begin
cxGridDBTableView1.Columns[0].PropertiesClassName := 'TcxCalcEditProperties';
cxGridDBTableView1.Columns[0].Properties := Frm_Main.gCalHCProperties;
cxGridDBTableView1.Columns[4].PropertiesClassName := 'TcxCalcEditProperties';
cxGridDBTableView1.Columns[4].Properties := Frm_Main.gCalHCProperties;
end else
begin
cxGridDBTableView1.Columns[0].PropertiesClassName := 'TcxLabelProperties';
cxGridDBTableView1.Columns[0].Properties := Frm_Main.gLblProperties;
cxGridDBTableView1.Columns[4].PropertiesClassName := 'TcxLabelProperties';
cxGridDBTableView1.Columns[4].Properties := Frm_Main.gLblProperties;
end;
end;
5 : begin
Frm_Main.sgExcel := '고객_휴면고객.xls';
Frm_Main.sgRpExcel := Format('고객>휴면고객]%s건/%s', [GetMoneyStr(CustView6.DataController.RecordCount), FExcelDownSleep]);
Frm_Main.cxGridExcel := cxGrid5;
Frm_Main.cxGridDBViewExcel := CustView6;
if RdExcel1.Checked then Frm_Main.bgExcelOPT := False else
if RdExcel2.Checked then Frm_Main.bgExcelOPT := True;
end;
8 : begin
Frm_Main.sgExcel := '고객_마일리지현황고객별.xls';
Frm_Main.sgRpExcel := Format('고객>마일리지현황]%s건/%s', [GetMoneyStr(CustView9.DataController.RecordCount), FExcelDownMile]);
Frm_Main.cxGridExcel := cxGrid6;
Frm_Main.cxGridDBViewExcel := CustView9;
if RdExcel1.Checked then Frm_Main.bgExcelOPT := False else
if RdExcel2.Checked then Frm_Main.bgExcelOPT := True;
if GS_XLS_DTypeUse then
begin
CustView9.Columns[0].PropertiesClassName := 'TcxCalcEditProperties';
CustView9.Columns[0].Properties := Frm_Main.gCalHCProperties;
CustView9.Columns[10].PropertiesClassName := 'TcxCalcEditProperties';
CustView9.Columns[10].Properties := Frm_Main.gCalHCProperties;
CustView9.Columns[19].PropertiesClassName := 'TcxCalcEditProperties';
CustView9.Columns[19].Properties := Frm_Main.gCalHCProperties;
CustView9.Columns[20].PropertiesClassName := 'TcxCalcEditProperties';
CustView9.Columns[20].Properties := Frm_Main.gCalHCProperties;
end else
begin
CustView9.Columns[0].PropertiesClassName := 'TcxLabelProperties';
CustView9.Columns[0].Properties := Frm_Main.gLblProperties;
CustView9.Columns[10].PropertiesClassName := 'TcxLabelProperties';
CustView9.Columns[10].Properties := Frm_Main.gLblProperties;
CustView9.Columns[19].PropertiesClassName := 'TcxLabelProperties';
CustView9.Columns[19].Properties := Frm_Main.gLblProperties;
CustView9.Columns[20].PropertiesClassName := 'TcxLabelProperties';
CustView9.Columns[20].Properties := Frm_Main.gLblProperties;
end;
end;
9 : begin
Frm_Main.sgExcel := '고객_마일리지상세.xls';
Frm_Main.sgRpExcel := Format('고객>마일리지상세]%s건/%s', [GetMoneyStr(CustView10.DataController.RecordCount), FExcelDownMileDetail]);
Frm_Main.cxGridExcel := cxGrid8;
Frm_Main.cxGridDBViewExcel := CustView10;
if RdExcel1.Checked then Frm_Main.bgExcelOPT := False else
if RdExcel2.Checked then Frm_Main.bgExcelOPT := True;
end;
10 :begin
Frm_Main.sgExcel := '고객_OK캐쉬백적립현황.xls';
Frm_Main.sgRpExcel := Format('고객_OK캐쉬백적립현황]%s건/%s', [GetMoneyStr(cxViewOKC.DataController.RecordCount), FExcelDownMileDetail]);
Frm_Main.cxGridExcel := cxGridOKC;
Frm_Main.cxGridDBViewExcel := cxViewOKC;
if RdExcel1.Checked then Frm_Main.bgExcelOPT := False else
if RdExcel2.Checked then Frm_Main.bgExcelOPT := True;
end;
11 :begin
if grpExcel_OPT.Tag = 0 then
begin
Frm_Main.sgExcel := '고객_추천인관리(앱).xls';
Frm_Main.sgRpExcel := Format('고객>추천인관리(앱)]%s건/%s', [GetMoneyStr(cxViewRCMD.DataController.RecordCount), FExcelDownRCMD]);
Frm_Main.cxGridExcel := cxRCMD;
Frm_Main.cxGridDBViewExcel := cxViewRCMD;
end else
if grpExcel_OPT.Tag = 1 then
begin
Frm_Main.sgExcel := '고객_추천인관리(앱)상세.xls';
Frm_Main.sgRpExcel := Format('고객>추천인관리(앱)상세]%s건/%s', [GetMoneyStr(cxViewRCMD_D.DataController.RecordCount), FExcelDownRCMDD]);
Frm_Main.cxGridExcel := cxRCMD_D;
Frm_Main.cxGridDBViewExcel := cxViewRCMD_D;
end;
if RdExcel1.Checked then Frm_Main.bgExcelOPT := False else
if RdExcel2.Checked then Frm_Main.bgExcelOPT := True;
end;
end;
Frm_Main.proc_excel(0);
grpExcel_OPT.Visible := False;
end;
procedure TFrm_CUT.pSetMultiMileInit;
Var i : Integer;
sNm : String;
begin
try
for i := 1 to 6 do
begin
case i of
1 : sNm := '0';
2 : sNm := '1';
3 : sNm := '3';
4 : sNm := '0A';
5 : sNm := '1A';
6 : sNm := '3A';
end;
TcxComBoBox(FindComponent('cbCashType'+sNm)).ItemIndex := 0;
TcxComBoBox(FindComponent('cbPostType'+sNm)).ItemIndex := 0;
TcxComBoBox(FindComponent('cbCardType'+sNm)).ItemIndex := 0;
TcxComBoBox(FindComponent('cbMileType'+sNm)).ItemIndex := 0;
TcxCurrencyEdit(FindComponent('edtCashValue'+sNm)).EditValue := 0;
TcxCurrencyEdit(FindComponent('edtPostValue'+sNm)).EditValue := 0;
TcxCurrencyEdit(FindComponent('edtCardValue'+sNm)).EditValue := 0;
TcxCurrencyEdit(FindComponent('edtMileValue'+sNm)).EditValue := 0;
TcxCheckBox(FindComponent('chkReceipNoMile'+sNm)).Checked := False;
TcxCurrencyEdit(FindComponent('edtFirstAdd'+sNm)).EditValue := 0;
TcxCurrencyEdit(FindComponent('edtOverAdd' +sNm)).EditValue := 0;
end;
except
end;
end;
procedure TFrm_CUT.pSetMultiMileSave( pData : TMileData);
var
sTemp, XmlData, ErrMsg: string;
i, ErrCode: integer;
asParam: array[1..10] of string;
begin
asParam[1] := cxBrNo8.Text; //지사코드
asParam[2] := pData.mType; // 적립타입(T.전화접수, A.앱접수)
asParam[3] := pData.mGubun; // 고객구분(0:일반 1:업소 3:법인)
asParam[4] := pData.mCash; // 현금설정
asParam[5] := pData.mPost; // 후불(법인)설정
asParam[6] := pData.mCard; // 카드설정
asParam[7] := pData.mMile; // 마일설정
asParam[8] := pData.mReceipNo; // 현금영수증설정
asParam[9] := pData.mFirstAdd; // 첫회추가적립금액
asParam[10] := pData.mOverAdd; // 최소적립요금
sTemp := '';
for i := 1 to 10 do
begin
if i = 1 then sTemp := asParam[1]
else
begin
sTemp := sTemp + '│' + asParam[i];
end;
end;
if not RequestBase(GetCallable06('SET_MILEAGE_CFG', 'MNG_BR_MLG_CFG.SET_MILEAGE_CFG', sTemp), XmlData, ErrCode, ErrMsg) then
begin
GMessageBox(Format('[%d] %s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
end;
end.
|
Unit MultiSel;
Interface
uses
Dos,App,Objects,Views,Dialogs,Drivers;
type
PSelStr = ^TSelStr;
TSelStr = object (TObject)
Selected: Boolean;
Name: PString;
constructor Init (AName: String);
function GetSel: Boolean;
procedure SetSel (AState: Boolean);
destructor Done; virtual;
end;
PSelStrCollection = ^TSelStrCollection;
TSelStrCollection = object (TSortedCollection)
Sel: PSelStr;
constructor Init(ALimit, ADelta: Integer);
function Compare (Key1,Key2: Pointer): Integer; virtual;
end;
PMultiSelListBox = ^TMultiSelListBox;
TMultiSelListBox = object (TListBox)
C: PSelStrCollection;
constructor Init(var Bounds: TRect; AScrollBar: PScrollBar);
function GetText (Item: Integer; MaxLen: Integer): String; virtual;
procedure SelectItem (Item: Integer); virtual;
function IsSelected(Item: Integer): Boolean; virtual;
procedure HandleEvent(var Event: TEvent); virtual;
end;
Implementation
constructor TSelStr.Init;
begin
Inherited Init;
Name := NewStr (AName);
Selected := False;
end;
function TSelStr.GetSel: Boolean;
begin
GetSel := Selected;
end;
procedure TSelStr.SetSel (AState: Boolean);
begin
Selected := AState;
end;
destructor TSelStr.Done;
begin
DisposeStr (Name);
Inherited Done;
end;
constructor TSelStrCollection.Init;
begin
Inherited Init(ALimit, ADelta);
Sel:=nil;
end;
function TSelStrCollection.Compare;
begin
if PSelStr (Key1)^.Name^ < PSelStr (Key2)^.Name^ then Compare := -1
else if PSelStr (Key1)^.Name^ > PSelStr (Key2)^.Name^ then Compare := 1
else Compare := 0;
end;
constructor TMultiSelListBox.Init;
begin
Inherited Init(Bounds, 2, AScrollBar);
end;
function TMultiSelListBox.GetText;
begin
GetText := PSelStr(List^.At (Item))^.Name^
end;
procedure TMultiSelListBox.SelectItem;
begin
with C^ do
begin
Sel:=PSelStr(List^.At (Item));
Sel^.SetSel (not Sel^.GetSel);
end;
DrawView;
end;
function TMultiSelListBox.IsSelected;
begin
IsSelected:=PSelStr(List^.At (Item))^.Selected;
end;
procedure TMultiSelListBox.HandleEvent;
begin
case Event.What of
evMouseDown:
begin
{ if Event.Double then
begin
Message(Owner,evCommand,cmViewInfo,list^.at(focused));
end;}
if Event.Buttons=mbRightButton then
begin
inherited HandleEvent(Event);
SelectItem(Focused);
end;
inherited HandleEvent(Event);
ClearEvent(Event);
end;
evKeyDown:
if Event.CharCode=' ' then
begin
SelectItem(Focused);
Event.KeyCode:=kbDown;
Draw;
end;
end;
inherited HandleEvent(Event);
end;
end. |
unit Thread.FinalizaOcorrenciasJornal;
interface
uses
System.Classes, System.Generics.Collections, System.SysUtils, Model.OcorrenciasJornal, DAO.OcorrenciasJornal, Vcl.Forms,
System.UITypes;
type
Thread_FinalizaOcorrenciasJornal = class(TThread)
private
{ Private declarations }
FdPos: Double;
FTexto: String;
ocorrencia : TOcorrenciasJornal;
ocorrencias : TObjectList<TOcorrenciasJornal>;
ocorrenciaDAO : TOcorrenciasJornalDAO;
protected
procedure Execute; override;
procedure IniciaProcesso;
procedure AtualizaProcesso;
procedure TerminaProcesso;
procedure SetupClass;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure Thread_FinalizaOcorrenciasJornal.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
uses View.OcorrenciasJornal, View.ResultatoProcesso;
{ Thread_FinalizaOcorrenciasJornal }
procedure Thread_FinalizaOcorrenciasJornal.IniciaProcesso;
begin
view_OcorrenciasJornal.pbOcorrencias.Visible := True;
view_OcorrenciasJornal.ds.Enabled := False;
view_OcorrenciasJornal.tbPlanilha.IsLoading := True;
view_OcorrenciasJornal.pbOcorrencias.Position := 0;
view_OcorrenciasJornal.pbOcorrencias.Refresh;
end;
procedure Thread_FinalizaOcorrenciasJornal.Execute;
var
ocorrenciaTMP: TOcorrenciasJornal;
iTotal : Integer;
iPos : Integer;
sMensagem: String;
begin
{ Place thread code here }
try
Synchronize(IniciaProcesso);
if not Assigned(view_ResultadoProcesso) then
begin
view_ResultadoProcesso := Tview_ResultadoProcesso.Create(Application);
end;
view_ResultadoProcesso.Show;
Screen.Cursor := crHourGlass;
ocorrenciaDAO := TOcorrenciasJornalDAO.Create();
iTotal := view_OcorrenciasJornal.tbPlanilha.RecordCount;
iPos := 0;
FdPos := 0;
if not view_OcorrenciasJornal.tbPlanilha.IsEmpty then view_OcorrenciasJornal.tbPlanilha.First;
while not view_OcorrenciasJornal.tbPlanilha.Eof do
begin
sMensagem := '';
if view_OcorrenciasJornal.tbPlanilhaDOM_FINALIZAR.Value then
begin
if view_OcorrenciasJornal.tbPlanilhaDOM_PROCESSADO.AsString = 'S' then
begin
SetupClass;
ocorrencia.Status := 3;
if ocorrenciaDAO.Exist(ocorrencia.CodigoAssinstura, ocorrencia.Produto, ocorrencia.Roteiro,
ocorrencia.CodigoOcorrencia, ocorrencia.Entregador, ocorrencia.DataOcorrencia) then
begin
if not ocorrenciaDAO.Update(ocorrencia) then
begin
sMensagem := 'Erro ao alterar a ocorrência! Nº ' + view_OcorrenciasJornal.tbPlanilhaNUM_OCORRENCIA.AsString;
end
else
begin
view_OcorrenciasJornal.tbPlanilha.Edit;
view_OcorrenciasJornal.tbPlanilhaDOM_GRAVAR.AsString := 'N';
view_OcorrenciasJornal.tbPlanilhaDOM_FINALIZAR.AsString := 'N';
view_OcorrenciasJornal.tbPlanilha.Post;
end;
end
else
begin
if not ocorrenciaDAO.Insert(ocorrencia) then
begin
sMensagem := 'Erro ao incluir a ocorrência! Assinatura Nº ' + view_OcorrenciasJornal.tbPlanilhaCOD_ASSINATURA.AsString
+ ' Data: ' + view_OcorrenciasJornal.tbPlanilhaDAT_OCORRENCIA.AsString;
end
else
begin
view_OcorrenciasJornal.tbPlanilha.Edit;
view_OcorrenciasJornal.tbPlanilhaNUM_OCORRENCIA.AsInteger := ocorrencia.Numero;
view_OcorrenciasJornal.tbPlanilhaDOM_GRAVAR.AsString := 'N';
view_OcorrenciasJornal.tbPlanilhaDOM_FINALIZAR.AsString := 'N';
view_OcorrenciasJornal.tbPlanilha.Post;
end;
end;
end
else
begin
sMensagem := 'Ocorrência da Assinatura Nº ' + view_OcorrenciasJornal.tbPlanilhaCOD_ASSINATURA.AsString +
' Data da Ocorrência: ' + view_OcorrenciasJornal.tbPlanilhaDAT_OCORRENCIA.AsString + ' não foi processada!';
end;
end;
if not sMensagem.IsEmpty then
begin
view_ResultadoProcesso.edtResultado.Lines.Add(sMensagem);
view_ResultadoProcesso.edtResultado.Refresh;
end;
view_OcorrenciasJornal.tbPlanilha.Next;
iPos := iPos + 1;
FdPos := (iPos / iTotal) * 100;
Synchronize(AtualizaProcesso);
end;
finally
Synchronize(TerminaProcesso);
Screen.Cursor := crDefault;
ocorrenciaDAO.Free;
end;
end;
procedure Thread_FinalizaOcorrenciasJornal.AtualizaProcesso;
begin
view_OcorrenciasJornal.pbOcorrencias.Position := FdPos;
view_OcorrenciasJornal.pbOcorrencias.Properties.Text := FormatFloat('0.00%',FdPos);
view_OcorrenciasJornal.pbOcorrencias.Refresh;
end;
procedure Thread_FinalizaOcorrenciasJornal.TerminaProcesso;
begin
view_OcorrenciasJornal.pbOcorrencias.Position := 0;
view_OcorrenciasJornal.pbOcorrencias.Properties.Text := '';
view_OcorrenciasJornal.pbOcorrencias.Refresh;
view_OcorrenciasJornal.tbPlanilha.IsLoading := False;
view_OcorrenciasJornal.ds.Enabled := True;
view_OcorrenciasJornal.pbOcorrencias.Visible := False;
end;
procedure Thread_FinalizaOcorrenciasJornal.SetupClass;
begin
ocorrencia.Numero := view_OcorrenciasJornal.tbPlanilhaNUM_OCORRENCIA.AsInteger;
ocorrencia.DataOcorrencia := view_OcorrenciasJornal.tbPlanilhaDAT_OCORRENCIA.AsDateTime;
ocorrencia.CodigoAssinstura := view_OcorrenciasJornal.tbPlanilhaCOD_ASSINATURA.AsString;
ocorrencia.Nome := view_OcorrenciasJornal.tbPlanilhaNOM_ASSINANTE.AsString;
ocorrencia.Roteiro := view_OcorrenciasJornal.tbPlanilhaDES_ROTEIRO.AsString;
ocorrencia.Entregador := view_OcorrenciasJornal.tbPlanilhaCOD_ENTREGADOR.AsInteger;
ocorrencia.Produto := view_OcorrenciasJornal.tbPlanilhaCOD_PRODUTO.AsString;
ocorrencia.CodigoOcorrencia := view_OcorrenciasJornal.tbPlanilhaCOD_OCORRENCIA.AsInteger;
ocorrencia.Reincidente := view_OcorrenciasJornal.tbPlanilhaDOM_REINCIDENTE.AsString;
ocorrencia.Descricao := view_OcorrenciasJornal.tbPlanilhaDES_DESCRICAO.AsString;
ocorrencia.Endereco := view_OcorrenciasJornal.tbPlanilhaDES_ENDERECO.AsString;
ocorrencia.Retorno := view_OcorrenciasJornal.tbPlanilhaDES_RETORNO.AsString;
ocorrencia.Resultado := view_OcorrenciasJornal.tbPlanilhaCOD_RESULTADO.AsInteger;
ocorrencia.Origem := view_OcorrenciasJornal.tbPlanilhaCOD_ORIGEM.AsInteger;
ocorrencia.Obs := view_OcorrenciasJornal.tbPlanilhaDES_OBS.AsString;
ocorrencia.Status := view_OcorrenciasJornal.tbPlanilhaCOD_STATUS.AsInteger;
ocorrencia.Apuracao := view_OcorrenciasJornal.tbPlanilhaDES_APURACAO.AsString;
ocorrencia.Qtde := view_OcorrenciasJornal.tbPlanilhaQTD_OCORRENCIAS.AsInteger;
ocorrencia.Valor := view_OcorrenciasJornal.tbPlanilhaVAL_OCORRENCIA.AsFloat;
ocorrencia.Impressao := view_OcorrenciasJornal.tbPlanilhaDOM_IMPRESSAO.AsString;
ocorrencia.Anexo := view_OcorrenciasJornal.tbPlanilhaDES_ANEXO.AsString;
ocorrencia.Log := view_OcorrenciasJornal.tbPlanilhaDES_LOG.AsString;
end;
end.
|
unit logsSetting;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Spin, Grids;
type TSetting = record
logFileName:string[255];
numberOfThread:byte;
ThreadLifeTime:array[1..255] of byte;
OldClearTime:byte;
end;
type
TFormSetting = class(TForm)
Label1: TLabel;
EditLogFileName: TEdit;
Label2: TLabel;
SpinEditNumThread: TSpinEdit;
Label3: TLabel;
SpinEditTimeLife: TSpinEdit;
Label4: TLabel;
Button1: TButton;
Button2: TButton;
StringGridThreadLife: TStringGrid;
procedure Button1Click(Sender: TObject);
procedure SpinEditNumThreadChange(Sender: TObject);
procedure SaveSetting;
procedure ReadSetting;
procedure UpdateInt;
procedure Button2Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure EditLogFileNameChange(Sender: TObject);
procedure SpinEditTimeLifeChange(Sender: TObject);
procedure StringGridThreadLifeDblClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
logSet:Tsetting;
isSetSaved:boolean;
end;
var
FormSetting: TFormSetting;
fset: file of TSetting;
implementation
{$R *.dfm}
procedure TFormSetting.SaveSetting;
begin
AssignFile(fset,'setup.ini');
Rewrite(fset);
Write(fset,logSet);
CloseFile(fset);
isSetSaved:=True;
end;
procedure TFormSetting.ReadSetting;
begin
AssignFile(fset,'setup.ini');
Reset(fset);
Read(fset,logSet);
CloseFile(fset);
end;
procedure TFormSetting.UpdateInt;
begin
EditLogFileName.Text:=logSet.logFileName;
SpinEditNumThread.Value:=logSet.numberOfThread;
SpinEditTimeLife.Value:=logSet.OldClearTime;
end;
procedure TFormSetting.Button1Click(Sender: TObject);
begin
if not isSetSaved then
begin
if MessageDlg('Изменения не сохранены. Закрыть без сохранения?',mtError,mbOkCancel,0)=mrOk then
begin
ReadSetting;
Close;
end;
end else
Close;
end;
procedure TFormSetting.SpinEditNumThreadChange(Sender: TObject);
var nn:byte;
begin
isSetSaved:=False;
try
logSet.numberOfThread:=SpinEditNumThread.Value;
except
logSet.numberOfThread:=0;
end;
StringGridThreadLife.RowCount:=logSet.numberOfThread;
for nn:=1 to logSet.numberOfThread do
begin
StringGridThreadLife.Cells[0,nn-1]:='Поток №'+IntToStr(nn);
StringGridThreadLife.Cells[1,nn-1]:=IntToStr(logSet.ThreadLifeTime[nn]);
end;
end;
procedure TFormSetting.Button2Click(Sender: TObject);
begin
SaveSetting;
ShowMessage('Установки сохранены.');
end;
procedure TFormSetting.FormShow(Sender: TObject);
begin
ReadSetting;
UpdateInt;
isSetSaved:=True;
end;
procedure TFormSetting.EditLogFileNameChange(Sender: TObject);
begin
isSetSaved:=False;
logSet.logFileName:=EditLogFileName.Text;
end;
procedure TFormSetting.SpinEditTimeLifeChange(Sender: TObject);
begin
isSetSaved:=False;
logSet.OldClearTime:=SpinEditTimeLife.Value;
end;
procedure TFormSetting.StringGridThreadLifeDblClick(Sender: TObject);
var srow:integer;
begin
isSetSaved:=False;
srow:=StringGridThreadLife.Selection.Top;
logSet.ThreadLifeTime[srow+1]:=StrToInt(InputBox('Введите значение:','Поток №'+IntToStr(srow+1),IntToStr(logSet.ThreadLifeTime[srow+1])));
StringGridThreadLife.Cells[1,srow]:=IntToStr(logSet.ThreadLifeTime[srow+1]);
end;
end.
|
{
TxdBuildResManage:
将指定文件编译成资源文件
编译指令:BuildResManage
TxdResManage:
使用文件名称的HASH值去匹配指定的资源文件。
编译指令:ResManage
}
unit uJxdGpResManage;
interface
uses
Windows, SysUtils, Classes, ExtCtrls, uJxdHashCalc, ActiveX, GDIPAPI, GDIPOBJ;
type
PComplieResInfo = ^TComplieResInfo;
TComplieResInfo = record
FFileName: string;
FHashString: string;
end;
PResInfo = ^TResInfo;
TResInfo = record
FBmp: TGPBitmap;
FGlb: HGLOBAL;
FRefCount: Integer;
FHashValue: string;
end;
TxdBuildResManage = class
public
constructor Create(const AProjectFileName: string);
destructor Destroy; override;
procedure AddToRes(const AFileName: string);
private
FProjectFileName: string;
FComplieResList: TList;
FTimerToNotifySave: TTimer;
FResFileName: string;
procedure DoTimerToSaveRes(Sender: TObject);
procedure FreeComplieResInfo;
procedure SetResFilename(const Value: string);
public
property ResFileName: string read FResFileName write SetResFilename;
end;
TxdResManage = class
public
constructor Create;
destructor Destroy; override;
function GetRes(const AFileName: string): TGPBitmap;
procedure RealseBitmap(const ABmp: TGPBitmap);
private
FResList: TList;
procedure FreeRes(Ap: PResInfo);
end;
{$IFDEF BuildResManage}
var
GBuildResManage: TxdBuildResManage = nil;
{$ENDIF}
{$IFDEF ResManage}
var
GResManage: TxdResManage = nil;
{$ENDIF}
implementation
const
CtResStyle = 'xdResManage';
CtResFileName = 'xdGpComponents.RES';
{ TxdResManage }
procedure TxdBuildResManage.AddToRes(const AFileName: string);
var
i: Integer;
strFileName, strHash: string;
p: PComplieResInfo;
bAdd: Boolean;
begin
if not FileExists(AFileName) then Exit;
strFileName := LowerCase(AFileName);
strHash := HashToStr( (HashString(strFileName)) );
bAdd := True;
for i := 0 to FComplieResList.Count - 1 do
begin
p := FComplieResList[i];
if CompareText(p^.FHashString, strHash) = 0 then
begin
bAdd := False;
Break;
end;
end;
if bAdd then
begin
New( p );
p^.FFileName := strFileName;
p^.FHashString := strHash;
FComplieResList.Add( p );
end;
if not Assigned(FTimerToNotifySave) then
begin
FTimerToNotifySave := TTimer.Create( nil );
FTimerToNotifySave.Interval := 2 * 1000;
FTimerToNotifySave.OnTimer := DoTimerToSaveRes;
FTimerToNotifySave.Enabled := True;
end;
end;
constructor TxdBuildResManage.Create(const AProjectFileName: string);
begin
FProjectFileName := AProjectFileName;
FResFileName := ExtractFilePath(AProjectFileName) + CtResFileName;
FComplieResList := TList.Create;
FTimerToNotifySave := nil;
end;
destructor TxdBuildResManage.Destroy;
begin
FreeComplieResInfo;
inherited;
end;
procedure TxdBuildResManage.DoTimerToSaveRes(Sender: TObject);
var
nResult: Integer;
i, nCount: Integer;
p: PComplieResInfo;
strText: TStringList;
strName: string;
bFind: Boolean;
begin
FTimerToNotifySave.Enabled := False;
if FProjectFileName = '' then
raise Exception.Create('需要设置资源文件名称:在创建TxdBuildResManage对象时设置 ProjectFileName' );
nResult := MessageBox(0, '是否保存软件所需要的资源文件?' + #13#10 + '(将它编译成RES,添加到工程目录下, 并会修改工程文件)',
'资源编译提示', MB_YESNO );
if nResult = IDYES then
begin
nCount := 0;
strText := TStringList.Create;
try
for i := 0 to FComplieResList.Count - 1 do
begin
p := FComplieResList[i];
if FileExists(p^.FFileName) then
begin
strText.Add( p^.FHashString + ' ' + CtResStyle + ' "' + p^.FFileName + '"' );
Inc( nCount );
end;
end;
if nCount > 0 then
begin
while FileExists(ResFileName) do
begin
DeleteFile( ResFileName );
Sleep( 100 );
end;
Sleep( 500 );
strName := StringReplace( ResFileName, '.RES', '.rc', [rfReplaceAll, rfIgnoreCase] );
strText.SaveToFile( strName );
Sleep( 500 );
WinExec( PChar('brcc32.exe "' + strName + '"'), SW_SHOWNORMAL );
Sleep( 500 );
while FileExists(strName) do
DeleteFile( strName );
end;
finally
strText.Free;
end;
if FileExists(ResFileName) then
begin
strText := TStringList.Create;
strText.LoadFromFile( FProjectFileName );
if CompareText(ExtractFilePath(FResFileName), ExtractFilePath(FProjectFileName)) = 0 then
strName := ExtractFileName( FResFileName )
else
strName := FResFileName;
bFind := False;
for i := 0 to strText.Count - 1 do
begin
if Pos(strName, strText[i]) > 0 then
begin
bFind := True;
strText[i] := '{$R ' + strName + '}';
Break;
end;
end;
if not bFind then
begin
for i := 0 to strText.Count - 1 do
begin
if CompareText('begin', strText[i]) = 0 then
begin
bFind := True;
strText.Insert(i - 1, '{$R ' + strName + '}' );
Break;
end;
end;
if not bFind and (strText.Count > 2) then
begin
strText.Insert(i - 1, '{$R ' + strName + '}' );
bFind := True;
end;
end;
if bFind then
strText.SaveToFile( FProjectFileName );
strText.Free;
if bFind then
MessageBox( 0, '编译成功, 并已修改了工程文件' + #13#10 +
' 关闭软件之后再去掉编译条件:BuildResManage之后再重新编译一次', '提示', MB_OK )
else
MessageBox( 0, '编译成功, 但无法修改工程文件,请确定设置是正确的', '提示', MB_OK )
end;
FreeAndNil( FTimerToNotifySave );
end
else
FTimerToNotifySave.Enabled := True;
end;
procedure TxdBuildResManage.FreeComplieResInfo;
var
i: Integer;
begin
FreeAndNil( FTimerToNotifySave );
for i := 0 to FComplieResList.Count - 1 do
Dispose( FComplieResList[i] );
FComplieResList.Clear;
FreeAndNil( FComplieResList );
end;
procedure TxdBuildResManage.SetResFilename(const Value: string);
begin
if Value <> '' then
FResFileName := Value;
end;
{ TxdResManage }
constructor TxdResManage.Create;
begin
FResList := TList.Create;
end;
destructor TxdResManage.Destroy;
var
i: Integer;
begin
for i := 0 to FResList.Count - 1 do
FreeRes( FResList[i] );
FResList.Free;
inherited;
end;
procedure TxdResManage.FreeRes(Ap: PResInfo);
begin
if Assigned(Ap^.FBmp) then
Ap^.FBmp.Free;
GlobalFree( Ap^.FGlb );
Dispose( Ap );
end;
function TxdResManage.GetRes(const AFileName: string): TGPBitmap;
var
i: Integer;
p: PResInfo;
strHash: string;
res: TResourceStream;
pBuf: PByte;
stream: IStream;
begin
Result := nil;
if AFileName = '' then Exit;
strHash := HashToStr( (HashString(LowerCase(AFileName))) );
for i := 0 to FResList.Count - 1 do
begin
p := FResList[i];
if CompareText(strHash, p^.FHashValue) = 0 then
begin
Result := p^.FBmp;
Inc( p^.FRefCount );
Break;
end;
end;
if not Assigned(Result) then
begin
try
res := TResourceStream.Create( HInstance, strHash, CtResStyle );
except
Exit;
end;
New( p );
p^.FGlb := GlobalAlloc( GHND, res.Size );
pBuf := GlobalLock( p^.FGlb );
res.Read( pBuf^, res.Size );
GlobalUnlock( p^.FGlb );
Res.Free;
CreateStreamOnHGlobal(p^.FGlb, False, stream );
p^.FBmp := TGPBitmap.Create( stream );
p^.FRefCount := 1;
p^.FHashValue := strHash;
FResList.Add( p );
Result := p^.FBmp;
end;
end;
procedure TxdResManage.RealseBitmap(const ABmp: TGPBitmap);
var
i: Integer;
p: PResInfo;
begin
for i := 0 to FResList.Count - 1 do
begin
p := FResList[i];
if p^.FBmp = ABmp then
begin
Dec( p^.FRefCount );
if p^.FRefCount <= 0 then
begin
FreeRes( p );
FResList.Delete( i );
end;
Break;
end;
end;
end;
initialization
{$IFDEF ResManage}
GResManage := TxdResManage.Create;
{$ENDIF}
finalization
{$IFDEF ResManage}
FreeAndNil( GResManage );
{$ENDIF}
end.
|
unit DataProxy.Customers;
interface
uses
Data.DB,
Data.DataProxy;
type
TCustomersProxy = class(TDatasetProxy)
protected
procedure ConnectFields; override;
public
CustomerID: TWideStringField;
CompanyName: TWideStringField;
ContactName: TWideStringField;
ConstacTitle: TWideStringField;
Address: TWideStringField;
City: TWideStringField;
Region: TWideStringField;
PostalCode: TWideStringField;
Country: TWideStringField;
Phone: TWideStringField;
Fax: TWideStringField;
// property DataSet: TDataSet read FDataSet;
end;
implementation
{ TOrder }
uses
System.SysUtils,
Database.Connector;
procedure TCustomersProxy.ConnectFields;
begin
CustomerID := FDataSet.FieldByName('CustomerID') as TWideStringField;
CompanyName := FDataSet.FieldByName('CompanyName') as TWideStringField;
ContactName := FDataSet.FieldByName('ContactName') as TWideStringField;
ConstacTitle := FDataSet.FieldByName('ConstacTitle') as TWideStringField;
Address := FDataSet.FieldByName('Address') as TWideStringField;
City := FDataSet.FieldByName('City') as TWideStringField;
Region := FDataSet.FieldByName('Region') as TWideStringField;
PostalCode := FDataSet.FieldByName('PostalCode') as TWideStringField;
Country := FDataSet.FieldByName('Country') as TWideStringField;
Phone := FDataSet.FieldByName('Phone') as TWideStringField;
Fax := FDataSet.FieldByName('Fax') as TWideStringField;
end;
end.
|
unit DTT_Network;
interface
uses
TNT_Vector;
const
SERVER_PORT = 30000;
MAX_PLAYERS = 4;
MSG_JOIN = 0;
MSG_PART = 1;
MSG_POSITION = 2;
type
TPlayerState = packed record
Name: String[16];
ID: Byte;
Position: TVector;
T: Single;
NbRocket: Byte;
Col: Byte;
Frame: Byte;
end;
TPlayerMsg = packed record
Name: String[16];
Port: Integer;
Msg: Byte;
end;
TGame = packed record
NbPlayers: Byte;
Players: packed array [1..MAX_PLAYERS] of TPlayerState;
end;
var
NetGame: TGame;
procedure InitNetGame;
implementation
procedure InitNetGame;
var
i: Integer;
begin
with NetGame do
begin
NbPlayers := 0;
for i := 1 to MAX_PLAYERS do
Players[i].Name := '';
end;
end;
end.
|
Unit uDToolServer;
interface
uses
Windows, Messages, Forms, Classes, System.SysUtils,
System.Generics.Collections,
HPSocketSDKUnit,
uGlobal
;
const
S_RET_OK = 'OK';
type
TConsoleSvr = class
private
FAppState : EnAppState;
FServer : Pointer;
FListener : Pointer;
FHost: string;
FPort: Word;
public
constructor Create();
destructor Destroy; override;
function Start(): En_HP_HandleResult;
function Stop(): En_HP_HandleResult;
function DisConn(AConnID: DWORD): En_HP_HandleResult;
{$REGION '通讯'}
function SuspendTask(AConnID: DWORD; AGroupName: string): Boolean;
function ResumeTask(AConnID: DWORD; AGroupName: string): Boolean;
function StopTask(AConnID: DWORD; AGroupName: string): Boolean;
function Shutdown(AConnID: DWORD; AGroupName: string): Boolean;
function ReBoot(AConnID: DWORD; AGroupName: string): Boolean;
function LogOff(AConnID: DWORD; AGroupName: string): Boolean;
//--发货机关闭或者,发货机异常后,处理订单
function SendMachineClose(AConnId: DWORD): Boolean;
function RetCmdOk(AConnId: DWORD): Boolean;
//---
function RetRoleStep(AConnId: DWORD; ARoleStep: TRoleStep): Boolean;
function RetRecvRoleName(AConnId: DWORD; ARecvRoleName: string): Boolean;
{$ENDREGION}
property Host: string read FHost write FHost;
property Port: Word read FPort write FPort;
property AppState: EnAppState read FAppState write FAppState;
property Server: Pointer read FServer write FServer;
end;
TDoCmd = class(TThread)
private
FCmd : string;
FConnID : DWORD;
protected
procedure Execute; override;
public
constructor Create(AConnID: DWORD; ALen: Integer; AData: Pointer);
destructor Destroy; override;
end;
var
ConsoleSvr: TConsoleSvr;
implementation
uses
ManSoy.Global,
ManSoy.Encode,
uJsonClass,
uTaskManager,
uCommand;
{ TDataHandleThread }
constructor TDoCmd.Create(AConnID: DWORD; ALen: Integer; AData: Pointer);
var
sCmd: AnsiString;
begin
FreeOnTerminate := True;
inherited Create(True);
// 以下是一个pData转字符串的演示
SetLength(sCmd, ALen);
Move(AData^, sCmd[1], ALen);
FCmd := Trim(string(sCmd));
FConnID := AConnID;
end;
destructor TDoCmd.Destroy;
begin
inherited;
end;
procedure TDoCmd.Execute;
var
vLst: TStrings;
sCmd, sGroupName, sKey, sJson, sTargetRoleName, sRoleName: string;
iRoleStep: Integer;
begin
try
{ TODO : 在这里处理,客户端请求 }
if FCmd = '' then Exit;
vLst := TStringList.Create;
try
vLst.Delimiter := ',';
vLst.DelimitedText := FCmd;
if vLst.Count = 0 then Exit;
sCmd := Trim(vLst.Values['cmd']);
if sCmd = '' then Exit;
if sCmd = 'GetTask' then
begin
sGroupName := vLst.Values['GroupName'];
sJson := ConnManager.GetConnOrderInfo(sGroupName);
uCommand.Cmd_RetTask(ConsoleSvr.Server, FConnID, sJson);
end else if sCmd = 'GetParam' then
begin
sJson := TSerizalizes.AsJSON<TConsoleSet>(GConsoleSet);
uCommand.Cmd_RetParam(ConsoleSvr.Server, FConnID, sJson);
end else if sCmd = 'RetState' then
begin
//--设置状态
sJson := Trim(vLst.Values['Json']);
SetTaskState(sJson);
end else if sCmd = 'EndTask' then
begin
//--发货机已经发完货, 或者异常了
sGroupName := Trim(vLst.Values['GroupName']);
sKey := Trim(vLst.Values['Key']);
uTaskManager.EndTask(sGroupName, sKey);
end else if sCmd = 'SuspendTask' then
begin
//--发货机已经发完货, 或者异常了
sGroupName := Trim(vLst.Values['GroupName']);
uTaskManager.SuspendTask(sGroupName);
end else if sCmd = 'Connection' then
begin
sGroupName := Trim(vLst.Values['GroupName']);
uTaskManager.AddConnItem(FConnID, sGroupName);
end else if sCmd = 'SetRoleStep' then
begin
ManSoy.Global.DebugInf('MS - %s', [FCmd]);
TaskManager.SetRoleStep(FCmd, FConnID);
end else if sCmd = 'ReSetRoleStep' then
begin
sGroupName := Trim(vLst.Values['GroupName']);
sRoleName := Trim(vLst.Values['RoleName']);
sTargetRoleName := Trim(vLst.Values['TargetRoleName']);
iRoleStep := StrToIntDef(Trim(vLst.Values['RoleStep']), 0);
ConnManager.ReSetRoleStep(FConnID, sGroupName, sRoleName, sTargetRoleName, TRoleStep(iRoleStep));
end else if sCmd = 'GetRoleStep' then
begin
sGroupName := Trim(vLst.Values['GroupName']);
ConnManager.RetRoleStep(FConnID, sGroupName);
end else if sCmd = 'GetTargetRoleStep' then
begin
ManSoy.Global.DebugInf('MS - %s', [FCmd]);
sGroupName := Trim(vLst.Values['GroupName']);
sRoleName := Trim(vLst.Values['RoleName']);
sTargetRoleName := Trim(vLst.Values['TargetRoleName']);
ConnManager.RetTargetRoleStep(FConnID, sGroupName, sRoleName, sTargetRoleName);
end else if sCmd = 'GetMasterRecRoleName' then
begin
sGroupName := Trim(vLst.Values['GroupName']);
sRoleName := Trim(vLst.Values['MasterRoleName']);
ConnManager.RetRecvRoleName(FConnID, sGroupName, sRoleName);
end else if sCmd = 'SetMasterRecRoleName' then
begin
AddLogMsg('MS - %s', [FCmd], True);
TaskManager.SetMasterRecRoleName(FCmd, FConnID);
end else if sCmd = 'ClearRecvRoleName' then
begin
AddLogMsg('MS - %s', [FCmd], True);
TaskManager.ClearRecvRoleName(FCmd, FConnID);
end;
finally
FreeAndNil(vLst);
end;
except
end
end;
{ TConsoleSvr }
function OnPrepareListen(soListen: Pointer): En_HP_HandleResult; stdcall;
begin
Result := HP_HR_OK;
end;
function OnAccept(dwConnId: DWORD; pClient: Pointer): En_HP_HandleResult; stdcall;
var
ip: array [0 .. 40] of WideChar;
ipLength: Integer;
port: USHORT;
begin
ipLength := 40;
if HP_Server_GetRemoteAddress(ConsoleSvr.Server, dwConnId, ip, @ipLength, @port) then
begin
//uGlobal.AddLogMsg(' > [%d,OnAccept] -> PASS(%s:%d)', [dwConnId, string(ip), port]);
end else
begin
//uGlobal.AddLogMsg(' > [%d,OnAccept] -> HP_Server_GetClientAddress() Error', [dwConnId]);
end;
Result := HP_HR_OK;
end;
function OnServerShutdown(): En_HP_HandleResult; stdcall;
begin
//uGlobal.AddLogMsg(' > [OnServerShutdown]', []);
Result := HP_HR_OK;
end;
function OnSend(dwConnId: DWORD; const pData: Pointer; iLength: Integer): En_HP_HandleResult; stdcall;
begin
//uGlobal.AddLogMsg(' > [%d,OnSend] -> (%d bytes)', [dwConnId, iLength]);
Result := HP_HR_OK;
end;
function OnReceive(dwConnId: DWORD; const pData: Pointer; iLength: Integer): En_HP_HandleResult; stdcall;
var
{$IFDEF _MS_DEBUG}
testString: Ansistring;
{$ENDIF}
doRec : TDoCmd;
begin
// uGlobal.AddLogMsg(' > [%d,OnReceive] -> (%d bytes)', [dwConnId, iLength]);
//
{$IFDEF _MS_DEBUG}
// 以下是一个pData转字符串的演示
SetLength(testString, iLength);
Move(pData^, testString[1], iLength);
//uGlobal.AddLogMsg(' > [%d,OnReceive] -> say:%s', [dwConnId, string(testString)]);
{$ENDIF}
doRec := TDoCmd.Create(dwConnId, iLength, pData);
doRec.Resume;
Result := HP_HR_OK;
end;
function OnCloseConn(dwConnId: DWORD): En_HP_HandleResult; stdcall;
begin
ConsoleSvr.SendMachineClose(dwConnId);
//uGlobal.AddLogMsg(' > [%d,OnCloseConn]', [dwConnId]);
Result := HP_HR_OK;
end;
function OnError(dwConnId: DWORD; enOperation: En_HP_SocketOperation; iErrorCode: Integer): En_HP_HandleResult; stdcall;
begin
//ConsoleSvr.SendMachineClose(dwConnId);
uGlobal.AddLogMsg('> [%d,OnError] -> OP:%d,CODE:%d', [dwConnId, Integer(enOperation), iErrorCode]);
Result := HP_HR_OK;
end;
constructor TConsoleSvr.Create;
begin
// 创建监听器对象
FListener := Create_HP_TcpServerListener();
// 创建 Socket 对象
FServer := Create_HP_TcpServer(FListener);
// 设置 Socket 监听器回调函数
HP_Set_FN_Server_OnPrepareListen(FListener, OnPrepareListen);
HP_Set_FN_Server_OnAccept(FListener, OnAccept);
HP_Set_FN_Server_OnSend(FListener, OnSend);
HP_Set_FN_Server_OnReceive(FListener, OnReceive);
HP_Set_FN_Server_OnClose(FListener, OnCloseConn);
HP_Set_FN_Server_OnError(FListener, OnError);
HP_Set_FN_Server_OnShutdown(FListener, OnServerShutdown);
FAppState := ST_STOPED;
end;
destructor TConsoleSvr.Destroy;
begin
// 销毁 Socket 对象
Destroy_HP_TcpServer(FServer);
// 销毁监听器对象
Destroy_HP_TcpServerListener(FListener);
inherited;
end;
function TConsoleSvr.DisConn(AConnID: DWORD): En_HP_HandleResult;
begin
Result := HP_HR_ERROR;
if HP_Server_Disconnect(FServer, AConnID, 1) then
uGlobal.AddLogMsg('(%d) Disconnect OK', [AConnID])
else
uGlobal.AddLogMsg('(%d) Disconnect Error', [AConnID]);
Result := HP_HR_OK;
end;
function TConsoleSvr.Start: En_HP_HandleResult;
var
errorId: En_HP_SocketError;
errorMsg: PWideChar;
begin
Result := HP_HR_ERROR;
FAppState := ST_STARTING;
if not HP_Server_Start(FServer, PWideChar(Host), Port) then
begin
errorId := HP_Server_GetLastError(FServer);
errorMsg := HP_Server_GetLastErrorDesc(FServer);
uGlobal.AddLogMsg('Server Start Error -> %s(%d)', [errorMsg, Integer(errorId)]);
FAppState := ST_STOPED;
Exit;
end;
uGlobal.AddLogMsg('Server Start OK -> (%s:%d)', [Host, Port]);
FAppState := ST_STARTED;
Result := HP_HR_OK;
end;
function TConsoleSvr.Stop: En_HP_HandleResult;
var
errorId: En_HP_SocketError;
errorMsg: PWideChar;
begin
Result := HP_HR_ERROR;
FAppState := ST_STOPING;
if not HP_Server_Stop(FServer) then
begin
errorId := HP_Server_GetLastError(FServer);
errorMsg := HP_Server_GetLastErrorDesc(FServer);
uGlobal.AddLogMsg('Stop Error -> %s(%d)', [errorMsg, Integer(errorId)]);
Exit;
end;
uGlobal.AddLogMsg('Server Stop', []);
FAppState := ST_STOPED;
Result := HP_HR_OK;
end;
{$REGION '通讯'}
function TConsoleSvr.SuspendTask(AConnID: DWORD; AGroupName: string): Boolean;
begin
Result := uCommand.Cmd_SuspendTask(Server, AConnID, AGroupName);
end;
function TConsoleSvr.ResumeTask(AConnID: DWORD; AGroupName: string): Boolean;
begin
Result := uCommand.Cmd_ResumeTask(Server, AConnID, AGroupName);
end;
function TConsoleSvr.StopTask(AConnID: DWORD; AGroupName: string): Boolean;
begin
Result := uCommand.Cmd_StopTask(Server, AConnID, AGroupName);
end;
function TConsoleSvr.Shutdown(AConnID: DWORD; AGroupName: string): Boolean;
begin
Result := uCommand.Cmd_Shutdown(Server, AConnID, AGroupName);
end;
function TConsoleSvr.ReBoot(AConnID: DWORD; AGroupName: string): Boolean;
begin
Result := uCommand.Cmd_ReStart(Server, AConnID, AGroupName);
end;
function TConsoleSvr.LogOff(AConnID: DWORD; AGroupName: string): Boolean;
begin
Result := uCommand.Cmd_Logout(Server, AConnID, AGroupName);
end;
function TConsoleSvr.SendMachineClose(AConnId: DWORD): Boolean;
var
sGroupName: string;
vConnItem: TConnItem;
vOrderInfo: TOrderItem;
I, iRoleIndex: Integer;
begin
sGroupName := ConnManager.GetGroupName(AConnId);
if sGroupName = '' then Exit;
vConnItem := ConnManager.Items[sGroupName];
if vConnItem = nil then Exit;
try
vOrderInfo := vConnItem.OrderItem;
if vOrderInfo = nil then
begin
SendMessage(GSharedInfo.MainFormHandle, WM_DEL_SEND_MACHINE, 0, LPARAM(sGroupName));
Exit;
end;
if Length(vOrderInfo.roles) = 0 then Exit;
vConnItem.LogMsgs.Add('发货机异常中断');
vConnItem.IsAbnormal := True;
vConnItem.State := sms异常;
vConnItem.RoleStep := rsNormal;
vConnItem.Suspend := False;
for i := Low(vOrderInfo.roles) to High(vOrderInfo.roles) do
begin
vOrderInfo.roles[i].taskState := Integer(tsFail);
vOrderInfo.roles[i].logMsg := '发货机异常中断';
//uCommand.PostState(vOrderInfo, I, GSharedInfo.ClientSet.GroupName, GConsoleSet.StateInterface);
end;
finally
//SendMessage(GSharedInfo.MainFormHandle, WM_DEL_SEND_MACHINE, 0, LPARAM(sGroupName));
end;
end;
function TConsoleSvr.RetCmdOk(AConnId: DWORD): Boolean;
begin
Result := uCommand.Cmd_CmdOK(Server, AConnId);
end;
function TConsoleSvr.RetRoleStep(AConnId: DWORD; ARoleStep: TRoleStep): Boolean;
begin
Result := uCommand.Cmd_RetRoleStep(Server, AConnId, ARoleStep);
end;
function TConsoleSvr.RetRecvRoleName(AConnId: DWORD; ARecvRoleName: string): Boolean;
begin
Result := uCommand.Cmd_RetRecvRoleName(Server, AConnId, ARecvRoleName);
end;
{$ENDREGION}
end.
|
{ Subroutine STRING_T_BITSC (S, BITS, STAT)
*
* Convert the string in S to the 8 bit CHAR in BITS. STAT is the completion
* status code.
}
module string_t_bitsc;
define string_t_bitsc;
%include 'string2.ins.pas';
procedure string_t_bitsc ( {convert 8 digit binary string to character}
in s: univ string_var_arg_t; {input string}
out bits: char; {output character}
out stat: sys_err_t); {completion status code}
var
im: sys_int_max_t; {raw integer value}
begin
string_t_int_max_base ( {convert string to raw integer}
s, {input string}
2, {number base of string}
[], {signed number, blank is error}
im, {raw integer value}
stat);
if sys_error(stat) then return;
if (im >= -128) and (im <= 127)
then begin {value is within range}
bits := chr(im); {pass back result}
end
else begin {value is out of range}
sys_stat_set (string_subsys_k, string_stat_ovfl_i_k, stat);
sys_stat_parm_vstr (s, stat);
end
;
end;
|
(*
@abstract(Contient le "Manager de son" pour la librairie Bass)
Les pilotes officiels de Bass peuvent être téléchargés à partir du site un4seen (http://www.un4seen.com).@br
Cette version est disponible pour les plateformes (Windows, Linux et Android) @br
et supporte les environnements 32bits et 64bits.
Actuellement Bass sound manager supporte : @br
@unorderedList(
@item (Le positionnement des sons en 3D)
@item (Les filtres :
@unorderedList(
@item (Low pass)
@item (Hi pass)
@item (Band pass)
))
@item (Les effets :
@unorderedList(
@item (Reverb)
@item (EAX Reverb)
@item (Chorus)
@item (Echo)
@item (Distorsion)
@item (Flanger)
@item (Ring Tone)
@item (Equalizer)
))
@item (Nombre d'effets maximum par source : 4 + 1 filtre direct)
@item (Effet Doppler)
@item (Le changement du volume principal)
@item (Le changement du volume d'une source)
@item (Le changement de pitch d'une source)
@item (Le support de sons multi-cannaux (1 = Mono, 2 = Strereo, 3 et 4 = Quadriphonie, 6 = 5.1, 7 = 6.1 et 8 = 7.1 ))
@item (Le support des environnement 3D virtuels via les effets REVERB et EAX_REVERB (Uniquement sous Windows) )
)
-------------------------------------------------------------------------------------------------------------
@created(2016-11-16)
@author(J.Delauney (BeanzMaster))
Historique : @br
@unorderedList(
@item(05/11/2017 : Creation )
)
-------------------------------------------------------------------------------------------------------------
@bold(Notes) : @br
-------------------------------------------------------------------------------------------------------------
@bold(Dépendances) :
-------------------------------------------------------------------------------------------------------------
Credits :
@unorderedList(
@item (Codé sur une base de GLScene http://www.sourceforge.net/glscene)
)
-------------------------------------------------------------------------------------------------------------
@bold(Licence) : MPL / GPL
------------------------------------------------------------------------------------------------------------- *)
unit BZBassManager;
//==============================================================================
{$mode objfpc}{$H+}
{$i ..\..\bzscene_options.inc}
//==============================================================================
interface
uses
Classes, SysUtils, Forms, Controls,
BZLibBass, BZMath, BZSound, BZSoundSample;
Type
{ Exception levée par TBZSoundBassManager }
EBZSoundBassManager = class(EBZSoundException);
TBZBass3DAlgorithm = (baDefault, baOff, baFull, baLight);
{ Gestionnaire audio pour Bass }
TBZSoundBassManager = class (TBZSoundManager)
private
FActivated : Boolean;
FAlgorithm3D : TBZBASS3DAlgorithm;
FChanges : TBZSoundManagerChanges;
protected
function GetErrorString(ErrCode : Integer) : String;
procedure ShowError(msg: string);
function DoActivate : Boolean; override;
procedure DoDeActivate; override;
procedure NotifyMasterVolumeChange; override;
procedure Notify3DFactorsChanged; override;
procedure NotifyEnvironmentChanged; override;
procedure KillSource(aSource : TBZBaseSoundSource); override;
procedure UpdateSource(aSource : TBZBaseSoundSource); override;
procedure MuteSource(aSource : TBZBaseSoundSource; muted : Boolean); override;
procedure PauseSource(aSource : TBZBaseSoundSource; paused : Boolean); override;
procedure PlaySource(aSource : TBZBaseSoundSource; playing : Boolean); override;
function GetDefaultFrequency(aSource : TBZBaseSoundSource) : Integer; override;
function GetTimePosition(aSource : TBZBaseSoundSource): Single; override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure UpdateSources; override;
function CPUUsagePercent : Single; override;
function EAXSupported : Boolean; override;
function GetInformations : String; override;
{ Retourne les changements d'état lors de la lecture d'une source audio }
property Changes : TBZSoundManagerChanges read FChanges;
published
property Algorithm3D : TBZBass3DAlgorithm read FAlgorithm3D write FAlgorithm3D default baDefault;
end;
type
TBZBASSInfo = record
channel : HCHANNEL;
sample : HSAMPLE;
end;
PBZBASSInfo = ^TBZBASSInfo;
implementation
uses
BZLogger, BZTypesHelpers, BZVectorMath, Dialogs;
procedure VectorToBASSVector(const aVector : TBZVector; var aBASSVector : BASS_3DVECTOR);
begin
aBASSVector.x:=aVector.X;
aBASSVector.y:=aVector.Y;
aBASSVector.z:=-aVector.Z;
end;
constructor TBZSoundBassManager.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
GlobalLogger.LogNotice('Initialize Sound BASS Manager. Ver ' + BASSVERSIONTEXT);
FAlgorithm3D := baFull;
// check the correct BASS was loaded
if (HI(BASS_GetVersion) <> BASSVERSION) then
begin
MessageDlg('An incorrect version of BASS.DLL was loaded', mtError, [mbOK],0);
Halt;
end;
// Initialize audio - default device, 44100hz, stereo, 16 bits
//if not(BASS_Init(-1, 44100, 0, Handle, nil) then ShowError('Error initialization ! ');
//if not(BASS_Init(1, OutputFrequency, BASS_DEVICE_3D, (TWinControl(Owner).Handle), nil)) then
//begin
// ShowError('Error initializing audio!');
// Exit;
//end;
//
//BASS_Load(bassdll);
MaxChannels:=32;
end;
destructor TBZSoundBassManager.Destroy;
begin
GlobalLogger.LogNotice('Finalize Sound BASS Manager');
inherited Destroy;
//BASS_UnLoad;
end;
function TBZSoundBassManager.GetErrorString(ErrCode : Integer) : String;
begin
Case ErrCode of
BASS_OK:
Result := 'all is OK';
BASS_ERROR_MEM:
Result := 'memory error';
BASS_ERROR_FILEOPEN:
Result := 'can''t open the file';
BASS_ERROR_DRIVER:
Result := 'can''t find a free/valid driver';
BASS_ERROR_BUFLOST:
Result := 'the sample buffer was lost';
BASS_ERROR_HANDLE:
Result := 'invalid handle';
BASS_ERROR_FORMAT:
Result := 'unsupported sample format';
BASS_ERROR_POSITION:
Result := 'invalid position';
BASS_ERROR_INIT:
Result := 'BASS_Init has not been successfully called';
BASS_ERROR_START:
Result := 'BASS_Start has not been successfully called';
BASS_ERROR_ALREADY:
Result := 'already initialized/paused/whatever';
BASS_ERROR_NOCHAN:
Result := 'can''t get a free channel';
BASS_ERROR_ILLTYPE:
Result := 'an illegal type was specified';
BASS_ERROR_ILLPARAM:
Result := 'an illegal parameter was specified';
BASS_ERROR_NO3D:
Result := 'no 3D support';
BASS_ERROR_NOEAX:
Result := 'no EAX support';
BASS_ERROR_DEVICE:
Result := 'illegal device number';
BASS_ERROR_NOPLAY:
Result := 'not playing';
BASS_ERROR_FREQ:
Result := 'illegal sample rate';
BASS_ERROR_NOTFILE:
Result := 'the stream is not a file stream';
BASS_ERROR_NOHW:
Result := 'no hardware voices available';
BASS_ERROR_EMPTY:
Result := 'the MOD music has no sequence data';
BASS_ERROR_NONET:
Result := 'no internet connection could be opened';
BASS_ERROR_CREATE:
Result := 'couldn''t create the file';
BASS_ERROR_NOFX:
Result := 'effects are not available';
BASS_ERROR_NOTAVAIL:
Result := 'requested data is not available';
BASS_ERROR_DECODE:
Result := 'the channel is/isn''t a decoding channel';
BASS_ERROR_DX:
Result := 'a sufficient DirectX version is not installed';
BASS_ERROR_TIMEOUT:
Result := 'connection timedout';
BASS_ERROR_FILEFORM:
Result := 'unsupported file format';
BASS_ERROR_SPEAKER:
Result := 'unavailable speaker';
BASS_ERROR_VERSION:
Result := 'invalid BASS version (used by add-ons)';
BASS_ERROR_CODEC:
Result := 'codec is not available/supported';
BASS_ERROR_ENDED:
Result := 'the channel/file has ended';
BASS_ERROR_BUSY:
Result := 'the device is busy';
BASS_ERROR_UNKNOWN:
Result := 'Unknown Error';
else
Result := 'Unknown Error';
end;
end;
procedure TBZSoundBassManager.ShowError(msg: string);
var
s: string;
begin
s := msg + LineEnding + 'Error code : ' + IntToStr(BASS_ErrorGetCode) +
LineEnding + ' Message : ' + GetErrorString(BASS_ErrorGetCode);
GlobalLogger.LogError(s);
MessageDlg(s, mtError, [mbOK],0);
end;
function TBZSoundBassManager.DoActivate : Boolean;
const
c3DAlgo : array [baDefault..baLight] of Integer =
(BASS_3DALG_DEFAULT, BASS_3DALG_OFF, BASS_3DALG_FULL, BASS_3DALG_LIGHT);
begin
//Assert(bass_isloaded,'BASS DLL is not present');
GlobalLogger.LogNotice('Activate Sound BASS Manager. OutputFrequency = ' + OutputFrequency.ToString);
//
if not(BASS_Init(-1, OutputFrequency, BASS_DEVICE_3D + BASS_DEVICE_SPEAKERS + BASS_DEVICE_FREQ, (TWinControl(Owner).Handle), nil)) then
begin
Raise EBZSoundBassManager.Create('Error on initializing engine !' + LineEnding + GetErrorString(BASS_ErrorGetCode));
Result:=False;
Exit;
end;
if not(BASS_Start) then
begin
Raise EBZSoundBassManager.Create('Error on start engine !' + LineEnding + GetErrorString(BASS_ErrorGetCode));
Result:=False;
Exit;
end;
FActivated := True;
BASS_SetConfig(BASS_CONFIG_3DALGORITHM, c3DAlgo[FAlgorithm3D]);
NotifyMasterVolumeChange;
Notify3DFactorsChanged;
if (Environment<>seGeneric) then NotifyEnvironmentChanged;
Result:=True;
end;
procedure TBZSoundBassManager.DoDeActivate;
begin
//GlobalLogger.LogNotice('Desactivate Sound BASS Manager');
FActivated:=False;
BASS_Stop;
BASS_Free;
end;
procedure TBZSoundBassManager.NotifyMasterVolumeChange;
begin
if FActivated then BASS_SetVolume(MasterVolume);
end;
procedure TBZSoundBassManager.Notify3DFactorsChanged;
begin
if FActivated then BASS_Set3DFactors(DistanceFactor, RollOffFactor, DopplerFactor);
end;
procedure TBZSoundBassManager.NotifyEnvironmentChanged;
const
cEnvironmentToBASSConstant : array [seGeneric..sePsychotic] of Integer = (
EAX_ENVIRONMENT_GENERIC, EAX_ENVIRONMENT_PADDEDCELL, EAX_ENVIRONMENT_ROOM,
EAX_ENVIRONMENT_BATHROOM, EAX_ENVIRONMENT_LIVINGROOM, EAX_ENVIRONMENT_STONEROOM,
EAX_ENVIRONMENT_AUDITORIUM, EAX_ENVIRONMENT_CONCERTHALL, EAX_ENVIRONMENT_CAVE,
EAX_ENVIRONMENT_ARENA, EAX_ENVIRONMENT_HANGAR, EAX_ENVIRONMENT_CARPETEDHALLWAY,
EAX_ENVIRONMENT_HALLWAY, EAX_ENVIRONMENT_STONECORRIDOR, EAX_ENVIRONMENT_ALLEY,
EAX_ENVIRONMENT_FOREST, EAX_ENVIRONMENT_CITY, EAX_ENVIRONMENT_MOUNTAINS,
EAX_ENVIRONMENT_QUARRY, EAX_ENVIRONMENT_PLAIN, EAX_ENVIRONMENT_PARKINGLOT,
EAX_ENVIRONMENT_SEWERPIPE, EAX_ENVIRONMENT_UNDERWATER, EAX_ENVIRONMENT_DRUGGED,
EAX_ENVIRONMENT_DIZZY, EAX_ENVIRONMENT_PSYCHOTIC);
begin
if FActivated and EAXSupported then BASS_SetEAXParameters(cEnvironmentToBASSConstant[Environment],-1,-1,-1);
end;
procedure TBZSoundBassManager.KillSource(aSource : TBZBaseSoundSource);
var
p : PBZBASSInfo;
begin
if aSource.ManagerTag<>0 then
begin
GlobalLogger.LogNotice('KillSource');
p := PBZBASSInfo(aSource.ManagerTag);
if p^.channel<>0 then
if not(BASS_ChannelStop(p^.channel)) then ShowError('Error kill source !'); //Assert(False);
BASS_SampleFree(p^.sample);
FreeMem(p);
aSource.ManagerTag := 0;
end;
end;
procedure TBZSoundBassManager.UpdateSource(aSource : TBZBaseSoundSource);
var
i : Integer;
p : PBZBASSInfo;
objPos, objOri, objVel : TBZVector;
position, orientation, velocity : BASS_3DVECTOR;
res: Boolean;
FxItem : TBZCustomSoundFXItem;
begin
//if (sscSample in aSource.Changes) then
//begin
// KillSource(aSource);
//end;
if (sscNewSample in aSource.Changes) or (sscSample in aSource.Changes) then
begin
if (Cadencer.Enabled=True) then Cadencer.Enabled := False;
KillSource(aSource);
aSource.Changes := aSource.Changes - [sscNewSample];
Cadencer.Enabled := True;
end;
// Creation d'un source OpenAL, si besoin, et place son ID dans aSource.ManagerTag
if aSource.SoundName <> '' then
begin
if (aSource.Sample=nil) or (aSource.Sample.Data=nil) or
(aSource.Sample.Data.SoundDataSize = 0) then Exit;
if (aSource.ManagerTag = 0) then
begin
//GlobalLogger.LogNotice('UpdateSource - Loading Data');
p := AllocMem(SizeOf(TBZBASSInfo));
p^.channel := 0;
i := BASS_SAMPLE_VAM + BASS_SAMPLE_OVER_DIST;// + BASS_SAMPLE_3D;
if aSource.Sample.Data.BitsPerSample = 8 then i := i + BASS_SAMPLE_8BITS;
if aSource.NbLoops>1 then i := i + BASS_SAMPLE_LOOP;
//GlobalLogger.LogStatus('- Sample Data Size in bytes = ' + aSource.Sample.Data.SoundDataSize.ToString);
//GlobalLogger.LogStatus('- Sample Data Frequency = ' + aSource.Sample.Data.Frequency.ToString);
//GlobalLogger.LogStatus('- Sample Data Channels = ' + aSource.Sample.Data.NbChannels.ToString);
//GlobalLogger.LogStatus('- Sample Data Bits per sample = ' + aSource.Sample.Data.BitsPerSample.ToString);
p^.Sample := BASS_SampleCreate(aSource.Sample.Data.SoundDataSize,aSource.Sample.Data.Frequency,aSource.Sample.Data.NbChannels,MaxChannels,i);
if (p^.sample=0) then
begin
Raise EBZSoundBassManager.Create('Error initializing sample !' + LineEnding + GetErrorString(BASS_ErrorGetCode));
Exit;
end;
BASS_SampleSetData(p^.Sample, aSource.Sample.Data.SoundData);
p^.channel := BASS_SampleGetChannel(p^.sample, true);
BASS_SetConfig(BASS_CONFIG_SRC_SAMPLE,0);
//if (p^.sample=0) then ShowError('Error load sample source !');
//p^.sample := BASS_SampleLoad(True, aSource.Sample.Data.SoundData, 0, 0, MaxChannels, i);
//Assert(p^.sample<>0, 'BASS Error '+IntToStr(Integer(BASS_ErrorGetCode)));
aSource.ManagerTag := Integer(p);
// 1. Filtre Direct
if (aSource.DirectFilter<>'') and (aSource.DirectFilterActivated) then
begin
// Recuperation du filtre dans le cache dédié
FXItem := aSource.DirectFilterFX;
// Initialisation du filtre
//InitSoundFilter(FXItem);
// Mise à jour des parametres
//UpdateSoundFilterParams(FXItem);
// Liaison du filtre à la source
//LinkDirectFilterToSource(aSource);
end;
// 2. Initialisation des Slots si besoin
//InitSourceAuxSlots(aSource);
// 3. Assignation des effets et filtres dans chaque Slot
If aSource.AuxSlots.Count > 0 then
begin
if UseEnvironment then
begin
end;
end;
if aSource.Frequency<=0 then aSource.Frequency:=-1;
end;
end
else
begin
if aSource.ManagerTag<>0 then
begin
//GlobalLogger.LogNotice('UpdateSource - desactivate source');
p := PBZBASSInfo(aSource.ManagerTag);
if BASS_ChannelIsActive(p^.channel) <> BASS_ACTIVE_PLAYING then
begin
aSource.Pause := true; // On ne libere pas la ressource on met juste la lecture en pause
aSource.Playing := False;
If aSource.AutoFreeOnStop then
begin
p^.channel:=0;
aSource.Free;
Exit;
end;
end;
end;
end;
if (aSource.ManagerTag <> 0) then
begin
p := PBZBASSInfo(aSource.ManagerTag);
if (p^.channel=0) and (aSource.Sample.Data<>nil) then
begin
p^.channel := BASS_SampleGetChannel(p^.sample,false);
end;
if (sscSample in aSource.Changes) then
begin
if not(aSource.Pause) and (aSource.Playing) then
begin
BASS_ChannelPlay(p^.channel,true);
End;
aSource.Changes := aSource.Changes - [sscSample];
end;
if (sscStatus in aSource.changes) then
begin
//res := BASS_ChannelSetAttribute(p^.channel, BASS_ATTRIB_FREQ, 0);
//if Res<>BASS_OK then ShowError('Error ChannelSetAttribute - BASS_ATTRIB_FREQ');
if aSource.Mute then
res := BASS_ChannelSetAttribute(p^.channel, BASS_ATTRIB_VOL, 0)
else
res := BASS_ChannelSetAttribute(p^.channel, BASS_ATTRIB_VOL, aSource.Volume);
if not(Res) then
begin
Raise EBZSoundBassManager.Create('Error initializing channel attribute : VOLUME !' + LineEnding + GetErrorString(BASS_ErrorGetCode));
Exit;
end;
//res := BASS_ChannelSet3DAttributes(p^.channel, BASS_3DMODE_NORMAL,
// aSource.MinDistance, aSource.MaxDistance,
// Round(aSource.InsideConeAngle),
// Round(aSource.OutsideConeAngle),
// Round(aSource.ConeOutsideVolume*100));
//if not(Res) then ShowError('Error BASS_ChannelSet3DAttributes - BASS_3DMODE_NORMAL');
end;
// Pitch are not supported by Bass or it is BITRATE ???
aSource.Changes := aSource.Changes - [sscStatus];
end;
if (sscFXStatus in aSource.Changes) then
begin
if (sfxcDirectFilter in aSource.FXChanges) then
begin
//if ASource.DirectFilterActivated then LinkDirectFilterToSource(aSource)
//else UnLinkDirectFilterFromSource(aSource);
aSource.FXChanges := aSource.FXChanges - [sfxcDirectFilter];
end;
aSource.Changes := aSource.Changes - [sscFXStatus];
end;
// if (aSource.UseEnvironnment) and (smcEnvironnment in FChanges) then
//if sscTransformation in aSource.Changes then
//begin
//if aSource.Origin<>nil then
//begin
// objPos := aSource.Origin.AbsolutePosition;
// objOri := aSource.Origin.AbsoluteZVector;
// objVel := NullHmgVector;
//end
//else
//begin
// objPos := NullHmgPoint;
// objOri := ZHmgVector;
// objVel := NullHmgVector;
//end;
//VectorToBASSVector(objPos, position);
//VectorToBASSVector(objVel, velocity);
//VectorToBASSVector(objOri, orientation);
//res := BASS_ChannelSet3DPosition(p^.channel,position, orientation, velocity);
//if Res<>BASS_OK then ShowError('Error BASS_ChannelSet3DPosition');
//Source.Changes := aSource.Changes - [sscTransformation];
//end;
//end;
//else
// aSource.Free;
inherited UpdateSource(aSource);
end;
procedure TBZSoundBassManager.MuteSource(aSource : TBZBaseSoundSource; muted : Boolean);
var
p : PBZBASSInfo;
res : Boolean;
begin
if aSource.ManagerTag<>0 then
begin
p := PBZBASSInfo(aSource.ManagerTag);
if muted then res := BASS_ChannelSetAttribute(p^.channel, BASS_ATTRIB_VOL, 0)
else res := BASS_ChannelSetAttribute(p^.channel, BASS_ATTRIB_VOL, aSource.Volume);
Assert(res);
end;
end;
procedure TBZSoundBassManager.PauseSource(aSource : TBZBaseSoundSource; paused : Boolean);
var
p : PBZBASSInfo;
begin
if aSource.ManagerTag<>0 then
begin
GlobalLogger.LogNotice('UpdateSource - Pause sound');
p := PBZBASSInfo(aSource.ManagerTag);
if paused then BASS_ChannelPause(p^.channel)
else BASS_ChannelPlay(p^.channel,false);
end;
end;
procedure TBZSoundBassManager.PlaySource(aSource : TBZBaseSoundSource; playing : Boolean);
var
p : PBZBASSInfo;
begin
p := PBZBASSInfo(aSource.ManagerTag);
if not(playing) then
begin
if not(BASS_ChannelPlay(p^.channel,true)) then
begin
Raise EBZSoundBassManager.Create('Error while playing audio !' + LineEnding + GetErrorString(BASS_ErrorGetCode));
Exit;
end;
//aSource.Playing := True;
end
else
begin
//PauseSource(aSource,False);
BASS_ChannelStop(p^.channel);
//aSource.Playing := False;
aSource.Pause := False;
end;
end;
procedure TBZSoundBassManager.UpdateSources;
var
objPos, objVel, objDir, objUp : TBZVector;
position, velocity, fwd, top : BASS_3DVECTOR;
begin
//GlobalLogger.LogNotice('UpdateSources');
// update listener
ListenerCoordinates(objPos, objVel, objDir, objUp);
VectorToBASSVector(objPos, position);
VectorToBASSVector(objVel, velocity);
VectorToBASSVector(objDir, fwd);
VectorToBASSVector(objUp, top);
if not BASS_Set3DPosition(position, velocity, fwd, top) then
begin
Raise EBZSoundBassManager.Create('Error initializing 3D position !' + LineEnding + GetErrorString(BASS_ErrorGetCode));
Exit;
end;
// update sources
inherited UpdateSources;
BASS_Apply3D;
end;
function TBZSoundBassManager.CPUUsagePercent : Single;
begin
Result := BASS_GetCPU*100;
end;
function TBZSoundBassManager.EAXSupported : Boolean;
var
c : Cardinal;
s : Single;
begin
{$IFDEF WINDOWS}
Result := BASS_GetEAXParameters(c, s, s, s);
{$ELSE}
Result := False;
{$ENDIF}
end;
function TBZSoundBassManager.GetInformations : String;
var
s : string;
n : Integer;
DeviceInfo : BASS_DEVICEINFO;
BassInfos : BASS_INFO;
function getDeviceTypeInfo(di : BASS_DEVICEINFO) : String;
var
St : String;
begin
case (di.flags and BASS_DEVICE_TYPE_MASK) of
BASS_DEVICE_TYPE_NETWORK :
St := 'Remote Network';
BASS_DEVICE_TYPE_SPEAKERS :
St := 'Speakers';
BASS_DEVICE_TYPE_LINE :
St := 'Line';
BASS_DEVICE_TYPE_HEADPHONES :
St := 'Headphones';
BASS_DEVICE_TYPE_MICROPHONE :
St := 'Microphone';
BASS_DEVICE_TYPE_HEADSET :
St := 'Headset';
BASS_DEVICE_TYPE_HANDSET :
St := 'Handset';
BASS_DEVICE_TYPE_DIGITAL :
St := 'Digital';
BASS_DEVICE_TYPE_SPDIF :
St := 'SPDIF';
BASS_DEVICE_TYPE_HDMI :
St := 'HDMI';
BASS_DEVICE_TYPE_DISPLAYPORT :
St := 'DisplayPort';
else
St := 'Unknown';
end;
Result := St;
//St := St + 'flags:';
//if (di.flags and BASS_DEVICE_LOOPBACK) = BASS_DEVICE_LOOPBACK then
// St := St + ' loopback';
//if (di.flags and BASS_DEVICE_ENABLED) = BASS_DEVICE_ENABLED then
// St := St + ' enabled';
//if (di.flags and BASS_DEVICE_DEFAULT) = BASS_DEVICE_DEFAULT then
// St := St + ' default';
//WriteLn(St, ' (', di.flags, ')');
end;
begin
S := 'BASS Version : ' + BASSVERSIONTEXT + LineEnding + LineEnding;
S := S + '--------------------------------------------------------------------' + LineEnding;
S := S + 'Output devices : ' + LineEnding;
n := 1;
While BASS_GetDeviceInfo(n, DeviceInfo) do
begin
S := S + ' - ' + n.ToString + ' : ' + AnsiToUTF8(DeviceInfo.name) + LineEnding;
S := S + ' Driver : ' + DeviceInfo.driver + LineEnding;
S := S + ' Type : ' + getDeviceTypeInfo(DeviceInfo) + LineEnding;
S := S + LineEnding;
inc(n);
end;
S := S + 'Input devices : ' + LineEnding;
n := 0;
While BASS_RecordGetDeviceInfo(n, DeviceInfo) do
begin
S := S + ' - ' + n.ToString + ' : ' + AnsiToUTF8(DeviceInfo.name) + LineEnding;
S := S + ' Driver : ' + DeviceInfo.driver + LineEnding;
S := S + ' Type : ' + getDeviceTypeInfo(DeviceInfo) + LineEnding;
S := S + LineEnding;
inc(n);
end;
S := S + '--------------------------------------------------------------------' + LineEnding + LineEnding;
BASS_GetInfo(BassInfos);
S := S + ' Number of speaker : ' + BassInfos.speakers.ToString + LineEnding;
S := S + ' EAX Supported : ' + BassInfos.eax.ToString() + LineEnding;
S := S + ' Total HW Memory : ' + (BassInfos.hwsize / 1024).ToString + 'Ko' + LineEnding;
S := S + ' Free HW Memory : ' + (BassInfos.hwfree / 1024).ToString + 'Ko' + LineEnding;
S := S + ' Min Rate : ' + BassInfos.minrate.ToString + LineEnding;
S := S + ' Max Rate : ' + BassInfos.maxrate.ToString + LineEnding;
S := S + ' Free HW Memory : ' + (BassInfos.hwfree / 1024).ToString + 'Ko' + LineEnding;
S := S + ' Free sample slot : ' + BassInfos.freesam.ToString + LineEnding;
S := S + ' Current frequency : ' + BassInfos.freq.ToString + ' Mhz' + LineEnding;
S := S + ' Latency : ' + BassInfos.latency.ToString + ' ms' + LineEnding;
Result := S;
end;
function TBZSoundBassManager.GetDefaultFrequency(aSource : TBZBaseSoundSource) : Integer;
var
p : PBZBASSInfo;
sampleInfo : BASS_Sample;
begin
try
p := PBZBASSInfo(aSource.ManagerTag);
BASS_SampleGetInfo(p^.sample, sampleInfo);
Result := sampleInfo.freq;
except
Result:=-1;
end;
end;
function TBZSoundBassManager.GetTimePosition(aSource : TBZBaseSoundSource) : Single;
var
p : PBZBASSInfo;
begin
Result := 0.0;
if (aSource.ManagerTag<>0) then
begin
p := PBZBASSInfo(aSource.ManagerTag);
Result := BASS_ChannelGetPosition(p^.channel,BASS_POS_BYTE) / aSource.Sample.Data.BytesPerSec;
end;
end;
end.
|
unit frmMemviewPreferencesUnit;
{$mode delphi}
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
StdCtrls, Menus, ExtCtrls, disassemblerviewunit, disassemblerviewlinesunit,
LCLIntf, LCLType,
{$ifdef darwin}
macport, math
{$endif}
{$ifdef windows}
windows, betterControls
{$endif};
type
{ TfrmMemviewPreferences }
TfrmMemviewPreferences = class(TForm)
btnFont: TButton;
btnHexFont: TButton;
btnRegisterViewFont: TButton;
Button2: TButton;
Button3: TButton;
cbColorGroup: TComboBox;
cbShowStatusBar: TCheckBox;
cbOriginalRenderingSystem: TCheckBox;
cbCenterDisassemblerWhenOutsideView: TCheckBox;
ColorDialog1: TColorDialog;
cbFontQuality: TComboBox;
edtSpaceAboveLines: TEdit;
edtSpaceBelowLines: TEdit;
edtHexSpaceBetweenLines: TEdit;
edtJLThickness: TEdit;
edtJLSpacing: TEdit;
FontDialog1: TFontDialog;
FontDialog2: TFontDialog;
FontDialog3: TFontDialog;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
GroupBox4: TGroupBox;
GroupBox5: TGroupBox;
GroupBox6: TGroupBox;
GroupBox7: TGroupBox;
Label1: TLabel;
lblHexFadecolor: TLabel;
lblRegHighLightAccess: TLabel;
lblRegHighLightChange: TLabel;
lblHexCursor: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
lblHexBreakpoint: TLabel;
lblHexDifferent: TLabel;
lblHexEditing: TLabel;
lblHexHighlighted: TLabel;
lblHexNormal: TLabel;
lblHexSecondaryEditing: TLabel;
lblHexTopLine: TLabel;
lblHexSeperator: TLabel;
lblConditionalJump: TLabel;
lblHexStatic: TLabel;
lblUnconditionalJump: TLabel;
lblCall: TLabel;
lblHex: TLabel;
lblNormal: TLabel;
lblRegister: TLabel;
lblSymbol: TLabel;
miRestoreToDefaults: TMenuItem;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
Panel5: TPanel;
pmColors: TPopupMenu;
procedure btnFontClick(Sender: TObject);
procedure btnRegisterViewFontClick(Sender: TObject);
procedure btnHexFontClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure cbColorGroupChange(Sender: TObject);
procedure cbFontQualitySelect(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure gbHexBackgroundMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure GroupBox1Click(Sender: TObject);
procedure GroupBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure GroupBox3Click(Sender: TObject);
procedure GroupBox5Click(Sender: TObject);
procedure lblHexFadecolorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure lblCallClick(Sender: TObject);
procedure lblConditionalJumpClick(Sender: TObject);
procedure lblHexClick(Sender: TObject);
procedure lblHexDefaultColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure lblHexHighlightColorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure lblHexMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure lblHexGraphicalColor(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure lblNormalClick(Sender: TObject);
procedure lblRegHighLightMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure lblRegisterClick(Sender: TObject);
procedure lblHexSeperatorColorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure lblHexStaticColorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure lblSymbolClick(Sender: TObject);
procedure lblUnconditionalJumpClick(Sender: TObject);
procedure miRestoreToDefaultsClick(Sender: TObject);
procedure Shape1ChangeBounds(Sender: TObject);
private
{ private declarations }
oldstate: TDisassemblerViewColorsState;
fspaceAboveLines: integer;
fspaceBelowLines: integer;
fhexspaceBetweenLines: integer;
fjlThickness: integer;
fjlSpacing: integer;
procedure setHexSpaceBetweenLines(s: integer);
procedure setSpaceAboveLines(s: integer);
procedure setSpaceBelowLines(s: integer);
procedure setjlThickness(t: integer);
procedure setjlSpacing(s: integer);
procedure applyfont;
public
{ public declarations }
colors: TDisassemblerViewColors;
property hexSpaceBetweenLines: integer read fhexspaceBetweenLines write setHexSpaceBetweenLines;
property spaceAboveLines: integer read fspaceAboveLines write setSpaceAboveLines;
property spaceBelowLines: integer read fspaceBelowLines write setSpaceBelowLines;
property jlThickness: integer read fjlThickness write setjlThickness;
property jlSpacing: integer read fjlSpacing write setjlSpacing;
end;
implementation
{ TfrmMemviewPreferences }
uses MemoryBrowserFormUnit;
resourcestring
rsBackgroundColor = 'Background color';
rsHexadecimalColor = 'Hexadecimal color';
rsNormalColor = 'Normal color';
rsRegisterColor = 'Register color';
rsSymbolColor = 'Symbol color';
rsConditionalJumpColor = 'Conditional jump color';
rsUnconditionalJumpColor = 'Unconditional jump color';
rsCallColor = 'Call color';
rsDCNormal='Normal';
rsDCHighlighted='Highlighted';
rsDCHighlightedSecondary='Highlighted secondary';
rsDCBreakpoint='Breakpoint';
rsDCHighlightedBreakpoint='Highlighted breakpoint';
rsDCHighlightedBreakpointSecondary='Highlighted breakpoint secondary';
rsDCUltimap2='Ultimap2';
rsDCHighlightedUltimap2='Highlighted Ultimap2';
rsDCHighlightedUltimap2Secondary='Highlighted Ultimap2 secondary';
rsHexedit='Hexedit';
procedure TfrmMemviewPreferences.setHexSpaceBetweenLines(s: integer);
begin
edtHexSpaceBetweenLines.text:=inttostr(s);
fhexspaceBetweenLines:=s;
end;
procedure TfrmMemviewPreferences.setSpaceAboveLines(s: integer);
begin
edtSpaceAboveLines.text:=inttostr(s);
fspaceAboveLines:=s;
end;
procedure TfrmMemviewPreferences.setSpaceBelowLines(s: integer);
begin
edtSpaceBelowLines.text:=inttostr(s);
fspaceBelowLines:=s;
end;
procedure TfrmMemviewPreferences.setjlThickness(t: integer);
begin
edtJLThickness.text:=inttostr(t);
fjlThickness:=t;
end;
procedure TfrmMemviewPreferences.setjlSpacing(s: integer);
begin
edtJLSpacing.text:=inttostr(s);
fjlThickness:=s;
end;
procedure TfrmMemviewPreferences.applyfont;
var oldcolor: TColor;
begin
cbColorGroupChange(cbColorGroup); //save the current colors
lblNormal.font:=fontdialog1.Font;
lblRegister.font:=fontdialog1.Font;
lblSymbol.font:=fontdialog1.Font;
lblHex.font:=FontDialog1.font;
oldcolor:=lblHexnormal.Font.color;
lblHexNormal.Font.assign(fontdialog2.font);
lblHexNormal.Font.color:=oldcolor;
oldcolor:=lblHexStatic.Font.color;
lblHexStatic.Font.assign(fontdialog2.font);
lblHexStatic.Font.color:=oldcolor;
oldcolor:=lblHexHighlighted.Font.color;
lblHexHighlighted.Font.assign(fontdialog2.font);
lblHexHighlighted.Font.color:=oldcolor;
oldcolor:=lblHexEditing.Font.color;
lblHexEditing.Font.assign(fontdialog2.font);
lblHexEditing.Font.color:=oldcolor;
oldcolor:=lblHexSecondaryEditing.Font.color;
lblHexSecondaryEditing.Font.assign(fontdialog2.font);
lblHexSecondaryEditing.Font.color:=oldcolor;
oldcolor:=lblHexBreakpoint.Font.color;
lblHexBreakpoint.Font.assign(fontdialog2.font);
lblHexBreakpoint.Font.color:=oldcolor;
oldcolor:=lblHexDifferent.Font.color;
lblHexDifferent.Font.assign(fontdialog2.font);
lblHexDifferent.Font.color:=oldcolor;
lblRegHighLightAccess.Font:=FontDialog3.font;
lblRegHighLightChange.font:=FontDialog3.font;
oldstate:=csUndefined;
cbColorGroupChange(cbColorGroup); //restore the colors
DoAutoSize;
end;
procedure TfrmMemviewPreferences.FormCreate(Sender: TObject);
begin
oldstate:=csUndefined;
cbColorGroup.Items.Clear;
cbColorGroup.Items.Add(rsDCNormal);
cbColorGroup.Items.Add(rsDCHighlighted);
cbColorGroup.Items.Add(rsDCHighlightedSecondary);
cbColorGroup.Items.Add(rsDCBreakpoint);
cbColorGroup.Items.Add(rsDCHighlightedBreakpoint);
cbColorGroup.Items.Add(rsDCHighlightedBreakpointSecondary);
cbColorGroup.Items.Add(rsDCUltimap2);
cbColorGroup.Items.Add(rsDCHighlightedUltimap2);
cbColorGroup.Items.Add(rsDCHighlightedUltimap2Secondary);
{$ifdef USELAZFREETYPE}
cbOriginalRenderingSystem.Visible:=true;
{$endif}
end;
procedure TfrmMemviewPreferences.FormShow(Sender: TObject);
var
i: integer;
extrasize: integer;
{$ifdef windows}
cbi: TComboboxInfo;
{$endif}
begin
applyfont;
oldstate:=csUndefined;
cbColorGroup.itemindex:=0;
cbColorGroupChange(cbColorGroup);
//
{$ifdef windows}
cbi.cbSize:=sizeof(cbi);
if GetComboBoxInfo(cbColorGroup.handle, @cbi) then
extrasize:=cbi.rcButton.Right-cbi.rcButton.Left+cbi.rcItem.Left
else
{$endif}
extrasize:=16;
i:=Canvas.TextWidth(rsDCNormal)+extrasize;
i:=max(i, Canvas.TextWidth(rsDCHighlighted)+extrasize);
i:=max(i, Canvas.TextWidth(rsDCHighlightedSecondary)+extrasize);
i:=max(i, Canvas.TextWidth(rsDCBreakpoint)+extrasize);
i:=max(i, Canvas.TextWidth(rsDCHighlightedBreakpoint)+extrasize);
i:=max(i, Canvas.TextWidth(rsDCHighlightedBreakpointSecondary)+extrasize);
i:=max(i, Canvas.TextWidth(rsDCUltimap2)+extrasize);
i:=max(i, Canvas.TextWidth(rsDCHighlightedUltimap2)+extrasize);
i:=max(i, Canvas.TextWidth(rsDCHighlightedUltimap2Secondary)+extrasize);
btnFont.Constraints.MinWidth:=i;
cbColorGroup.Constraints.MinWidth:=i;
btnHexFont.Constraints.MinWidth:=i;
end;
procedure TfrmMemviewPreferences.gbHexBackgroundMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
end;
procedure TfrmMemviewPreferences.GroupBox1Click(Sender: TObject);
begin
colordialog1.Color:=groupbox1.color;
colordialog1.Title:=rsBackgroundColor;
if colordialog1.execute then
groupbox1.color:=colordialog1.Color;
end;
procedure TfrmMemviewPreferences.GroupBox1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
groupbox1.OnClick(sender);
end;
procedure TfrmMemviewPreferences.GroupBox3Click(Sender: TObject);
begin
end;
procedure TfrmMemviewPreferences.GroupBox5Click(Sender: TObject);
begin
end;
procedure TfrmMemviewPreferences.lblHexFadecolorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var l: TLabel;
begin
l:=tlabel(sender);
colordialog1.Title:=rsHexedit+' '+l.caption;
colordialog1.color:=l.color;
if colordialog1.execute then
l.color:=colordialog1.color;
end;
procedure TfrmMemviewPreferences.lblCallClick(Sender: TObject);
begin
colordialog1.Color:=lblCall.font.color;
colordialog1.Title:=rsCallColor;
if colordialog1.execute then
lblCall.font.color:=colordialog1.Color;
end;
procedure TfrmMemviewPreferences.lblConditionalJumpClick(Sender: TObject);
begin
colordialog1.Color:=lblConditionalJump.font.color;
colordialog1.Title:=rsConditionalJumpColor;
if colordialog1.execute then
lblConditionalJump.font.color:=colordialog1.Color;
end;
procedure TfrmMemviewPreferences.lblHexClick(Sender: TObject);
begin
colordialog1.Color:=lblHex.font.color;
colordialog1.Title:=rsHexadecimalColor;
if colordialog1.execute then
lblHex.font.color:=colordialog1.Color;
end;
procedure TfrmMemviewPreferences.lblHexDefaultColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
end;
procedure TfrmMemviewPreferences.lblHexHighlightColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
end;
procedure TfrmMemviewPreferences.lblHexMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var l: TLabel;
begin
l:=tlabel(sender);
colordialog1.Title:=rsHexedit+' '+l.caption;
if button=mbLeft then //font
colordialog1.Color:=l.font.color
else //background
colordialog1.Color:=l.color;
if colordialog1.execute then
begin
if button=mbLeft then
l.font.color:=colordialog1.color
else
l.color:=colordialog1.color;
end;
end;
procedure TfrmMemviewPreferences.lblHexGraphicalColor(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var l: TLabel;
begin
l:=tlabel(sender);
colordialog1.Title:=rsHexedit+' '+l.caption;
colordialog1.color:=l.font.color;
if colordialog1.execute then
l.font.color:=colordialog1.color;
end;
procedure TfrmMemviewPreferences.lblNormalClick(Sender: TObject);
begin
colordialog1.Color:=lblNormal.font.color;
colordialog1.Title:=rsNormalColor;
if colordialog1.execute then
lblNormal.font.color:=colordialog1.Color;
end;
procedure TfrmMemviewPreferences.lblRegHighLightMouseDown(
Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var l: TLabel;
begin
l:=tlabel(sender);
colordialog1.Title:=rsHexedit+' '+l.caption;
colordialog1.color:=l.color;
if colordialog1.execute then
l.color:=colordialog1.color;
end;
procedure TfrmMemviewPreferences.lblRegisterClick(Sender: TObject);
begin
colordialog1.Color:=lblRegister.font.color;
colordialog1.Title:=rsRegisterColor;
if colordialog1.execute then
lblRegister.font.color:=colordialog1.Color;
end;
procedure TfrmMemviewPreferences.lblHexSeperatorColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
end;
procedure TfrmMemviewPreferences.lblHexStaticColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
end;
procedure TfrmMemviewPreferences.lblSymbolClick(Sender: TObject);
begin
colordialog1.Color:=lblSymbol.font.color;
colordialog1.Title:=rsSymbolColor;
if colordialog1.execute then
lblSymbol.font.color:=colordialog1.Color;
end;
procedure TfrmMemviewPreferences.lblUnconditionalJumpClick(Sender: TObject);
begin
colordialog1.Color:=lblunConditionalJump.font.color;
colordialog1.Title:=rsunConditionalJumpColor;
if colordialog1.execute then
lblunConditionalJump.font.color:=colordialog1.Color;
end;
procedure TfrmMemviewPreferences.miRestoreToDefaultsClick(Sender: TObject);
begin
//restore to defaults
MemoryBrowser.disassemblerview.getDefaultColors(colors);
groupbox1.Color:=colors[oldstate].backgroundcolor;
lblnormal.font.color:=colors[oldstate].normalcolor;
lblRegister.font.color:=colors[oldstate].registercolor;
lblSymbol.font.color:=colors[oldstate].symbolcolor;
lblHex.Font.color:=colors[oldstate].hexcolor;
fontdialog1.Font.Name:=MemoryBrowser.Font.name; //parent fontname and size
fontdialog1.font.Size:=MemoryBrowser.Font.size;
btnFont.Caption:=fontdialog1.Font.Name+' '+inttostr(fontdialog1.Font.Size);
fontdialog1.font.Charset:=DEFAULT_CHARSET;
fontdialog1.font.Color:=clwindowText;
fontdialog2.font.Size:=10;
fontdialog1.font.Name:='MS Sans Serif';
fontdialog1.font.Style:=[];
fontdialog2.font.Charset:=DEFAULT_CHARSET;
fontdialog2.font.Color:=clwindowText;
fontdialog2.font.Height:=-11;
fontdialog2.font.Size:=10;
fontdialog2.font.Name:='Courier New';
fontdialog2.font.Style:=[];
applyfont;
oldstate:=csUndefined;
cbColorGroupChange(cbColorGroup);
end;
procedure TfrmMemviewPreferences.Shape1ChangeBounds(Sender: TObject);
begin
end;
procedure TfrmMemviewPreferences.btnFontClick(Sender: TObject);
var s: string;
f:tfont;
fd: TFontData;
begin
fd:=Graphics.GetFontData(lblNormal.Font.Handle);
fd.Handle:=fontdialog1.Font.Handle;
fontdialog1.Font.FontData:=fd;
if fontdialog1.execute then
begin
btnFont.Caption:=fontdialog1.Font.Name+' '+inttostr(fontdialog1.Font.Size);
oldstate:=csUndefined;
applyfont;
cbColorGroupChange(cbColorGroup);
end;
end;
procedure TfrmMemviewPreferences.btnRegisterViewFontClick(Sender: TObject);
begin
if fontdialog3.execute then
begin
btnRegisterViewFont.Caption:=fontdialog3.Font.Name+' '+inttostr(fontdialog3.Font.Size);
applyfont;
end;
end;
procedure TfrmMemviewPreferences.btnHexFontClick(Sender: TObject);
var fd: TFontData;
begin
if fontdialog2.execute then
begin
btnHexFont.Caption:=fontdialog2.Font.Name+' '+inttostr(fontdialog2.Font.Size);
applyfont;
end;
end;
procedure TfrmMemviewPreferences.Button2Click(Sender: TObject);
begin
fhexspaceBetweenLines:=strtoint(edtHexSpaceBetweenLines.Text);
fspaceAboveLines:=strtoint(edtSpaceAboveLines.Text);
fspaceBelowLines:=strtoint(edtSpaceBelowLines.Text);
fjlThickness:=strtoint(edtJLThickness.Text);
fjlSpacing:=strtoint(edtJLSpacing.Text);
fhexSpaceBetweenLines:=strtoint(edtHexSpaceBetweenLines.text);
cbColorGroupChange(cbColorGroup); //apply changes of the current page first
modalresult:=mrok;
end;
procedure TfrmMemviewPreferences.cbColorGroupChange(Sender: TObject);
begin
//store the current state into oldstate
if oldstate<>csUndefined then
begin
colors[oldstate].backgroundcolor:=groupbox1.Color;
colors[oldstate].normalcolor:=lblnormal.Font.color;
colors[oldstate].registercolor:=lblRegister.Font.color;
colors[oldstate].symbolcolor:=lblSymbol.font.color;
colors[oldstate].hexcolor:=lblHex.font.color;
end;
//load the new state
oldstate:=TDisassemblerViewColorsState(cbColorGroup.ItemIndex);
if oldstate<>csUndefined then
begin
groupbox1.Color:=colors[oldstate].backgroundcolor;
lblnormal.font.color:=colors[oldstate].normalcolor;
lblRegister.font.color:=colors[oldstate].registercolor;
lblSymbol.font.color:=colors[oldstate].symbolcolor;
lblHex.Font.color:=colors[oldstate].hexcolor;
end;
end;
procedure TfrmMemviewPreferences.cbFontQualitySelect(Sender: TObject);
begin
if cbFontQuality.ItemIndex<>-1 then
begin
fontdialog2.Font.quality:=TFontQuality(cbFontQuality.ItemIndex);
applyfont;
end;
end;
initialization
{$I frmMemviewPreferencesUnit.lrs}
end.
|
unit UPedidoRepositoryImpl;
interface
uses
UPedidoRepositoryIntf, UPizzaTamanhoEnum, UPizzaSaborEnum, UDBConnectionIntf,
FireDAC.Comp.Client, UPedidoRetornoDTOImpl;
type
TPedidoRepository = class(TInterfacedObject, IPedidoRepository)
private
FDBConnection: IDBConnection;
FFDQuery: TFDQuery;
public
procedure efetuarPedido(const APizzaTamanho: TPizzaTamanhoEnum;
const APizzaSabor: TPizzaSaborEnum; const AValorPedido: Currency;
const ATempoPreparo: Integer; const ACodigoCliente: Integer);
function consultarPedido(const ADocumentoCliente: string)
: TpedidoRetornoDTO;
constructor Create; reintroduce;
destructor Destroy; override;
end;
implementation
uses
UDBConnectionImpl, System.SysUtils, Data.DB, FireDAC.Stan.Param, System.Rtti;
const
CMD_INSERT_PEDIDO
: String =
'INSERT INTO tb_pedido (cd_cliente, dt_pedido, dt_entrega, vl_pedido, nr_tempopedido, sabor, tamanho) VALUES (:pCodigoCliente, :pDataPedido, :pDataEntrega, :pValorPedido, :pTempoPedido, :pSabor, :pTamanho)';
CMD_CONSULTAR_PEDIDO:
String ='select tb_pedido.cd_cliente, tb_pedido.dt_pedido, tb_pedido.nr_tempopedido,' +
' tb_pedido.vl_pedido, tb_pedido.te_sabor, tb_pedido.te_tamanho from tb_pedido' +
' join tb_cliente on tb_cliente.id = tb_pedido.cd_cliente' +
' where tb_cliente.nr_documento = :doc' +
' limit 1';
{ TPedidoRepository }
function TPedidoRepository.consultarPedido(
const ADocumentoCliente: string): TpedidoRetornoDTO;
begin
FFDQuery.SQL.Text := CMD_CONSULTAR_PEDIDO;
FFDQuery.ParamByName('PNR_DOCUMENTO').AsString := ADocumentoCliente;
FFDQuery.Open();
if (FFDQuery.RecordCount = 0) then
raise Exception.Create('Não foram encontrados pedidos para este cliente.');
Result := TPedidoRetornoDTO.Create(
TRttiEnumerationType.GetValue<TPizzaTamanhoEnum>(FFDQuery.FieldByName('TE_TAMANHO').AsString),
TRttiEnumerationType.GetValue<TPizzaSaborEnum>(FFDQuery.FieldByName('te_sabor').AsString),
FFDQuery.FieldByName('VL_PEDIDO').AsFloat,
FFDQuery.FieldByName('NR_TEMPOPEDIDO').AsInteger)
end;
constructor TPedidoRepository.Create;
begin
inherited;
FDBConnection := TDBConnection.Create;
FFDQuery := TFDQuery.Create(nil);
FFDQuery.Connection := FDBConnection.getDefaultConnection;
end;
destructor TPedidoRepository.Destroy;
begin
FFDQuery.Free;
inherited;
end;
procedure TPedidoRepository.efetuarPedido(const APizzaTamanho
: TPizzaTamanhoEnum; const APizzaSabor: TPizzaSaborEnum;
const AValorPedido: Currency; const ATempoPreparo: Integer;
const ACodigoCliente: Integer);
begin
FFDQuery.SQL.Text := CMD_INSERT_PEDIDO;
FFDQuery.ParamByName('pCodigoCliente').AsInteger := ACodigoCliente;
FFDQuery.ParamByName('pDataPedido').AsDateTime := now();
FFDQuery.ParamByName('pDataEntrega').AsDateTime := now();
FFDQuery.ParamByName('pValorPedido').AsCurrency := AValorPedido;
FFDQuery.ParamByName('pTempoPedido').AsInteger := ATempoPreparo;
FFDQuery.ParamByName('pSabor').AsString:= TRttiEnumerationType.GetName<TPizzaSaborEnum>(APizzaSabor);
FFDQuery.ParamByName('pTamanho').AsString:= TRttiEnumerationType.GetName<TPizzaTamanhoEnum>(APizzaTamanho);
FFDQuery.Prepare;
FFDQuery.ExecSQL(True);
end;
end.
|
unit UnitChunkStream; // Copyright (C) 2006-2017, Benjamin Rosseaux - License: zlib
{$ifdef fpc}
{$mode delphi}
{$ifdef cpui386}
{$define cpu386}
{$endif}
{$ifdef cpu386}
{$asmmode intel}
{$endif}
{$ifdef cpuamd64}
{$asmmode intel}
{$endif}
{$ifdef fpc_little_endian}
{$define little_endian}
{$else}
{$ifdef fpc_big_endian}
{$define big_endian}
{$endif}
{$endif}
{$ifdef fpc_has_internal_sar}
{$define HasSAR}
{$endif}
{-$pic off}
{$define caninline}
{$ifdef FPC_HAS_TYPE_EXTENDED}
{$define HAS_TYPE_EXTENDED}
{$else}
{$undef HAS_TYPE_EXTENDED}
{$endif}
{$ifdef FPC_HAS_TYPE_DOUBLE}
{$define HAS_TYPE_DOUBLE}
{$else}
{$undef HAS_TYPE_DOUBLE}
{$endif}
{$ifdef FPC_HAS_TYPE_SINGLE}
{$define HAS_TYPE_SINGLE}
{$else}
{$undef HAS_TYPE_SINGLE}
{$endif}
{$else}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$realcompatibility off}
{$localsymbols on}
{$define little_endian}
{$ifndef cpu64}
{$define cpu32}
{$endif}
{$define delphi}
{$undef HasSAR}
{$define UseDIV}
{$define HAS_TYPE_EXTENDED}
{$define HAS_TYPE_DOUBLE}
{$define HAS_TYPE_SINGLE}
{$endif}
{$ifdef cpu386}
{$define cpux86}
{$endif}
{$ifdef cpuamd64}
{$define cpux86}
{$endif}
{$ifdef win32}
{$define windows}
{$endif}
{$ifdef win64}
{$define windows}
{$endif}
{$ifdef wince}
{$define windows}
{$endif}
{$ifdef windows}
{$define win}
{$endif}
{$ifdef sdl20}
{$define sdl}
{$endif}
{$rangechecks off}
{$extendedsyntax on}
{$writeableconst on}
{$hints off}
{$booleval off}
{$typedaddress off}
{$stackframes off}
{$varstringchecks on}
{$typeinfo on}
{$overflowchecks off}
{$longstrings on}
{$openstrings on}
{$ifndef HAS_TYPE_DOUBLE}
{$error No double floating point precision}
{$endif}
{$ifdef fpc}
{$define caninline}
{$else}
{$undef caninline}
{$ifdef ver180}
{$define caninline}
{$else}
{$ifdef conditionalexpressions}
{$if compilerversion>=18}
{$define caninline}
{$ifend}
{$endif}
{$endif}
{$endif}
interface
uses SysUtils,Classes;
type PChunkSignature=^TChunkSignature;
TChunkSignature=array[0..3] of ansichar;
PChunk=^TChunk;
TChunk=packed record
Signature:TChunkSignature;
Offset:longint;
Size:longint;
Reserved:longword;
end;
TChunks=array of TChunk;
EChunkStream=class(Exception);
TChunkStream=class(TStream)
private
fStream:TStream;
fOffset:int64;
fSize:int64;
fPosition:int64;
fMemory:boolean;
public
constructor Create(const AStream:TStream;const AOffset,ASize:int64;const AMemory:boolean=true);
destructor Destroy; override;
function Read(var Buffer;Count:longint):longint; override;
function Write(const Buffer;Count:longint):longint; override;
function Seek(Offset:longint;Origin:word):longint; override;
function Seek(const Offset:int64;Origin:TSeekOrigin):int64; override;
procedure SetSize(NewSize:longint); override;
procedure SetSize(const NewSize:int64); override;
function ReadWithCheck(var Buffer;Count:longint):longint;
function ReadString:ansistring;
function ReadByte:byte;
function ReadInt32:longint;
function ReadUInt32:longword;
function ReadFloat:single;
end;
implementation
constructor TChunkStream.Create(const AStream:TStream;const AOffset,ASize:int64;const AMemory:boolean=true);
begin
inherited Create;
if (not assigned(AStream)) or ((AOffset<0) or ((AOffset+ASize)>AStream.Size)) then begin
raise EChunkStream.Create('Stream slice error');
end;
fPosition:=0;
fMemory:=AMemory;
if fMemory then begin
fStream:=TMemoryStream.Create;
fOffset:=0;
fSize:=ASize;
if AStream.Seek(AOffset,soBeginning)<>AOffset then begin
raise EChunkStream.Create('Stream seek error');
end;
if fStream.CopyFrom(AStream,ASize)<>ASize then begin
raise EChunkStream.Create('Stream copy error');
end;
if fStream.Seek(0,soBeginning)<>fOffset then begin
raise EChunkStream.Create('Stream seek error');
end;
end else begin
fStream:=AStream;
fOffset:=AOffset;
fSize:=ASize;
end;
end;
destructor TChunkStream.Destroy;
begin
if fMemory then begin
fStream.Free;
end;
inherited Destroy;
end;
function TChunkStream.Read(var Buffer;Count:longint):longint;
begin
if (fPosition+Count)>fSize then begin
Count:=fSize-fPosition;
end;
if Count>0 then begin
if fStream.Position<>(fOffset+fPosition) then begin
if fStream.Seek(fOffset+fPosition,soBeginning)<>(fOffset+fPosition) then begin
raise EChunkStream.Create('Stream seek error');
end;
end;
result:=fStream.Read(Buffer,Count);
inc(fPosition,result);
end else begin
result:=0;
end;
end;
function TChunkStream.Write(const Buffer;Count:longint):longint;
begin
if (fPosition+Count)>fSize then begin
Count:=fSize-fPosition;
end;
if Count>0 then begin
if fStream.Position<>(fOffset+fPosition) then begin
if fStream.Seek(fOffset+fPosition,soBeginning)<>(fOffset+fPosition) then begin
raise EChunkStream.Create('Stream seek error');
end;
end;
result:=fStream.Write(Buffer,Count);
inc(fPosition,result);
end else begin
result:=0;
end;
end;
function TChunkStream.Seek(Offset:longint;Origin:word):longint;
begin
case Origin of
soFromBeginning:begin
fPosition:=Offset;
end;
soFromCurrent:begin
inc(fPosition,Offset);
end;
soFromEnd:begin
fPosition:=fSize+Offset;
end;
end;
if (fPosition<0) or (fPosition>fSize) then begin
raise EChunkStream.Create('Stream seek error');
end;
result:=fPosition;
end;
function TChunkStream.Seek(const Offset:int64;Origin:TSeekOrigin):int64;
begin
case Origin of
soBeginning:begin
fPosition:=Offset;
end;
soCurrent:begin
inc(fPosition,Offset);
end;
soEnd:begin
fPosition:=fSize+Offset;
end;
end;
if (fPosition<0) or (fPosition>fSize) then begin
raise EChunkStream.Create('Stream seek error');
end;
result:=fPosition;
end;
procedure TChunkStream.SetSize(NewSize:longint);
begin
if fSize<>NewSize then begin
raise EChunkStream.Create('Stream set size error');
end;
end;
procedure TChunkStream.SetSize(const NewSize:int64);
begin
if fSize<>NewSize then begin
raise EChunkStream.Create('Stream set size error');
end;
end;
function TChunkStream.ReadWithCheck(var Buffer;Count:longint):longint;
begin
result:=Read(Buffer,Count);
if result<>Count then begin
raise EChunkStream.Create('Stream read error');
end;
end;
function TChunkStream.ReadString:ansistring;
var Len:longint;
begin
ReadWithCheck(Len,SizeOf(longint));
SetLength(result,Len);
if Len>0 then begin
ReadWithCheck(result[1],Len*SizeOf(AnsiChar));
end;
end;
function TChunkStream.ReadByte:byte;
begin
ReadWithCheck(result,SizeOf(byte));
end;
function TChunkStream.ReadInt32:longint;
begin
ReadWithCheck(result,SizeOf(longint));
end;
function TChunkStream.ReadUInt32:longword;
begin
ReadWithCheck(result,SizeOf(longword));
end;
function TChunkStream.ReadFloat:single;
begin
ReadWithCheck(result,SizeOf(single));
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.