{ =============================================================================== Copyright (©) 2007. Rodax Software. =============================================================================== Los contenidos de este fichero son propiedad de Rodax Software titular del copyright. Este fichero sólo podrá ser copiado, distribuido y utilizado, en su totalidad o en parte, con el permiso escrito de Rodax Software, o de acuerdo con los términos y condiciones establecidas en el acuerdo/contrato bajo el que se suministra. ----------------------------------------------------------------------------- Web: www.rodax-software.com =============================================================================== Fecha primera versión: Versión actual: 1.0.0 Fecha versión actual: =============================================================================== Modificaciones: Fecha Comentarios --------------------------------------------------------------------------- =============================================================================== } unit uRecibosClienteController; interface uses Classes, SysUtils, uDADataTable, uControllerBase, uPagosClienteController, uClientesController, uViewGridBase, uBizRecibosCliente, uIDataModuleRecibosCliente; type IRecibosClienteController = interface(IObservador) ['{CBC8BDB8-FBE0-4D54-B2F1-A9330E8339EB}'] function GetPagosController: IPagosClienteController; procedure SetPagosController(const Value: IPagosClienteController); property PagosController: IPagosClienteController read GetPagosController write SetPagosController; procedure Anadir(ARecibosCliente : IBizRecibosCliente); function Eliminar(ARecibosCliente : IBizRecibosCliente): Boolean; function AnadirPago(ARecibosCliente : IBizRecibosCliente; FechaPago: String =''): Boolean; procedure ModificarPago(ARecibosCliente : IBizRecibosCliente); function EliminarPago(ARecibosCliente : IBizRecibosCliente): Boolean; function EliminarTodo(ARecibosCliente : IBizRecibosCliente): Boolean; function Guardar(ARecibosCliente : IBizRecibosCliente): Boolean; procedure DescartarCambios(ARecibosCliente : IBizRecibosCliente); function Duplicar(ARecibosCliente: IBizRecibosCliente): IBizRecibosCliente; function Nuevo : IBizRecibosCliente; procedure RecuperarCliente(AReciboCliente : IBizRecibosCliente); function Buscar(const ID: Integer): IBizRecibosCliente; function BuscarTodos: IBizRecibosCliente; function BuscarRecibosRemesa(const ID_REMESA: Integer): IBizRecibosCliente; function BuscarRecibosFactura(const ID_FACTURA: Integer): IBizRecibosCliente; function BuscarRecibosACompensar(const Recibo: IBizRecibosCliente): IBizRecibosCliente; function BuscarRecibosARemesar(const AListaVisibles, AListaNoVisibles: TStringList): IBizRecibosCliente; procedure VerTodos(ARecibosCliente: IBizRecibosCliente); procedure Ver(ARecibosCliente: IBizRecibosCliente); function ExtraerSeleccionados(ARecibosCliente: IBizRecibosCliente; Const ViewGrid: IViewGridBase = Nil) : IBizRecibosCliente; function ElegirRecibos(ARecibos : IBizRecibosCliente; AMensaje: String; AMultiSelect: Boolean): IBizRecibosCliente; procedure AsignarRemesa(ARecibos : IBizRecibosCliente; ID_REMESA: Integer); procedure QuitarRemesa(ARecibos : IBizRecibosCliente); procedure SetSituacionCobrados(ARecibos : IBizRecibosCliente; WithDeltas: Boolean=False); function ElegirRecibosCompensados(ARecibo : IBizRecibosCliente): Boolean; procedure QuitarReciboCompensado(ARecibo : IBizRecibosCliente); procedure Preview(ARecibosCliente : IBizRecibosCliente; AllItems: Boolean = false); function Print(ARecibosCliente : IBizRecibosCliente; AllItems: Boolean = false): Boolean; function EnviarEmailRecibos(ARecibos : IBizRecibosCliente): Boolean; function GenerarEmailRecibo(ARecibo : IBizRecibosCliente): Boolean; function EnviarReciboPorEMail(ARecibo: IBizRecibosCliente; const AEnviarDirectamente: Boolean = True; const ADireccionEMail: String = ''; const AAsuntoEMail: String = ''; const ATextoEMail: String = ''): Boolean; function DarListaAnosRecibos: TStringList; procedure FiltrarAno(ARecibo: IBizRecibosCliente; AWhereDataTable: String; const Ano: String); end; TRecibosClienteController = class(TObservador, IRecibosClienteController) private function ImporteTotalModificado(ARecibosCliente: IBizRecibosCliente; var ImporteRestante: Currency): Boolean; procedure _AnadirMarcaEnvioCorreo(ARecibo: IBizRecibosCliente); protected FDataModule : IDataModuleRecibosCliente; FPagosController : IPagosClienteController; FClienteController : IClientesController; function GetPagosController: IPagosClienteController; procedure SetPagosController(const Value: IPagosClienteController); function _Vacio : IBizRecibosCliente; function ValidarReciboCliente(ARecibosCliente: IBizRecibosCliente): Boolean; procedure AsignarDataModule; procedure AsignarID(ARecibosCliente: IBizRecibosCliente; const IDNuevo: Integer); function DarNuevaReferencia(ID_FACTURA : Integer; REFERENCIA: String): String; public property PagosController: IPagosClienteController read GetPagosController write SetPagosController; constructor Create; virtual; destructor Destroy; override; procedure RecuperarCliente(AReciboCliente : IBizRecibosCliente); procedure Anadir(ARecibosCliente : IBizRecibosCliente); function AnadirPago(ARecibosCliente : IBizRecibosCliente; FechaPago: String =''): Boolean; procedure ModificarPago(ARecibosCliente : IBizRecibosCliente); function Eliminar(ARecibosCliente : IBizRecibosCliente): Boolean; function EliminarPago(ARecibosCliente : IBizRecibosCliente): Boolean; function EliminarTodo(ARecibosCliente : IBizRecibosCliente): Boolean; function Guardar(ARecibosCliente : IBizRecibosCliente): Boolean; procedure DescartarCambios(ARecibosCliente : IBizRecibosCliente); function Duplicar(ARecibosCliente: IBizRecibosCliente): IBizRecibosCliente; function Nuevo : IBizRecibosCliente; function Buscar(const ID: Integer): IBizRecibosCliente; function BuscarTodos: IBizRecibosCliente; function BuscarRecibosRemesa(const ID_REMESA: Integer): IBizRecibosCliente; function BuscarRecibosFactura(const ID_FACTURA: Integer): IBizRecibosCliente; function BuscarRecibosACompensar(const Recibo: IBizRecibosCliente): IBizRecibosCliente; function BuscarRecibosARemesar(const AListaVisibles, AListaNoVisibles: TStringList): IBizRecibosCliente; procedure VerTodos(ARecibosCliente: IBizRecibosCliente); procedure Ver(ARecibosCliente: IBizRecibosCliente); function ExtraerSeleccionados(ARecibosCliente: IBizRecibosCliente; Const ViewGrid: IViewGridBase = Nil) : IBizRecibosCliente; function ElegirRecibos(ARecibos : IBizRecibosCliente; AMensaje: String; AMultiSelect: Boolean): IBizRecibosCliente; function ElegirRecibosCompensados(ARecibo : IBizRecibosCliente): Boolean; procedure AsignarRemesa(ARecibos : IBizRecibosCliente; ID_REMESA: Integer); procedure QuitarRemesa(ARecibos : IBizRecibosCliente); procedure QuitarReciboCompensado(ARecibo : IBizRecibosCliente); procedure SetSituacionCobrados(ARecibos : IBizRecibosCliente; WithDeltas: Boolean=False); procedure Preview(ARecibosCliente : IBizRecibosCliente; AllItems: Boolean = false); function Print(ARecibosCliente : IBizRecibosCliente; AllItems: Boolean = false): Boolean; function EnviarEmailRecibos(ARecibos : IBizRecibosCliente): Boolean; function GenerarEmailRecibo(ARecibo : IBizRecibosCliente): Boolean; function EnviarReciboPorEMail(ARecibo: IBizRecibosCliente; const AEnviarDirectamente: Boolean = True; const ADireccionEMail: String = ''; const AAsuntoEMail: String = ''; const ATextoEMail: String = ''): Boolean; function DarListaAnosRecibos: TStringList; procedure FiltrarAno(ARecibo: IBizRecibosCliente; AWhereDataTable: String; const Ano: String); end; implementation uses Forms, uNumUtils, cxControls, DB, uEditorRegistryUtils, Dialogs, uDAInterfaces, uDataTableUtils, uDataModuleUsuarios, uDateUtils, uROTypes, DateUtils, Controls, Windows, Variants, uRecibosClienteReportController, uBizContactos, uDataModuleRegistroCorreos, schRecibosClienteClient_Intf, uIEditorRecibosCliente, uIEditorReciboCliente, uIEditorElegirRecibosCliente, uDataModuleRecibosCliente, uIEditorFechaPago, uIDialogListaRecibosCliEnvioEMail, uSistemaFunc, uStringsUtils, uDialogElegirEMail, uEMailUtils; { TRecibosClienteController } procedure TRecibosClienteController.Anadir(ARecibosCliente: IBizRecibosCliente); begin ARecibosCliente.Insert; end; function TRecibosClienteController.AnadirPago(ARecibosCliente: IBizRecibosCliente; FechaPago: String =''): Boolean; var AEditor : IEditorFechaPago; begin Result := False; if (Length(ARecibosCliente.REFERENCIA_REMESA) = 0) or (Application.MessageBox(PChar('Este recibo está remesado en la remesa de referencia ' + ARecibosCliente.REFERENCIA_REMESA + '.' + #10#13 + 'Si añade una devolución, el recibo quedará libre y podrá ser incluido en otra remesa diferente.' + #10#13 + '¿Desea continuar?'), 'Atención', MB_YESNO) = IDYES) then begin //Pedimos la fecha del pago if (Length(FechaPago) = 0) then begin CreateEditor('EditorFechaPago', IEditorFechaPago, AEditor); if Assigned(AEditor) then try if (AEditor.ShowModal = mrOk) then FechaPago := DateToStr(AEditor.FechaPago); AEditor.Release; finally AEditor := NIL; end; end; // Se cancela la operación if Length(FechaPago) = 0 then Exit; //Liberamos el recibo aunque ya este libre if not ARecibosCliente.DataTable.Editing then ARecibosCliente.DataTable.Edit; ARecibosCliente.ID_REMESA := 0; ARecibosCliente.REFERENCIA_REMESA := ''; ARecibosCliente.DataTable.Post; end // Se cancela la operación else Exit; //Finalmente añadimos el pago (cobro o devolucion) if PagosController.Anadir(ARecibosCliente.Pagos, FechaPago) then begin ARecibosCliente.Edit; ARecibosCliente.SITUACION := CTE_COBRADO; Result := True; end //Podremos modificar si anulamos el cobro mediante una devolución else begin ARecibosCliente.Edit; ARecibosCliente.SITUACION := CTE_DEVUELTO; Result := False; end; end; procedure TRecibosClienteController.AsignarDataModule; begin FDataModule := TDataModuleRecibosCliente.Create(Nil); end; procedure TRecibosClienteController.AsignarID(ARecibosCliente: IBizRecibosCliente; const IDNuevo: Integer); begin if not Assigned(ARecibosCliente) then raise Exception.Create ('IBizRecibosCliente no asignado'); if not Assigned(ARecibosCliente.Pagos) then raise Exception.Create ('Pagos del recibo no asignados'); if not Assigned(FPagosController) then raise Exception.Create ('Controller pagos no asignado'); { Los detalles hay que comprobarlos siempre tanto en inserción como en modificación. } if Assigned(ARecibosCliente.Pagos) then FPagosController.AsignarID(ARecibosCliente.Pagos, IDNuevo, ARecibosCliente.EsNuevo); //Lo haremos siempre para actualizar siempre la referencia del recibo // if ARecibosCliente.EsNuevo then // begin ARecibosCliente.Edit; ARecibosCliente.ID := IDNuevo; ARecibosCliente.DESCRIPCION := 'RECIBO ' + ARecibosCliente.REFERENCIA + ' - ' + CifraToLetras((ARecibosCliente.IMPORTE + ARecibosCliente.OTROS_GASTOS)); ARecibosCliente.Post; // end; end; procedure TRecibosClienteController.AsignarRemesa(ARecibos: IBizRecibosCliente; ID_REMESA: Integer); begin if Assigned(ARecibos) then begin With ARecibos.DataTable do begin First; While not EOF do begin if (ARecibos.ID_REMESA <> ID_REMESA) then begin ARecibos.Edit; //Añadimos el cobro automatico por la remesa y volvemos a asignar ID //para que asigne un ID nuevo para el pago, porque aqui si hay maestro-detalle AnadirPago(ARecibos, DateToStr(Date)); //->Ojo el orden es importante ARecibos.ID_REMESA := ID_REMESA; AsignarID(ARecibos, ARecibos.ID); end; Next; end; end; end; end; function TRecibosClienteController.BuscarTodos: IBizRecibosCliente; begin Result := FDataModule.GetItems; end; function TRecibosClienteController.BuscarRecibosACompensar(const Recibo: IBizRecibosCliente): IBizRecibosCliente; begin if not Assigned(Recibo) then raise Exception.Create ('IBizRecibosCliente no asignado (BuscarRecibosACompensar)'); ShowHourglassCursor; try Result := BuscarTodos; with Result.DataTable.Where do begin if NotEmpty then AddOperator(opAND); //No podrá compensarse un recibo a si mismo OpenBraket; AddText(fld_RecibosClienteID + ' <> ' + IntToStr(Recibo.ID)); CloseBraket; AddOperator(opAND); //Solo podrá compensar recibos del mismo cliente OpenBraket; AddText(fld_RecibosClienteID_CLIENTE + ' = ' + IntToStr(Recibo.ID_CLIENTE)); CloseBraket; AddOperator(opAND); //Omitimos los recibos compensados OpenBraket; AddText(fld_RecibosClienteID_RECIBO_COMPENSADO + ' IS NULL '); CloseBraket; AddOperator(opAND); //No podrá compensarse recibos que estan cobrados OpenBraket; AddText(fld_RecibosClienteSITUACION + ' <> ''' + CTE_COBRADO + ''''); CloseBraket; end; finally HideHourglassCursor; end; end; constructor TRecibosClienteController.Create; begin inherited; AsignarDataModule; FPagosController := TPagosClienteController.Create; FClienteController := TClientesController.Create; // FPagosController.addObservador(Self); //PETA NO SE PORQUE end; function TRecibosClienteController.Buscar(const ID: Integer): IBizRecibosCliente; begin Result := (FDataModule as IDataModuleRecibosCliente).GetItem(ID); end; function TRecibosClienteController.BuscarRecibosFactura(const ID_FACTURA: Integer): IBizRecibosCliente; begin ShowHourglassCursor; try Result := BuscarTodos; with Result.DataTable.Where do begin if NotEmpty then AddOperator(opAND); OpenBraket; AddText(fld_RecibosClienteID_FACTURA + ' = ' + IntToStr(ID_FACTURA)); CloseBraket; end; finally HideHourglassCursor; end; end; function TRecibosClienteController.BuscarRecibosARemesar(const AListaVisibles, AListaNoVisibles: TStringList): IBizRecibosCliente; var i: Integer; begin ShowHourglassCursor; try Result := BuscarTodos; with Result.DataTable.Where do begin if NotEmpty then AddOperator(opAND); //Omitimos los recibos compensados OpenBraket; AddText(fld_RecibosClienteID_RECIBO_COMPENSADO + ' IS NULL '); CloseBraket; AddOperator(opAND); //Solo dejaremos remesar aquellos recibos que no esten cobrados (Pendientes/Devueltos) OpenBraket; AddText(fld_RecibosClienteSITUACION + ' <> ''' + CTE_COBRADO + ''''); CloseBraket; //En este caso vamos a quitar de la lista de recibos pendientes aquellos que ya hemos //añadido a la remesa pero que estan en memoria ya que todavia no se ha guarado en BD for i := 0 to AListaNoVisibles.Count - 1 do begin AddOperator(opAND); OpenBraket; AddText(fld_RecibosClienteID + ' <> ''' + AListaNoVisibles.Strings[i] + ''''); CloseBraket; end; //En el caso contrario no hacemos nada, porque si se elimina un recibo de la remesa //y sin guardar los cambios damos a añadir el recibo todavia está cobrado y no se que efectos //secundarios puede provocar //AListaVisibles end; finally HideHourglassCursor; end; end; function TRecibosClienteController.BuscarRecibosRemesa(const ID_REMESA: Integer): IBizRecibosCliente; begin ShowHourglassCursor; try Result := BuscarTodos; with Result.DataTable.Where do begin if NotEmpty then AddOperator(opAND); OpenBraket; AddText(fld_RecibosClienteID_REMESA + ' = ' + IntToStr(ID_REMESA)); CloseBraket; end; finally HideHourglassCursor; end; end; procedure TRecibosClienteController._AnadirMarcaEnvioCorreo(ARecibo: IBizRecibosCliente); var ASoloLectura : Boolean; begin if not Assigned(ARecibo) then raise Exception.Create ('Recibo no asignada (_AnadirMarcaEnvioCorreo)'); if ARecibo.DataTable.Active then ARecibo.DataTable.Active := True; if AnadirMarcaEnvioCorreo(nme_RecibosCliente, ARecibo.ID) then begin DesconectarTabla(ARecibo.DataTable); try ASoloLectura := ARecibo.DataTable.ReadOnly; if ASoloLectura then SetDataTableReadOnly(ARecibo.DataTable, False); try ARecibo.Edit; ARecibo.NUM_CORREOS := ARecibo.NUM_CORREOS + 1; ARecibo.Post; finally if ASoloLectura then SetDataTableReadOnly(ARecibo.DataTable, True); end; finally ConectarTabla(ARecibo.DataTable); end; end; end; function TRecibosClienteController._Vacio: IBizRecibosCliente; begin Result := Buscar(ID_NULO); end; function TRecibosClienteController.DarListaAnosRecibos: TStringList; begin Result := FDataModule.GetAnosItems; end; function TRecibosClienteController.DarNuevaReferencia(ID_FACTURA: Integer; REFERENCIA: String): String; var ARecibosCliente: IBizRecibosCliente; NumReferencia : Integer; Cadena : String; begin try ARecibosCliente := BuscarRecibosFactura(ID_FACTURA); ARecibosCliente.DataTable.Active := True; NumReferencia := ARecibosCliente.DataTable.RecordCount; Cadena := Copy(REFERENCIA, 0, Pos('-', REFERENCIA)); Result := Cadena + ' ' + IntToStr((NumReferencia + 1)); finally ARecibosCliente := Nil; end; end; procedure TRecibosClienteController.DescartarCambios(ARecibosCliente: IBizRecibosCliente); begin if not Assigned(ARecibosCliente) then raise Exception.Create ('IBizRecibosCliente no asignado'); ShowHourglassCursor; try if (ARecibosCliente.State in dsEditModes) then ARecibosCliente.Cancel; ARecibosCliente.DataTable.CancelUpdates; finally HideHourglassCursor; end; end; destructor TRecibosClienteController.Destroy; begin FDataModule := NIL; FPagosController := NIL; FClienteController := NIL; inherited; end; function TRecibosClienteController.Duplicar(ARecibosCliente: IBizRecibosCliente): IBizRecibosCliente; begin Result := Self._Vacio; ShowHourglassCursor; try DuplicarRegistros(ARecibosCliente.DataTable, Result.DataTable, mdrActual); // Descomentar esto si hay detalles // (EN ESTE CASO NO NOS INTERESA COPIAR LOS PAGOS DEL RECIBO DUPLIACDO) // DuplicarRegistros(ARecibosCliente.Detalles.DataTable, Result.Detalles.DataTable, mdrTodos); // ¡CUIDADO! Hay que dejar algunos campos como si fuera todo nuevo Result.Edit; with Result do begin // Ejemplos // ID_EMPRESA := dmUsuarios.IDEmpresaActual; // USUARIO := dmUsuarios.LoginInfo.Usuario; // REFERENCIA := ''; //Para que se asigne una nueva // FECHA_FACTURA := DateOf(Now); // SITUACION := SITUACION_PENDIENTE; end; Result.Post; finally HideHourglassCursor; end; end; function TRecibosClienteController.ValidarReciboCliente(ARecibosCliente: IBizRecibosCliente): Boolean; var ImporteRestante: Double; begin Result := False; if not Assigned(ARecibosCliente) then raise Exception.Create ('IBizRecibosCliente no asignado'); if (ARecibosCliente.DataTable.State in dsEditModes) then ARecibosCliente.DataTable.Post; // Tambien hacemos post de sus tablas hija if (ARecibosCliente.Pagos.DataTable.State in dsEditModes) then ARecibosCliente.Pagos.DataTable.Post; if ARecibosCliente.DataTable.FieldByName(fld_RecibosClienteFECHA_EMISION).IsNull then raise Exception.Create('Debe indicar la fecha de emisión del recibo.'); if ARecibosCliente.DataTable.FieldByName(fld_RecibosClienteFECHA_VENCIMIENTO).IsNull then raise Exception.Create('Debe indicar la fecha de vencimiento del recibo.'); { Asegurarse de valores en campos "automáticos" tanto en MODIFICACIÓN como en INSERCIÓN. } ARecibosCliente.Edit; try ARecibosCliente.USUARIO := dmUsuarios.LoginInfo.Usuario; Result := True; finally ARecibosCliente.Post; end; Result := True; end; procedure TRecibosClienteController.Ver(ARecibosCliente: IBizRecibosCliente); var AEditor : IEditorReciboCliente; begin AEditor := NIL; ShowHourglassCursor; try RecuperarCliente(ARecibosCliente); CreateEditor('EditorReciboCliente', IEditorReciboCliente, AEditor); with AEditor do begin Controller := Self; //OJO ORDEN MUY IMPORTANTE Recibo := ARecibosCliente; end; finally HideHourglassCursor; end; if Assigned(AEditor) then try AEditor.ShowModal; AEditor.Release; finally AEditor := NIL; end; end; procedure TRecibosClienteController.VerTodos(ARecibosCliente: IBizRecibosCliente); var AEditor : IEditorRecibosCliente; begin AEditor := NIL; ShowHourglassCursor; try CreateEditor('EditorRecibosCliente', IEditorRecibosCliente, AEditor); if Assigned(AEditor) then with AEditor do begin Controller := Self; //OJO ORDEN MUY IMPORTANTE RecibosCliente := ARecibosCliente; MultiSelect := True; ShowEmbedded; end; finally AEditor := NIL; HideHourglassCursor; end; end; function TRecibosClienteController.ElegirRecibos(ARecibos: IBizRecibosCliente; AMensaje: String; AMultiSelect: Boolean): IBizRecibosCliente; var AEditor : IEditorElegirRecibosCliente; begin Result := NIL; CreateEditor('EditorElegirRecibosCliente', IEditorElegirRecibosCliente, AEditor); try with AEditor do begin Controller := Self; RecibosCliente := ARecibos; MultiSelect := AMultiSelect; Mensaje := AMensaje; if IsPositiveResult(ShowModal) then Result := RecibosClienteSeleccionados; Release; end; finally AEditor := NIL; end; end; function TRecibosClienteController.ElegirRecibosCompensados(ARecibo: IBizRecibosCliente): Boolean; var ARecibosACompensar: IBizRecibosCliente; begin ARecibosACompensar := Self.ElegirRecibos(BuscarRecibosACompensar(ARecibo), 'Elija los recibos que desea compensar', True); if Assigned(ARecibosACompensar) then begin ShowHourglassCursor; try DuplicarRegistros(ARecibosACompensar.DataTable, ARecibo.RecibosCompensados.DataTable, mdrTodos, True, True, False); Result := True; finally HideHourglassCursor; ARecibosACompensar := Nil; end; end; end; function TRecibosClienteController.Eliminar(ARecibosCliente: IBizRecibosCliente): Boolean; begin Result := False; if not Assigned(ARecibosCliente) then raise Exception.Create ('IBizRecibosCliente no asignado'); ShowHourglassCursor; try if (ARecibosCliente.State in dsEditModes) then ARecibosCliente.Cancel; ARecibosCliente.Delete; ARecibosCliente.DataTable.ApplyUpdates; HideHourglassCursor; Result := True; finally HideHourglassCursor; end; end; function TRecibosClienteController.EliminarPago(ARecibosCliente: IBizRecibosCliente): Boolean; begin Result := PagosController.Eliminar(ARecibosCliente.Pagos); end; function TRecibosClienteController.EliminarTodo(ARecibosCliente: IBizRecibosCliente): Boolean; begin if Assigned(ARecibosCliente) then begin if not ARecibosCliente.DataTable.Active then ARecibosCliente.DataTable.Active := True; ARecibosCliente.DataTable.ClearRows; ARecibosCliente.DataTable.ApplyUpdates; Result := True; end; end; function TRecibosClienteController.EnviarEmailRecibos( ARecibos: IBizRecibosCliente): Boolean; var ADialog : IDialogListaRecibosCliEnvioEMail; ARespuesta : Integer; begin ADialog := NIL; if not Assigned(ARecibos) then raise Exception.Create ('Recibos no asignadas (EnviarRecibosCliPorEMail)'); if ARecibos.DataTable.Active then ARecibos.DataTable.Active := True; ShowHourglassCursor; try CreateEditor('DialogListaRecibosCliEnvioEMail', IDialogListaRecibosCliEnvioEMail, ADialog); if Assigned(ADialog) then begin try ADialog.Recibos := ARecibos; ARespuesta := ADialog.ShowModal; Result := (ARespuesta = mrOK) finally ADialog.Release; end; end; finally ADialog := NIL; HideHourglassCursor; end; end; function TRecibosClienteController.EnviarReciboPorEMail( ARecibo: IBizRecibosCliente; const AEnviarDirectamente: Boolean; const ADireccionEMail, AAsuntoEMail, ATextoEMail: String): Boolean; var AReportController : IRecibosClienteReportController; AFicheroTMP : TFileName; AEMail : String; AAsunto : String; AListaEmail : TStringList; begin if not Assigned(ARecibo) then raise Exception.Create ('Recibo no asignada (EnviarReciboPorEMail)'); if ARecibo.DataTable.Active then ARecibo.DataTable.Active := True; RecuperarCliente(ARecibo); ARecibo.Cliente.DataTable.Active := True; AFicheroTMP := DarFicheroPDFTemporal(EscapeIllegalChars(ARecibo.REFERENCIA)); if not EsCadenaVacia(ADireccionEMail) then AEMail := ADireccionEMail else begin AListaEmail := TStringList.Create; try if not EsCadenaVacia(ARecibo.Cliente.EMAIL_ADMINISTRACION) then AListaEmail.Add(ARecibo.Cliente.EMAIL_ADMINISTRACION); if not ElegirEMail(AListaEmail, AEMail) then Exit; finally FreeANDNIL(AListaEmail); end; end; if not EsCadenaVacia(AAsuntoEMail) then AAsunto := AAsuntoEMail else AAsunto := 'Recibo ' + ARecibo.REFERENCIA; ShowHourglassCursor; Application.ProcessMessages; AReportController := TRecibosClienteReportController.Create; try AReportController.ExportToPDF(ARecibo.ID, AFicheroTMP); Result := EnviarEMailMAPI(AAsunto, ATextoEMail, AFicheroTMP, '', '', ARecibo.Cliente.NOMBRE, AEMail, AEnviarDirectamente); if Result then _AnadirMarcaEnvioCorreo(ARecibo); finally SysUtils.DeleteFile(AFicheroTMP); AReportController := NIL; HideHourglassCursor; Application.ProcessMessages; end; end; procedure TRecibosClienteController.RecuperarCliente(AReciboCliente: IBizRecibosCliente); begin AReciboCliente._Cliente := (FClienteController.Buscar(AReciboCliente.ID_Cliente) as IBizCliente); end; function TRecibosClienteController.GenerarEmailRecibo( ARecibo: IBizRecibosCliente): Boolean; begin if not Assigned(ARecibo) then raise Exception.Create ('Recibos no asignadas (GenerarEmailRecibo)'); if ARecibo.DataTable.Active then ARecibo.DataTable.Active := True; ShowHourglassCursor; try RecuperarCliente(ARecibo); EnviarReciboPorEMail(ARecibo, False, ARecibo.Cliente.EMAIL_ADMINISTRACION); finally HideHourglassCursor; end; end; function TRecibosClienteController.GetPagosController: IPagosClienteController; begin Result := FPagosController; end; procedure TRecibosClienteController.SetPagosController(const Value: IPagosClienteController); begin FPagosController := Value; end; procedure TRecibosClienteController.SetSituacionCobrados(ARecibos: IBizRecibosCliente; WithDeltas: Boolean); begin if Assigned(ARecibos) then begin ARecibos.DataTable.DisableControls; try DesconectarTabla(ARecibos.DataTable); with ARecibos.DataTable do begin First; while not Eof do begin if not Editing then Edit; ARecibos.SITUACION := CTE_COBRADO; Post; Next; end; First; end; finally ConectarTabla(ARecibos.DataTable); ARecibos.DataTable.EnableControls; end; end; end; function TRecibosClienteController.ImporteTotalModificado(ARecibosCliente : IBizRecibosCliente; var ImporteRestante: Currency) : Boolean; var HayCambio: TDADeltaChange; begin Result := False; ImporteRestante := 0; HayCambio := ARecibosCliente.DataTable.Delta.FindChange(ARecibosCliente.RecNo); if (Assigned(HayCambio)) and (HayCambio.OldValueByName[fld_RecibosClienteIMPORTE] <> 0) then begin ImporteRestante := HayCambio.OldValueByName[fld_RecibosClienteIMPORTE] - ARecibosCliente.IMPORTE; if ImporteRestante <> 0 then Result := True; end; end; function TRecibosClienteController.Guardar(ARecibosCliente: IBizRecibosCliente): Boolean; var NuevoID : Integer; ANuevoReciboCliente : IBizRecibosCliente; ImporteRestante : Currency; begin Result := False; ANuevoReciboCliente := NIL; ImporteRestante := 0; if ValidarReciboCliente(ARecibosCliente) then begin ShowHourglassCursor; try if ARecibosCliente.EsNuevo then NuevoID := FDataModule.GetNextID(ARecibosCliente.DataTable.LogicalName) else NuevoID := ARecibosCliente.ID; //Si el importe ha cambiado se debe hacer un recibo nuevo con el importe restante if ImporteTotalModificado(ARecibosCliente, ImporteRestante) then begin ANuevoReciboCliente := Duplicar(ARecibosCliente); ANuevoReciboCliente.Edit; ANuevoReciboCliente.REFERENCIA := DarNuevaReferencia(ARecibosCliente.ID_FACTURA, ARecibosCliente.REFERENCIA); ANuevoReciboCliente.ID := FDataModule.GetNextID(ARecibosCliente.DataTable.LogicalName); ANuevoReciboCliente.IMPORTE := ImporteRestante; ANuevoReciboCliente.DESCRIPCION := 'RECIBO ' + ANuevoReciboCliente.REFERENCIA + ' - ' + CifraToLetras(ImporteRestante); ANuevoReciboCliente.Post; end; //Primero debemos hacer el ApplyUpdates del recibo inicial por si fallase //Así no se haría el nuevo AsignarID(ARecibosCliente, NuevoID); ARecibosCliente.DataTable.ApplyUpdates; if Assigned(ANuevoReciboCliente) then ANuevoReciboCliente.DataTable.ApplyUpdates; Result := True; finally ANuevoReciboCliente := NIL; HideHourglassCursor; end; end; end; procedure TRecibosClienteController.ModificarPago(ARecibosCliente: IBizRecibosCliente); var AEditor : IEditorFechaPago; AFechaPago: String; begin //Pedimos la fecha del pago CreateEditor('EditorFechaPago', IEditorFechaPago, AEditor); if Assigned(AEditor) then try AEditor.FechaPago:= ARecibosCliente.Pagos.FECHA_PAGO; if (AEditor.ShowModal = mrOk) then AFechaPago := DateToStr(AEditor.FechaPago); AEditor.Release; finally AEditor := NIL; end; if Length(AFechaPago) > 0 then PagosController.Modificar(ARecibosCliente.Pagos, AFechaPago); end; function TRecibosClienteController.Nuevo: IBizRecibosCliente; var ARecibo : IBizRecibosCliente; begin ARecibo := Buscar(ID_NULO); ARecibo.DataTable.Active := True; Anadir(ARecibo); Result := ARecibo; end; procedure TRecibosClienteController.QuitarReciboCompensado(ARecibo: IBizRecibosCliente); var IdRecibo: Variant; begin IdRecibo := ARecibo.RecibosCompensados.ID; ARecibo.RecibosCompensados.DataTable.First; while ARecibo.RecibosCompensados.DataTable.Locate('ID', IdRecibo,[]) do begin ARecibo.RecibosCompensados.DataTable.Delete; ARecibo.RecibosCompensados.DataTable.First; end; end; procedure TRecibosClienteController.QuitarRemesa(ARecibos: IBizRecibosCliente); begin if Assigned(ARecibos) then begin if ARecibos.Pagos.DataTable.RecordCount = 0 then Exit; //Eliminamos el cobro generado por la remesa y quitamos el ID_REMESA del recibo ARecibos.Pagos.DataTable.Last; ARecibos.Pagos.Delete; ARecibos.DataTable.Edit; ARecibos.ID_REMESA := 0; ARecibos.DataTable.Post; end; end; function TRecibosClienteController.ExtraerSeleccionados(ARecibosCliente: IBizRecibosCliente; Const ViewGrid: IViewGridBase = Nil): IBizRecibosCliente; var ASeleccionados : IBizRecibosCliente; begin if Assigned(ViewGrid) then begin //Guardamos la situación porque el CopyDataTable nos cambia la posicion ViewGrid.SaveGridStatus; ViewGrid.DesactivarGrid; end; ASeleccionados := (Self.Buscar(ID_NULO) as IBizRecibosCliente); CopyDataTable(ARecibosCliente.DataTable, ASeleccionados.DataTable, True); Result := ASeleccionados; if Assigned(ViewGrid) then begin ViewGrid.ActivarGrid; ViewGrid.RestoreGridStatus; end; end; procedure TRecibosClienteController.FiltrarAno(ARecibo: IBizRecibosCliente; AWhereDataTable: String; const Ano: String); var FechaIni: String; FechaFin: String; begin ARecibo.DataTable.Where.Clear; ARecibo.DataTable.Where.AddText(AWhereDataTable); if (Ano <> 'Todos') then begin // Filtrar las facturas actuales por empresa FechaIni := '01.01.' + Ano; FechaFin := '31.12.' + Ano; with ARecibo.DataTable.Where do begin if NotEmpty then AddOperator(opAND); AddCondition(fld_RecibosClienteFECHA_EMISION, cMajorOrEqual, FechaIni); AddOperator(opAND); AddCondition(fld_RecibosClienteFECHA_EMISION, cLessOrEqual, FechaFin); end; end; end; procedure TRecibosClienteController.Preview(ARecibosCliente: IBizRecibosCliente; AllItems: Boolean = false); var AReportController : IRecibosClienteReportController; ID_Recibos: TStringList; begin AReportController := TRecibosClienteReportController.Create; try ID_Recibos := TStringList.Create; //Si deseamos previsualizar todos los items del objeto albaran if AllItems then begin with ARecibosCliente.DataTable do begin First; while not EOF do begin ID_Recibos.Add(IntToStr(ARecibosCliente.ID)); Next; end; end; end //Solo previsualizamos el item seleccionado else ID_Recibos.Add(IntToStr(ARecibosCliente.ID)); AReportController.Preview(ID_Recibos.CommaText); finally AReportController := NIL; ID_Recibos.Free; end; end; function TRecibosClienteController.Print(ARecibosCliente: IBizRecibosCliente; AllItems: Boolean = false): Boolean; var AReportController : IRecibosClienteReportController; ID_Recibos: TStringList; begin Result := False; AReportController := TRecibosClienteReportController.Create; try ID_Recibos := TStringList.Create; //Si deseamos previsualizar todos los items del objeto albaran if AllItems then begin with ARecibosCliente.DataTable do begin First; while not EOF do begin ID_Recibos.Add(IntToStr(ARecibosCliente.ID)); Next; end; end; end //Solo previsualizamos el item seleccionado else ID_Recibos.Add(IntToStr(ARecibosCliente.ID)); Result := AReportController.Print(ID_Recibos.CommaText); finally AReportController := NIL; ID_Recibos.Free; end; end; end.