var indicexGridApp = angular.module('IndicesGridApp', ['module.configuration', 'index.services', 'index.grid.services', 'index.filters', 'moex']);
indicexGridApp.controller('GetIndicesCtrl', ['$scope', 'LocalGroupSettingsFabric', 'IssFabric', 'FieldFabric', 'LocalFabric',
'StringHelper', 'FieldStyleFabric', 'HistoryDataFabric', 'fieldCollectionUrl', 'marketDataCollectionUrl', 'indicesTreeColectionUrl', 'historyCollectionUrl', '$timeout',
function ($scope, LocalGroupSettingsFabric, IssFabric, FieldFabric, LocalFabric,
StringHelper, FieldStyleFabric, HistoryDataFabric, fieldCollectionUrl, marketDataCollectionUrl, indicesTreeColectionUrl, historyCollectionUrl, $timeout) {
$scope.ErrorText = "";
$scope.ReadyData = false;
var indexCollections = null;
var indexSecurities = null;
$('.blocks-list__item._content2').css('border-radius', 0);
$scope.init = function (lang) {
//This function is sort of private constructor for controller
lang = lang || page.lang();
$scope.Lang = lang;
var _LocalGroupSettingsFabricInit = false;
var updateMarketData = function () {
IssFabric.MarketDataCollection(marketDataCollectionUrl, $scope.Lang).success(function (data, status) {
if (data == undefined) {
$scope.ErrorText = "Sorry,there is no data.";
$scope.groupCollection = null;
} else {
$scope.MarketData = data[1].marketdata; //add securities
_.each(data[1].securities, function (security_data) {
if (security_data.SECID === "MOEX10") {
security_data.NAME = moex.localizer.translateRuEn("Индекс МосБиржи 10", security_data.NAME);
}
else if (security_data.SECID === "MOEXINN") {
security_data.NAME = moex.localizer.translateRuEn("Индекс МосБиржи инноваций", security_data.NAME);
}
$scope.MarketData.push(security_data);
});
indexSecurities = data[1].securities;
if (!_LocalGroupSettingsFabricInit){
_LocalGroupSettingsFabricInit = true;
LocalGroupSettingsFabricInit();
}
}
});
$timeout(updateMarketData, 10000);
};
// дерево коллекций индикаторов (группы, подгруппы, {id, parent_id})
var indicesCollectionFunc = IssFabric.IndicesTreeCollection(indicesTreeColectionUrl, $scope.Lang);
// перечисление всех возможных полей (колонок)
var fieldCollectionFunc = FieldFabric.FieldCollectionPromise(fieldCollectionUrl, $scope.Lang);
// данные всех индикаторов
var marketDataCollectionFunc = IssFabric.MarketDataCollection(marketDataCollectionUrl, $scope.Lang);
var LocalGroupSettingsFabricInit = function(){
// LocalGroupSettingsFabric - собственно выводимые групы и подгруппы индикаторов (это всё таблицы), это простой json
LocalGroupSettingsFabric.success(function (settings, status, headers, config) {
var subGroupSettingColl = settings.SubGroupCollection;
var groupSettingColl = settings.GroupCollection;
$scope.groupFields = settings.GroupCollection;
if ($scope.ErrorText != "")
return;
//get Indices Tree
indicesCollectionFunc.success(function (data, status) {
if (data == undefined || data.length < 1) {
$scope.ErrorText = "Sorry,there is no data.";
$scope.ReadyData = true;
$scope.groupCollection = null;
} else {
//get indices tree data from request
var treeData = data[1];
indexCollections = treeData;
//get Marketdata Collection
marketDataCollectionFunc.success(function (data, status) {
if (data == undefined) {
$scope.ErrorText = "Sorry,there is no data.";
$scope.ReadyData = true;
$scope.groupCollection = null;
} else {
//get marketdata + securities from requst
$scope.MarketData = data[1].marketdata; //add securities
_.each(data[1].securities, function (security_data) {
$scope.MarketData.push(security_data);
});
//get History
HistoryDataFabric.HistoryDataCollection(historyCollectionUrl, $scope.Lang, function (data) {
if (data != undefined) {
$scope.History = data;
}
});
//create groupCollection using groupSettings and indices tree data
$scope.groupCollection = LocalFabric.getIndicesTree(treeData, subGroupSettingColl, $scope.MarketData, $scope.History, $scope.Lang);
$scope.groupCollection
if ($scope.groupCollection == "no data") {
$scope.ErrorText = "Sorry,there is no data";
$scope.ReadyData = true;
return;
}
_.each($scope.groupCollection, function (group) {
_.each(group.SubGroupCollection, function (subGroup) {
_.each(subGroup.IndicesCollection, function (indexData) {
if (indexData.title === 'Транспорт') {
indexData.title = 'Транспорта';
}
else if (indexData.title === "Индекс ММВБ 10") {
indexData.title = moex.localizer.translateRuEn("Индекс МосБиржи 10", indexData.title);
}
else if (indexData.title === "Индекс ММВБ-инновации") {
indexData.title = moex.localizer.translateRuEn("Индекс МосБиржи инноваций", indexData.title);
}
});
});
});
var ru = window.location.toString().toLowerCase().indexOf('moex.com/ru/') >= 0;
_.each($scope.groupCollection, function (group) {
if (group.Id === 1) { // Индексы Акций
var newGroup = {
GroupId: 1,
ButtonTitle: ru ? "Показать все" : "SHOW ALL",
HideButtonTitleEn: "HIDE",
HideButtonTitleRu: "Скрыть",
Id: 4,
IssSubGroupId: 60,
ShowAll: false,
ShowAllIndices: false,
ShowButtonTitleEn: "SHOW ALL",
ShowButtonTitleRu: "Показать все",
SortOrder: 25,
Name: ru ? "Индексы полной доходности" : "Total return Indices",
RowCount: 9,
IndexCollection: [{
Id: 0,
SecId: "MCFTR",
SortOrder: 0
},
{
Id: 0,
SecId: "RTSTR",
SortOrder: 1
},
{
Id: 0,
SecId: "MEBCTR",
SortOrder: 2
}],
IndicesCollection: [
{
id: 115426,
RowCount: 1,
title: ru ? 'Индексы МосБиржи полной доходности "брутто"' : 'MOEX Russia Total Return',
SubIndicesCollection: [{
collection_id: 60,
secid: "MCFTR"
}]
},
{
id: 115427,
RowCount: 1,
title: ru ? 'Индексы МосБиржи полной доходности "нетто" (нерезидент)' : 'MOEX Russia Net Total Return (Non-Resident)',
SubIndicesCollection: [{
collection_id: 60,
secid: "MCFTRN"
}]
},
{
id: 115428,
RowCount: 1,
title: ru ? 'Индексы МосБиржи полной доходности "нетто" (резидент)' : 'MOEX Russia Net Total Return (Resident)',
SubIndicesCollection: [{
collection_id: 60,
secid: "MCFTRR"
}]
},
{
id: 0,
RowCount: 1,
title: ru ? 'Индекс РТС полной доходности "брутто"' : 'RTS Total Return',
SubIndicesCollection: [{
collection_id: 60,
secid: "RTSTR"
}]
},
{
id: 0,
RowCount: 1,
title: ru ? 'Индекс РТС полной доходности "нетто" (нерезидент)' : 'RTS Net Total Return (Non-Resident)',
SubIndicesCollection: [{
collection_id: 60,
secid: "RTSTRN"
}]
},
{
id: 0,
RowCount: 1,
title: ru ? 'Индекс РТС полной доходности "нетто" (резидент)' : 'RTS Net Total Return (Resident)',
SubIndicesCollection: [{
collection_id: 60,
secid: "RTSTRR"
}]
}
]
};
newGroup.IndicesCollection = [];
indexCollections.collections_securities.sort(function(a, b){
if (a.secid === b.secid){
return 0;
}
return a.secid > b.secid ? 1 : -1;
});
var id = 0;
_.each(indexCollections.collections_securities, function(ic){
if (ic.collection_id !== 60){
return;
}
var text = _.find(indexSecurities, function(sec){
return sec.SECID.toUpperCase() === ic.secid.toUpperCase();
});
var item = {
id: id++,
RowCount: 1,
title: text.NAME,
SortOrder: 1000,
SecId: ic.secid,
SubIndicesCollection: [{
collection_id: 60,
secid: ic.secid,
SecId: ic.secid,
SortOrder: 1000,
}]
};
if (ic.secid === 'MCFTR'){
item.SortOrder = 0;
}
else if (ic.secid === 'RTSTR'){
item.SortOrder = 1;
}
else if (ic.secid === 'MEBCTR'){
item.SortOrder = 2;
}
newGroup.IndicesCollection.push(item);
});
group.SubGroupCollection.push(newGroup);
}
});
//console.log($scope.groupCollection);
//get Fields Collection
//TODO: add callback function and move this method to common js file
fieldCollectionFunc.then(function (response, status) {
var data = response.data;
if (data != null && data.length > 1) {
var allFields = data[1].marketdata;
_.each(data[1].securities, function (field) {
var commonField = _.find(allFields, function (existField) { return existField.name.toUpperCase() == field.name.toUpperCase(); });
if (commonField == undefined)
allFields.push(field);
});
}
_.each($scope.groupCollection, function (group) {
//set fieldCollection from settings to new group object
var groupSettingItem = _.find(groupSettingColl, function (item) {
return item.IssGroupId == group.Id;
});
if (groupSettingItem) {
;
}
else {
//return;
}
group.SortOrder = groupSettingItem.SortOrder;
group.FieldCollection = LocalFabric.getFieldCollection(groupSettingItem.FieldCollection, allFields);
angular.forEach(group.FieldCollection, function (item) {
if (item.name == "VALTODAY") {
item.title = (item.title || "").replace(", руб", "").replace(", RUB", "");
}
});
group.FieldsCount = _.size(group.FieldCollection);
/*get title of Group*/
var titleField = _.find(allFields, function (field) {
return (field.name.toUpperCase() == "SHORTNAME" && field.title != "");
});
if (titleField != null)
group.FieldShortName = titleField.title;
else
group.FieldShortName = '';
$scope.onReadyStyles = "visible";
$scope.ReadyData = true;
});
$scope.groupCollection = _.sortBy($scope.groupCollection, function (group) {
return group.SortOrder;
});
});
}
});
}
});
});
}
FieldStyleFabric.FieldsStyleData("allIndices", function (fieldStyles) {
$scope.fieldStyleCollection = fieldStyles;
});
updateMarketData();
};
$scope.fieldStyles = function (secid, field, groupId) {
try {
var value = StringHelper.FixedNumber($scope.fieldValue(secid, field, groupId));
if (value == '')
return '';
return FieldStyleFabric.FieldStyleGet(field.name, value, $scope.fieldStyleCollection);
}
catch (err) {
return '';
}
};
$scope.fieldValue = function (secid, field, groupId) {
try {
if (field == undefined || secid == undefined || groupId == undefined)
return '';
var values = _.filter($scope.MarketData, function (data) {
return data.SECID.toUpperCase() == secid.toUpperCase();
});
var value = '';
//get data from history
if (values == undefined || values.length < 1) {
values = _.filter($scope.History, function (data) {
return data.SECID.toUpperCase() == secid.toUpperCase();
});
var newField;
_.each($scope.groupFields, function (group) {
if (group.IssGroupId == groupId) {
newField = _.find(group.FieldCollection, function (data) {
return field.name == data.IssFieldId;
});
}
});
field = newField.HistoryIssFieldId;
} else {
field = field.name;
}
if (field === "VALTODAY") {
switch (secid) {
case "RTSI":
field = "VALTODAY_USD";
break;
case "RTS2":
field = "VALTODAY_USD";
break;
case "RUBMI":
field = "VALTODAY_USD";
break;
case "RTSog":
field = "VALTODAY_USD";
break;
case "RTSeu":
field = "VALTODAY_USD";
break;
case "RTStl":
field = "VALTODAY_USD";
break;
case "RTSmm":
field = "VALTODAY_USD";
break;
case "RTSin":
field = "VALTODAY_USD";
break;
case "RTSfn":
field = "VALTODAY_USD";
break;
case "RTScr":
field = "VALTODAY_USD";
break;
case "RTSch":
field = "VALTODAY_USD";
break;
case "RTStn":
field = "VALTODAY_USD";
break;
case "MCFTR":
field = "VALTODAY";
break;
case "MCFTRN":
field = "VALTODAY";
break;
case "MCFTRR":
field = "VALTODAY";
break;
case "RTSTR":
field = "VALTODAY_USD";
break;
case "RTSTRN":
field = "VALTODAY_USD";
break;
case "RTSTRR":
field = "VALTODAY_USD";
break;
}
}
if (field == "UPDATETIME") { field = "TIME"; }
if (values[0][field] != undefined) {
value = values[0][field];
}
else if (values[1][field] != undefined) {
value = values[1][field];
}
return value;
}
catch (err) {
return '';
}
};
$scope.indexCardUrlPrefix = function () {
return '/' + window.page.lang() + '/index';
};
var totalReturnIndicesRoot = 'MCFTR,RTSTR,MEBCTR,MESMTR,RUSMTR,MEOGTR,RUOGTR,RUEUTR,MEEUTR,METLTR, MERETR,RURETR,MEITTR,RUITTR,RUTLTR,RUMMTR,MEMMTR,MEFNTR,RUFNTR,RUCNTR,MECNTR,RUCHTR,MECHTR,METNTR,RUTNTR'.split(',');
var totalReturnIndices = null;
$scope.urlEncode = function (indexCardUrl, secid) {
if (totalReturnIndices){
;
}
else {
totalReturnIndices = [];
_.each(totalReturnIndicesRoot, function(tr){
totalReturnIndices.push(tr);
totalReturnIndices.push(tr + "R");
totalReturnIndices.push(tr + "N");
});
}
var find = _.find(totalReturnIndices, function(tr){
return (tr === secid);
});
if (find){
var trSecId = secid;
if (_.find(totalReturnIndicesRoot, function(tr){
return tr === trSecId;
})){
;
}
else {
trSecId = trSecId.substring(0, trSecId.length - 1);
}
return '/' + window.page.lang() + '/index/totalreturn/' + trSecId;
}
return indexCardUrl + '/' + secid;
};
$scope.fieldValueFormat = function (secid, field, groupId) {
var value = $scope.fieldValue(secid, field, groupId);
///////////////////////
if (field.name == "TIME") {
var isTimeToDate = false;
angular.forEach($scope.groupCollection, function (pItem) {
if (pItem.Id == 21) {
angular.forEach(pItem.SubGroupCollection, function (item) {
if (item.Id == 24) {
angular.forEach(item.IndicesCollection, function (it) {
switch (it.id) {
case 38: // Дополнительные индексы государственных облигаций
case 39: // Дополнительные индексы корпоративных облигаций
case 40: // Дополнительные индексы муниципальных облигаций
var c = _.find(it.SubIndicesCollection, { secid: secid });
if (c != null) {
isTimeToDate = true;
}
break;
}
});
}
});
}
});
if (isTimeToDate) {
var c = _.find($scope.History, { SECID: secid });
if (c != null) {
value = c.TRADEDATE;
field.type = "date";
}
}
}
///////////////////////
if (field.name === "CALCMODE") {
if (value === "CP") {
value = window.page.ru() ? "ценовой" : "Clean Price";
}
else if (value === "TR" || value === "") {
value = window.page.ru() ? "совокупный доход" : "Total Return";
}
}
if (value != undefined && value.length != 0) {
if (field.type != undefined) {
if (field.type.toLowerCase() == "number") {
value = StringHelper.ConvertCurrencyToFormat(value, $scope.Lang, '');
} else if (field.type.toLowerCase() == "date") {
value = StringHelper.ConvertDateToFormat(value);
}
}
if (field.postfix != undefined)
value = value + field.postfix;
} else {
value = '-';
}
return value;
};
$scope.showIndices = function (subGroup, showAll) {
subGroup.ShowAll = !showAll;
if (window.page.ru($scope.Lang)) {
if (subGroup.ShowAll)
subGroup.ButtonTitle = subGroup.HideButtonTitleRu;
else
subGroup.ButtonTitle = subGroup.ShowButtonTitleRu;
}
if (window.page.en($scope.Lang)) {
if (subGroup.ShowAll)
subGroup.ButtonTitle = subGroup.HideButtonTitleEn;
else
subGroup.ButtonTitle = subGroup.ShowButtonTitleEn;
}
};
$scope.getButtonClass = function (subGroup) {
if (subGroup.RowCount == 0 || subGroup.ShowAllIndices) {
return 'btnHide';
}
return '';
};
var firstColumnWidth = $('table.table_index th.index-first-column').width() || 150;
$scope.getStyleTH = function (FieldsCount, index, field, group) {
var result = {
width: $scope.getColumnWidth(FieldsCount, index, field, group)
};
if (field.name === 'LASTVALUE') {
result.display = 'none';
}
return result;
};
$scope.getStyleTD = function (FieldsCount, index, field, group) {
var result = {
width: $scope.getColumnWidth(FieldsCount, index, field, group)
};
if (field.name === 'LASTVALUE') {
result.display = 'none';
}
return result;
};
var _get_indices_offsetWidth = null;
var get_indices_offsetWidth = function(){
if (_get_indices_offsetWidth >= 0){
return _get_indices_offsetWidth;
}
_get_indices_offsetWidth = document.getElementById('indices').offsetWidth;
return _get_indices_offsetWidth;
};
$scope.getColumnWidth = function (FieldsCount, index, field, group) {
if (field && group) {
if (group.Id === 1) { //Индексы Акций
if (field.name === 'UPDATETIME') {
return '60px';
}
else if (field.name === 'MONTHCHANGEPRC') {
return '60px';
}
else if (field.name === 'YEARCHANGEPRC') {
return '60px';
}
else if (field.name === 'HIGH') {
return '60px';
}
else if (field.name === 'LOW') {
return '60px';
}
}
else if (group.Id === 43) { //Индикаторы РЕПО
if (field.name === 'SECID') {
//return '120px';
}
}
}
if (field) {
if (field.name === 'UPDATETIME') {
return '60px';
}
else if (field.name === 'CURRENTVALUE') {
return '70px';
}
else if (field.name === 'LASTVALUE') {
return '85px';
}
else if (field.name === 'CALCMODE') {
return '120px';
}
else if (field.name === 'CURRENCYID') {
return '55px';
}
else if (field.name === 'SECID') {
return '120px';
}
else if (field.name === 'VALTODAY') {
return '100px';
}
}
var divWidth = get_indices_offsetWidth();// document.getElementById('indices').offsetWidth;
if (index != FieldsCount - 1) {
return Math.round((divWidth - firstColumnWidth) / FieldsCount) + 'px';
}
return '';
};
$scope.getColumnStyle = function (field) {
var result = {};
if (field) {
if (field.name === 'CALCMODE') {
result["text-align"] = 'left';
}
else if (field.name === 'SECID') {
result["text-align"] = 'center';
}
else if (field.name === 'UPDATETIME') {
result["text-align"] = 'center';
}
}
return result;
};
var ru = window.page.ru();
$scope.fieldTitle = function (field, small) {
if (field.name === "HIGH") {
return ru ? 'Макс' : 'Max'; // field.title;
}
else if (field.name === "LOW") {
return ru ? 'Мин' : 'Min'; //field.title;
}
else if (field.name === "LASTCHANGEPRC") {
return ru ? 'Изм. к закрытию,%' : field.title;
}
else if (field.name === "UPDATETIME") {
return ru ? 'Время обнов.' : field.title;
}
small = small === true;
if (!small) {
return (field.title || "").replace(', %', ',%');
}
//console.log(field);
return (field.title || "").replace(', %', ',%');
};
}]);