Virtonomica:Notes

Система добавления и показа оповещений

当前为 2014-06-23 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Virtonomica:Notes
  3. // @namespace Virtonomica
  4. // @description Система добавления и показа оповещений
  5. // @version 0.17
  6. // @include http://*virtonomic*.*/*/main/unit/view/*
  7. // @include http://*virtonomic*.*/*/main/company/view/*/unit_list
  8. // ==/UserScript==
  9. var run = function() {
  10. var win = (typeof(unsafeWindow) != 'undefined' ? unsafeWindow : top.window);
  11. $ = win.$;
  12.  
  13. /**
  14. * записать данные в локальнео хранилище, с проверкой ошибок
  15. */
  16. function ToStorage(name, val)
  17. {
  18. try {
  19. window.localStorage.setItem( name, JSON.stringify( val ) );
  20. } catch(e) {
  21. out = "Ошибка добавления в локальное хранилище";
  22. //console.log(out);
  23. }
  24. }
  25.  
  26. function getFromStorage(obj, id_shop)
  27. {
  28. if (obj[id_shop] == null) return '';
  29. return JSON.stringify(obj[id_shop]);
  30. }
  31.  
  32. /**
  33. * Добавить заметку к текущему предприятию
  34. * следует вызывать на страницах где одно подраздление, ИД которого виден в url
  35. *
  36. * @param msg текст сообщения, можно использовать html теги
  37. */
  38. function addNotes( msg ){
  39. // объект для хранения сообщений
  40. notes = JSON.parse( window.localStorage.getItem('notes') );
  41. if ( notes == null ) notes = new Object();
  42.  
  43. // Идентификатор подразделения
  44. var id = /(\d+)/.exec(location.href)[0];
  45. var head = $("#headerInfo");
  46. var title = $("h1", head).text();
  47.  
  48. head = $("div.officePlace");
  49. var type = head.text();
  50. var nn = type.indexOf("компании");
  51. if (nn > 0){
  52. type = type.substring(0, nn);
  53. var ptrn = /\s*((\S+\s*)*)/;
  54. type = type.replace(ptrn, "$1");
  55. ptrn = /((\s*\S+)*)\s*/;
  56. type = type.replace(ptrn, "$1");
  57. } else {
  58. type = '';
  59. }
  60.  
  61. if ( notes[id] == null ) notes[id] = new Object();
  62.  
  63. var d = new Date();
  64.  
  65. if ( notes[id]['text'] != null) {
  66. // сообщение для этого подраздления уже есть
  67. msg = notes[id]['text'] + "<br>" + msg;
  68. }
  69.  
  70. notes[id]['text'] = msg;
  71. // Количество миллисекунд
  72. notes[id]['time'] = d.getTime();
  73. notes[id]['name'] = title;
  74. notes[id]['type'] = type;
  75.  
  76. ToStorage('notes', notes);
  77. }
  78.  
  79. var txt = "<table><tr><td><td><table width=100%><tr><td align=rigth id=notes_title><td align=center><h3>Напоминания</h3></table><td>&nbsp;"
  80. +"<tr><td>&nbsp;<td align=center id=notes_form>&nbsp;<td>&nbsp;"
  81. +"<tr><td colspan=3></table>";
  82. var div_form = "<div id=notes style='background: none repeat scroll 0% 0% rgb(223, 223, 223); z-index: 1002; position: absolute; border: 1px solid rgb(0, 0, 0); display: none;'>" + txt + "</div>";
  83.  
  84. var div_export = "<div id=notes_export style='background: none repeat scroll 0% 0% rgb(223, 223, 223); z-index: 1003; position: absolute; border: 1px solid rgb(0, 0, 0); display: none;'>"
  85. + "<h3>Данные экспорта</h3>"
  86. + "<table><tr><td>&nbsp;<td>"
  87. + "<textarea name=export_text id=export_text rows=10 cols=64></textarea>"
  88. + "<br><center><span id=export_load></span></center>"
  89. + "</table>";
  90. + "</div>";
  91.  
  92. var tu = $("table.unit-list-2014");
  93. if (tu.length == 1) {
  94. // Это у нас список подразделений - рисуем кнопку отображения отчета со сылками
  95. // Оповещения
  96. notes = JSON.parse( window.localStorage.getItem('notes') );
  97. if ( notes == null ) notes = new Object();
  98. var len = 0;
  99.  
  100. // проверить, какие оповещения отразить как актуальные
  101. for (key in notes){
  102. len++;
  103. }
  104.  
  105. // http://cdn1.iconfinder.com/data/icons/Upojenie_by_SoundForge/Icons/Notes.png
  106. // http://www.iconsearch.ru/uploads/icons/crystalclear/24x24/kedit.png
  107.  
  108. var wc = $("<li><div id=main_notes style='float:left;cursor:pointer; color: white;'> <img alt='Список напоминаний' src=http://cdn1.iconfinder.com/data/icons/humano2/32x32/apps/gnome-sticky-notes-applet.png> <span id=all_notes> ("+ len+")</span></div>").click( function() {
  109. $("#notes").toggle();
  110. if( $('#notes').is(':visible') ) {
  111. // код для visible
  112. // Оповещения
  113. notes = JSON.parse( window.localStorage.getItem('notes') );
  114. if ( notes == null ) notes = new Object();
  115.  
  116. // Формируем ссылку на торговый зал
  117. var url = /^http:\/\/virtonomic[as]\.(\w+)\/\w+\//.exec(location.href)[0];
  118. console.log(url);
  119.  
  120. var all_count = 0;
  121. $("#notes_form").html('');
  122. var out = $("<table>");
  123. for (key in notes){
  124. if (notes[key] == null) continue;
  125. if (notes[key]['time'] == null) continue;
  126.  
  127. // подсчитываем сколько у нас оповещениий
  128. // TODO - учитывать только акутальные
  129. all_count++;
  130.  
  131. var d = new Date();
  132. d.setTime(notes[key]['time']);
  133.  
  134. link = "<a href=" + url + "main/unit/view/" + key + ">" + notes[key]['name'] + "</a>";
  135. span = $("<span name=" + key + " style='cursor:pointer;' title='del'><font color=red><b>Х</b></font></span>").click(
  136. function(){
  137. idp = $(this).attr('name');
  138. //alert('del = ' + idp);
  139. delete notes[idp];
  140. ToStorage('notes', notes);
  141. $("#main_notes").click().click();
  142. });
  143.  
  144. out_tr = $("<tr>");
  145. out_tr.append("<td>" + d.toLocaleDateString())
  146. .append("<td>" + link)
  147. .append("<td>(" + notes[key]['type'] + ")")
  148. .append("<td style='border: 1px solid gray; border-radius: 4px 4px 4px 4px; box-shadow: 0 1px 3px 0 #999999; display: block; float: left; margin-top: 4px; overflow: hidden; padding: 2px 4px; text-align:left'>" + notes[key]['text'])
  149. .append("<td>").append(span);
  150. out.append(out_tr);
  151. str = "(" + all_count +")";
  152. if (all_count == 0) str = '';
  153. $("#all_notes").html("(" + all_count +")");
  154. }
  155. $("#notes_form").html( out );
  156.  
  157. }
  158. });
  159.  
  160. // http://cdn1.iconfinder.com/data/icons/basicset/save_32.png
  161. // http://www.iconsearch.ru/uploads/icons/ultimategnome/48x48/stock_export.png
  162. var wc_export = $("<span id=main_notes_export style='cursor:pointer; color: white;'><img src=http://cdn1.iconfinder.com/data/icons/basicset/save_32.png title='Окно экспорта/импорта' alt='Окно экспорта/импорта'></span>").click( function() {
  163. $("#export_text").val( JSON.stringify( notes ) );
  164. $("#notes_export").toggle();
  165. });
  166.  
  167. // http://cdn1.iconfinder.com/data/icons/freeapplication/png/24x24/Load.png
  168. // http://www.iconsearch.ru/uploads/icons/freeapplication/24x24/load.png
  169. var wc_load = $("<img src=http://cdn1.iconfinder.com/data/icons/freeapplication/png/24x24/Load.png title='Импортировать данные из окна' alt='Импортировать данные из окна'>").click( function() {
  170. //alert("Load");
  171. var text = $("#export_text").val() ;
  172. try {
  173. notes = JSON.parse( text );
  174. ToStorage('notes', notes);
  175. $("#notes_export").hide();
  176. $("#main_notes").click().click();
  177. } catch(e) {
  178. alert("Неверные данным для импорта");
  179. }
  180. });
  181.  
  182. var container = $('ul.tabu');
  183. container.append( wc );
  184.  
  185. $("table.unit-top").before ( div_form);
  186. //container.append( div_form );
  187. //var container = $('#topblock');
  188. //container.append( $('<table><tr><td>').append(wc) );
  189. //container.append( div_form );
  190. $("#notes_title").append(wc_export).append( div_export );
  191. $("#export_load").append(wc_load);
  192.  
  193.  
  194. return;
  195. }
  196.  
  197. // Идентификатор подразделения
  198. var id = /(\d+)/.exec(location.href)[0];
  199.  
  200. var head = $("#headerInfo");
  201. var title = $("h1", head).text();
  202.  
  203. head = $("div.officePlace");
  204. var type = head.text();
  205. var nn = type.indexOf("компании");
  206. if (nn > 0){
  207. type = type.substring(0, nn);
  208. var ptrn = /\s*((\S+\s*)*)/;
  209. type = type.replace(ptrn, "$1");
  210. ptrn = /((\s*\S+)*)\s*/;
  211. type = type.replace(ptrn, "$1");
  212. } else {
  213. type = '';
  214. }
  215. // Оповещения
  216. notes = JSON.parse( window.localStorage.getItem('notes') );
  217. if ( notes == null ) notes = new Object();
  218. if ( notes[id] == null) notes[id] = new Object();
  219.  
  220. notes_html = "";
  221. if ( notes[id]['text'] != null) notes_html = notes[id]['text'];
  222.  
  223. var form = "";
  224. form += "<span id=notes_error style='color:red;'></span><br>";
  225. form+= ("<div id=notes_preview style='border: 1px solid gray; border-radius: 4px 4px 4px 4px; box-shadow: 0 1px 3px 0 #999999; display: block; float: left; margin-top: 4px; overflow: hidden; padding: 2px 4px; text-align:left'>" + notes_html +"</div>");
  226. form += " <textarea name=notes_txt id=notes_txt rows=5 cols=48>";
  227. form += notes_html;
  228. form+= "</textarea><br>";
  229.  
  230. var form_button = $("<button id=notes_btn>сохранить</button>").click( function() {
  231. $("#notes_error").text('');
  232. var text = $("#notes_txt").val() ;
  233. $("#notes_preview").html( text );
  234. if (text == '') {
  235. $("#notes_error").text('Ошибка - нет описания');
  236. return;
  237. }
  238.  
  239. var d = new Date();
  240. // Оповещения
  241. notes = JSON.parse( window.localStorage.getItem('notes') );
  242. if ( notes == null ) notes = new Object();
  243.  
  244. if ( notes[id] == null) notes[id] = new Object();
  245.  
  246. notes[id]['text'] = text;
  247. notes[id]['time'] = d.getTime();
  248. notes[id]['name'] = title;
  249. notes[id]['type'] = type;
  250.  
  251. ToStorage('notes', notes);
  252. $("#notes").toggle();
  253. });
  254.  
  255. var form_button_del = $(" <button>Удалить</button>").click( function() {
  256. // Оповещения
  257. notes = JSON.parse( window.localStorage.getItem('notes') );
  258. if ( notes == null ) notes = new Object();
  259.  
  260. if ( notes[id] == null) notes[id] = new Object();
  261.  
  262. $("#notes_txt").val("");
  263. $("#notes_preview").html( "" );
  264. delete notes[id];
  265. ToStorage('notes', notes);
  266. });
  267.  
  268. // http://cdn1.iconfinder.com/data/icons/oxygen/32x32/actions/document-new.png
  269. // http://www.iconsearch.ru/uploads/icons/ull_icons/24x24/message_add.png
  270. var wc = $("<li style='cursor:pointer; color: white;'><img alt='Добавить напоминание' src=http://cdn1.iconfinder.com/data/icons/oxygen/32x32/actions/document-new.png title='Добавить напоминание'> </li>").click( function() {
  271. $("#notes").toggle();
  272. // Обновить зампетку
  273. notes = JSON.parse( window.localStorage.getItem('notes') );
  274. if ( notes == null ) notes = new Object();
  275. if ( notes[id] == null) notes[id] = new Object();
  276.  
  277. if ( notes[id]['text'] == null ) return;
  278. $("#notes_txt").val( notes[id]['text'] );
  279. $("#notes_preview").html( notes[id]['text'] );
  280. });
  281.  
  282. //var container = $('#topblock');
  283. var container = $('#topblock').next();
  284.  
  285. if (tu.length == 0) {
  286. container = $("li:last", container).prev().parent();
  287. container.append(wc) ;
  288. //container.append( $('<table><tr><td>').append(wc) );
  289. $("#childMenu").before ( div_form);
  290.  
  291. $("#notes_form").append(form).append(form_button).append(form_button_del);
  292. }
  293. }
  294.  
  295. if(window.top == window) {
  296. var script = document.createElement("script");
  297. script.textContent = '(' + run.toString() + ')();';
  298. document.documentElement.appendChild(script);
  299. }