Skip to content

Instantly share code, notes, and snippets.

@dutchand
Created November 12, 2014 16:40
Show Gist options
  • Save dutchand/2cd1b2acd6e16e4c28a0 to your computer and use it in GitHub Desktop.
Save dutchand/2cd1b2acd6e16e4c28a0 to your computer and use it in GitHub Desktop.
Local mail implementation within application
/**
* ActionScript source file that defines the UI logic and some of the data access code.
* This file is linked into the main application MXML file using the mx:Script tag.
* Most of the functions in this file are called by event handlers defined in
* the MXML.
*/
//import Modulos.Auditoria.AuditoriaClase;
import Model.Modelo.AppModel;
public var usuario_conectado:String = AppModel.nombre_usuario;
public var role_user:String = AppModel.privilegiado;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.events.CloseEvent;
import mx.events.DataGridEvent;
import mx.managers.CursorManager;
import mx.rpc.AsyncToken;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import Model.Validacion.ValidacionClase;
//include the constant definition of the server endpoint URL
include "correoconfig.as";
/**
* gateway : this is the communication layer with the server side php code
*/
private var gateway:HTTPService = new HTTPService();
/**
* the array collection holds the rows that we use in the grid
*/
[Bindable]
public var dataArr:ArrayCollection = new ArrayCollection();
[Bindable]
public var usuario_sistema:ArrayCollection = new ArrayCollection();
/**
* column that we order by. This is updated each time the users clicks on the
* grid column header.
* see headerRelease="setOrder(event);" in the DataGrid instantiation in the
* mxml file
*/
private var orderColumn:Number;
/**
* the list of fields in the database table
* needed to parse the response into hashes
*/
private var fields:Object = { 'IDsms':Number, 'Id_usuario':String,
'Asunto':String, 'Mensaje':String,
'Fecha':Date
};
private var usuario:Object = { 'Id_usuario':String };
/**
* Executes when the mxml is completed loaded. Initialize the Rest Gateway.
*/
private function initApp():void
{
gateway.url = ENDPOINT_URL;
gateway.method = "POST";
gateway.useProxy = false;
gateway.resultFormat = "e4x";
gateway.addEventListener(ResultEvent.RESULT, resultHandler);
gateway.addEventListener(FaultEvent.FAULT, faultHandler);
if(usuario_conectado == "Administrator")
mostrar_usuarios2();
else
mostrar_usuarios();
fill();
// Alert.show(""+role_user+);
}
/**
* Click handler for "Filter" button.
* When setting another filter, refresh the collection, and load the new data
*/
private function filterResults():void
{
fill();
}
/**
* dragHeader handler for the datagrid. This handler is executed when the user
* clicks on a header column in the datagrid
* updates the global orderColumn variable, refreshes the TableCollection
* @param event DataGridEvent details about the column
*/
private function setOrder(event:DataGridEvent):void
{
if(event.columnIndex > 0)
{
orderColumn = event.columnIndex;
var col:DataGridColumn = dataGrid.columns[orderColumn];
col.sortDescending = !col.sortDescending;
fill();
}
event.preventDefault();
}
/**
* Click handler for the "Save" button in the "Add" state
* collects the information in the form and adds a new object to the collection
*/
private function insertItem(UsuarioDestino:String, Asunto:String, Mensaje:String):void
{
AppModel.UsuarioDestino = UsuarioDestino;
var parameters:* =
{
"method": "Insert", "UsuarioOrigen": usuario_conectado,
"UsuarioDestino": UsuarioDestino,
"Asunto": Asunto,
"Mensaje": Mensaje
};
doRequest("Insert", parameters, insertItemHandler);
}
/**
* Result handler for the insert call.
* Alert the error if it exists
* if the call went through ok, return to the list, and refresh the data
*/
private function insertItemHandler(e:Object):void
{
if (e.isError)
{
Alert.show(e.data.error,"Mensajería interna",4,null,null,ValidacionClase.IconoAlertaError());
}
else
{
// var Accion:String = "Envió un correo al usuario: " + AppModel.UsuarioDestino;
//AuditoriaClase.AgregarAuditoria(AppModel.nombre_usuario,Accion);
fill();
goToView();
}
}
private function ResetearBusqueda():void
{
FechaBusqueda.text = "";
filterTxt.text = "";
fill();
}
private function fill():void
{
/**
* find the order parameters
*/
var desc:Boolean = false;
var orderField:String = '';
if(!isNaN(orderColumn))
{
var col:DataGridColumn = dataGrid.columns[orderColumn];
desc = col.sortDescending;
//remove the 'Col' particle
orderField = col.dataField.substr(0,col.dataField.length-3);
}
dataGrid.enabled = false;
CursorManager.setBusyCursor();
var parameters:* =
{
"orderField": orderField,
"orderDirection": (desc) ? "DESC" : "ASC",
"filter": filterTxt.text,
"usuario_conectado": usuario_conectado,
"Fecha": FechaBusqueda.text
}
/**
* execute the server "select" command
*/
doRequest("FindAll", parameters, fillHandler);
}
/**
* result handler for the fill call.
* if it is an error, show it to the user, else refill the arraycollection with the new data
*
*/
private function fillHandler(e:Object):void
{
if (e.isError)
{
Alert.show("Error: " + e.data.error);
}
else
{
dataArr.removeAll();
for each(var row:XML in e.data.row)
{
var temp:* = {};
for (var key:String in fields)
{
temp[key + 'Col'] = row[key];
}
dataArr.addItem(temp);
}
CursorManager.removeBusyCursor();
dataGrid.enabled = true;
}
}
//--------------------------------------------------------------en combobox para elegir
private function mostrar_usuarios():void
{
var desc:Boolean = false;
var parameters:* =
{
"nada": 0
}
doRequest("Usuarios", parameters, LLenarCombousuarios);
}
//--------------------------------------------------------------------------------------
private function LLenarCombousuarios(e:Object):void
{
if (e.isError)
{
Alert.show("Error: " + e.data.error);
}
else
{
usuario_sistema.removeAll();
for each(var row:XML in e.data.row)
{
var temp:* = {};
for (var key:String in usuario)
{
temp[key] = row[key];
}
usuario_sistema.addItem(temp);
}
}
}
private function mostrar_usuarios2():void
{
var desc:Boolean = false;
var parameters:* =
{
"nada": 0
}
doRequest("Usuarios2", parameters, LLenarCombousuarios2);
}
//--------------------------------------------------------------------------------------
private function LLenarCombousuarios2(e:Object):void
{
if (e.isError)
{
Alert.show("Error: " + e.data.error);
}
else
{
usuario_sistema.removeAll();
for each(var row:XML in e.data.row)
{
var temp:* = {};
for (var key:String in usuario)
{
temp[key] = row[key];
}
usuario_sistema.addItem(temp);
}
}
}
//------------------------------------------------------------------------------------------------
/**
* Click handler for the "delete" button in the list
* confirms the action and launches the deleteClickHandler function
*/
private function deleteItem():void
{
if (dataGrid.selectedItem)
{
Alert.show("Are you sure that you want to delete this message?",
"Internal Messaging System", 3, this, deleteClickHandler,ValidacionClase.IconoAlertaAdvertencia());
}
else
{
Alert.show("Select a message to perform this action!!!",
"Internal Messaging System", 4, null, null,ValidacionClase.IconoAlertaError());
}
}
/**
* Event handler function for the Confirm dialog raises when the
* Delete button is pressed.
* If the pressed button was Yes, then the product is deleted.
* @param object event
* @return nothing
*/
private function deleteClickHandler(event:CloseEvent):void
{
if (event.detail == Alert.YES)
{
var vo:* = dataGrid.selectedItem;
AppModel.UsuarioOrigen = vo.Id_usuarioCol;
var parameters:* =
{
"IDsms": vo.IDsmsCol
}
/**
* execute the server "delete" command
*/
doRequest("Delete", parameters, deleteHandler);
setTimeout( function():void
{
dataGrid.destroyItemEditor();
},
1);
}
}
public function deleteHandler(e:*):void
{
if (e.isError)
{
Alert.show(e.data.error,"Internal Messaging System",4,null,null,ValidacionClase.IconoAlertaError());
}
else
{
// var Accion:String = "Eliminó el correo del usuario: " + AppModel.UsuarioOrigen;
//AuditoriaClase.AgregarAuditoria(AppModel.nombre_usuario,Accion);
var IDsms:Number = parseInt(e.data.toString(), 10);
for (var index:Number = 0; index < dataArr.length; index++)
{
if (dataArr[index].IDsmsCol == IDsms)
{
dataArr.removeItemAt(index);
break;
}
}
}
}
/**
* deserializes the xml response
* handles error cases
*
* @param e ResultEvent the server response and details about the connection
*/
public function deserialize(obj:*, e:*):*
{
var toret:Object = {};
toret.originalEvent = e;
if (obj.data.elements("error").length() > 0)
{
toret.isError = true;
toret.data = obj.data;
}
else
{
toret.isError = false;
toret.metadata = obj.metadata;
toret.data = obj.data;
}
return toret;
}
/**
* result handler for the gateway
* deserializes the result, and then calls the REAL event handler
* (set when making a request in the doRequest function)
*
* @param e ResultEvent the server response and details about the connection
*/
public function resultHandler(e:ResultEvent):void
{
var topass:* = deserialize(e.result, e);
e.token.handler.call(null, topass);
}
/**
* fault handler for this connection
*
* @param e FaultEvent the error object
*/
public function faultHandler(e:FaultEvent):void
{
var errorMessage:String = "Connection error: " + e.fault.faultString;
if (e.fault.faultDetail)
{
errorMessage += "\n\nAdditional detail: " + e.fault.faultDetail;
}
Alert.show(errorMessage);
}
/**
* makes a request to the server using the gateway instance
*
* @param method_name String the method name used in the server dispathcer
* @param parameters Object name value pairs for sending in post
* @param callback Function function to be called when the call completes
*/
public function doRequest(method_name:String, parameters:Object, callback:Function):void
{
// add the method to the parameters list
parameters['method'] = method_name;
gateway.request = parameters;
var call:AsyncToken = gateway.send();
call.request_params = gateway.request;
call.handler = callback;
}
/**
* Click handler when the user click the "Create" button
* Load the "Update" canvas.
*/
public function goToUpdate():void
{
//applicationScreens.selectedChild = update;
}
/**
* Load the "View" canvas.
*/
public function goToView():void
{
applicationScreens.selectedChild = view;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment