window.confirm = function (message, callback, caption) { caption = caption || '' $(document.createElement('div')).attr({ title: caption, 'class': 'dialog' }).html(message).dialog({ modal: true, resizable: false, height: "auto", width: 400, buttons: { "Отмена": function () { $(this).dialog('close'); return false; }, "OK": function () { $(this).dialog('close'); callback() return true; } }, close: function () { $(this).remove(); }, }); }; var SocketHandler = function () { domain = domain.replace(':' + port, ''); var url = 'ws://' + domain + '/chat/' + userId + '/'; var sock = new WebSocket(url); var intervalId; sock.onopen = function () { console.log("Start connect"); intervalId = setInterval(function () { sock.send('{"dummy": 1}'); }, 15000); }; sock.onmessage = function (event) { console.log(event.data); var message = JSON.parse(event.data); var inbox; if (message.answer_type == 'contact' || message.answer_type == 'add_message_contact') { var docSpace = document.getElementById('documentSpace'); docSpace.innerHTML += message.docs_attach; var sumSenderRecipent = parseInt(message.recipent_id) + parseInt(message.sender_id); var inboxClass = document.getElementsByClassName('contact-space' + sumSenderRecipent); if (inboxClass.length > 0) { inbox = inboxClass[0]; } else { $(".contact-count-" + sumSenderRecipent).text(parseInt($(".contact-count-" + sumSenderRecipent).text()) + 1); } } else if (message.answer_type == 'order' || message.answer_type == 'add_message_order') { inbox = document.getElementById('message-chat-order-space'); var docOrderSpace = document.getElementById('documentOrderSpace'); docOrderSpace.innerHTML += message.docs_attach; } else if (message.answer_type == 'add_message_team') { inbox = document.getElementById('message-chat-team-space'); var docSpace = document.getElementById('documentTeamSpace'); docSpace.innerHTML += message.docs_attach; } else if (message.answer_type == 'approve_stages') { var resOrderId = message.order_id; $.jGrowl(message.msg, { life: 4000 }); setTimeout(function () { $("#orderBlock" + resOrderId).trigger('click'); }, 200); } if (inbox) { var textMessage = message.msg; var classMessage = 'youChat'; var senderName = 'Вы'; var timeMessage = message.msg_time; if (message.sender_id != userId) { senderName = message.sender_name; classMessage = ''; } inbox.innerHTML += '
' + '

' + senderName + '

' + timeMessage + '
' + '

' + textMessage + '

'; var height = inbox.scrollHeight; inbox.scrollTop = height; } }; this.send_stages_approve = function (data) { sock.send(JSON.stringify(data)); }; this.send_message = function (messageData) { sock.send(JSON.stringify(messageData)); } } function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } var socket = new SocketHandler(); var csrftoken = getCookie('csrftoken'); function test_dialog(message){ var resStatus; $("#dialog_delete .modal-title").html(message); $("#dialog_delete").modal('show'); $("#btnYes").click(function (e) { $("#dialog_delete").modal('hide'); resStatus = true; }); $("#btnNot").click(function (e) { $("#dialog_delete").modal('hide'); resStatus = false; }); return resStatus; } $(function () { function dialog (message, yesCallback, notCallback) { $("#dialog_delete .modal-title").html(message); $("#dialog_delete").modal('show'); $("#btnYes").click(function (e) { e.preventDefault(); yesCallback(); $("#dialog_delete").modal('hide'); }); $("#btnNot").click(function (e) { e.preventDefault(); notCallback(); $("#dialog_delete").modal('hide'); }); } var currentHash = URI(location.href).hash(); $('a[data-toggle="tab"]').on('show.bs.tab', function (e) { var activeTab = $(this).attr('href').substring(1); var liveHash = URI(location.href).hash(); switch (activeTab) { case 'tab1': setTimeout(function () { if (liveHash.indexOf("#user") == 0) { var userHashId = liveHash.replace("#user", ""); $("#userBlock" + userHashId).trigger('click'); } else { $(".user-block").first().trigger('click'); } }, 100); break; case 'tab2': setTimeout(function () { if (liveHash.indexOf("#order") == 0) { var ordHashId = liveHash.replace("#order", ""); $("#orderBlock" + ordHashId).trigger('click'); } else { $(".order-block").first().trigger('click'); } }, 100); break; case 'tab3': setTimeout(function () { if (liveHash.indexOf("#teamorder") == 0) { var teamHashId = liveHash.replace("#teamorder", ""); $("#teamOrderBlock" + teamHashId).trigger('click'); } else if (liveHash.indexOf("#myteam") == 0) { var teamHashId = liveHash.replace("#myteam", ""); $("#teamMyBlock" + teamHashId).trigger('click'); } else { var firstTeamBlock = $(".team-block").first(); var firstTeamOrder = $(".team-order-block").first(); if (firstTeamOrder.length == 1) { firstTeamOrder.trigger('click'); } else if (firstTeamBlock.length == 1) { firstTeamBlock.trigger('click'); } } }, 100); } }); if (currentHash.indexOf("#order") == 0) { $("a[href='#tab2']").trigger('click'); } else if (currentHash.indexOf("#user") == 0) { $("a[href='#tab1']").trigger('click'); } else if (currentHash.indexOf("#teamorder") == 0 || currentHash.indexOf("#myteam") == 0) { $("a[href='#tab3']").trigger('click'); } else { $("a[href='#tab1']").trigger('click'); } $("#trashed-button").on('click',function(e){ e.preventDefault(); var trashedOrderHtml = ""; $.ajax({ url: '/api/orders/', type: 'GET', dataType: 'json', success: function(json){ console.log(json.results); $.each(json.results, function(i, v){ var temp = '
' + '

'+ v.project.name +'

' + 'Исполнитель:

' + '' + 'Полное описание заказа
'; trashedOrderHtml += temp; }); $("#trashed-orders").html(trashedOrderHtml); }, error: function(e, jqxhr){ console.log(e); } }) }); // Информация о заказе $(".full-order-info").click('on', function (e) { e.preventDefault(); e.stopPropagation(); var orderId = $(this).closest('.orderBlock').attr('data-id'); $.ajax({ url: '/api/orders/' + orderId + '/', data: { csrfmiddlewaretoken: csrftoken, }, dataType: 'json', success: function (data) { var outTable = ''; outTable += 'Название' + data.project.name + ''; outTable += 'Безопасная сделка' + data.secure + ''; if (data.project.realty) { outTable += 'Тип здания' + data.project.realty.building_classification.name + ''; outTable += 'Классификация здания' + data.project.realty.construction_type.name + ''; } $("#order-info table").html(outTable); $("#order-info").modal('show'); }, error: function (e, jqxhr) { console.log(e); } }); }); $(".conMess").click('on', function (e) { e.preventDefault(); e.stopPropagation(); var userId = $(this).attr('data-id'); $.ajax({ url: '/api/users/' + userId + '/', data: { csrfmiddlewaretoken: csrftoken, }, dataType: 'json', success: function (data) { var outTable = ''; if (data.username) { outTable += 'Ник' + data.username + ''; } if (data.fio) { outTable += 'Ф.И.О' + data.fio + ''; } if (data.skype) { outTable += 'Skype' + data.skype + ''; } if (data.website) { outTable += 'Сайт' + data.website + ''; } if (data.phone) { outTable += 'Телефон' + data.phone + ''; } $("#contact-info table").html(outTable); $("#contact-info").modal('show'); console.log(data); }, error: function (e, jqxhr) { console.log(e); } }); }); $("#paymentfromSite").on('click', function () { var sum = $("#stageSumPay").val(); var stages = $("#stagesIds").val(); var orderId = $("#ordermodalId").val(); $.ajax({ url: '/wallets/payfromscore/', type: 'POST', data: { csrfmiddlewaretoken: csrftoken, sum: sum, stages_id: stages, }, dataType: 'json', success: function (json) { if (json.status == 'ok') { socket.send_stages_approve({ "format_type": "approve_stages", "data": { "sender_id": json.sender, "recipent_id": json.recipent, "order_id": json.order, "msg": "Заказчик зарезервировал сумму для этапов " + json.stages, } }); $("#reserve-stage-modal").modal('hide'); $("#orderBlock" + orderId).trigger('click'); } else if (json.status == 'error') { alert(json.message_error); } }, error: function (e, jqxhr) { console.log(e); console.log(jqxhr); } }) }); //Удаление документа $('.tab-content').on('click', '.remove-document', function (e) { e.preventDefault(); var dataId = $(this).attr('data-id'); var _this = $(this); $.ajax({ url: '/api/documents/' + dataId + '/', type: 'PATCH', beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) }, data: {is_delete: true}, dataType: 'json', success: function (json) { _this.parent().remove(); console.log(json); }, error: function (e, jqxhr) { console.log(jqxhr); } }); }); // Вытащить сообщения для конактов $('.user-block').on('click', function () { var contactId = $(this).attr('data-id'); location.hash = '#user' + contactId; $("#contact-chat-form #recipentContactId").val(contactId); $("#add-form-contractor-note #recipentNoteContractor").val(contactId); $('.user-block').each(function () { $(this).removeClass('mesAct'); }); $(this).addClass('mesAct'); var inbox = document.getElementById('message-chat-space'); var sumSenderRecipent = parseInt(userId) + parseInt(contactId); $("#message-chat-space").removeClass().addClass("contact-space" + sumSenderRecipent); $(".contact-count-" + sumSenderRecipent).text(0); var docList = document.getElementById('documentSpace'); inbox.innerHTML = ''; docList.innerHTML = ''; $.ajax({ url: '/api/message', type: 'GET', data: { csrfmiddlewaretoken: csrftoken, 'operand': 'in', 'sender_id': userId, 'recipent_id': contactId }, dataType: 'json', success: function (json) { $.each(json.results, function (i, v) { var senderName = 'Вы'; var className = 'youChat'; if (v.sender.id == contactId) { senderName = v.sender.username; className = ''; } inbox.innerHTML += '
' + '

' + senderName + '

' + v.created + '
' + '

' + v.text + '

'; }); var height = inbox.scrollHeight; inbox.scrollTop = height; } }); $.ajax({ url: '/api/documents', type: 'GET', data: { csrfmiddlewaretoken: csrftoken, 'operand': 'in', 'sender_id': userId, 'recipent_id': contactId, 'is_delete': false, 'is_send': true, }, dataType: 'json', success: function (json) { console.log(json); $.each(json.results, function (i, v) { docList.innerHTML += '
  • ' + v.file + '
  • '; }); }, error: function (e) { console.log(e); } }); $.ajax({ url: '/api/note/', type: 'GET', data: { csrfmiddlewaretoken: csrftoken, 'operand': 'in', 'sender_id': userId, 'recipent_id': contactId }, dataType: 'json', success: function (json) { console.log(json.results); var noteHtmlInbox = ''; $.each(json.results, function (i, v) { noteHtmlInbox += '
  • ' + v.text + '
  • '; }); $(".contractor-notes-block").html(noteHtmlInbox); } }); }); $('.deleteMess').on('click', function (e) { e.preventDefault(); e.stopPropagation(); var senderId = userId; var recipentId = $(this).attr('data-recipent-id'); var _this = $(this); dialog("Вы действительно хотите удалить сообщения этого пользователя?", function () { $.ajax({ url: '/chat/messages_delete/', type: 'POST', beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) }, data: {'sender_id': senderId, 'recipent_id': recipentId}, dataType: 'json', success: function (json) { if (json.status == 'ok') { _this.parent().remove(); $("#message-chat-space").html(""); } }, error: function (e) { console.log('error'); console.log(e); } }); }.bind(null, senderId, recipentId, _this), function () { }); }); $('.deleteOrder').on('click', function (e) { e.preventDefault(); e.stopPropagation(); var senderId = userId; var projectId = $(this).attr('data-project-id'); var _this = $(this); dialog("Вы действительно хотите удалить этот заказ?", function () { $.ajax({ url: '/chat/project/trashed/', type: 'POST', beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) }, data: {'project_id': projectId}, dataType: 'json', success: function (json) { if (json.status == 'ok') { _this.parent().parent().remove(); $("#message-chat-space").html(""); } }, error: function (e) { console.log('error'); console.log(e); } }); }.bind(null, senderId, projectId), function () { }); }); $('#add-note-contractor').on('click', function (e) { e.preventDefault(); $.ajax({ url: '/api/note/', type: 'POST', beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) }, data: $("#add-form-contractor-note").serialize(), dataType: 'json', success: function (json) { console.log(json); $("#add-form-contractor-note #chat2").val(""); $('
  • ' + json.text + '
  • ').appendTo(".contractor-notes-block"); }, error: function (e) { console.log('error'); console.log(e); } }); }); //Добавить заметку. $('#add-note-button').on('click', function (e) { e.preventDefault(); $.ajax({ url: '/api/note/', type: 'POST', beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) }, data: $("#add-form-order-note").serialize(), dataType: 'json', success: function (json) { $("
  • " + json.text + "
  • ").appendTo(".order-notes-block"); $("#add-form-order-note #chat2").val(""); }, error: function (e) { console.log('error'); console.log(e); } }); }); //Добавить заметку. $('#add-team-note-button').on('click', function (e) { e.preventDefault(); $.ajax({ url: '/api/note/', type: 'POST', beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) }, data: $("#add-form-team-note").serialize(), dataType: 'json', success: function (json) { $("
  • " + json.text + "
  • ").appendTo(".team-notes-block"); $("#add-form-team-note #chat2").val(""); }, error: function (e) { console.log('error'); console.log(e); } }); }); // Добавление сообщения для заказа. $('#order-chat-add-message').on('click', function (e) { e.preventDefault(); var chatMessage = $("#chat-order-add #chat").val(); var recipentId = $("#chat-order-add #recipentId").val(); var senderId = $("#chat-order-add #senderId").val(); var orderId = $("#chat-order-add #orderId").val(); if (chatMessage) { var sendLinks = $("#document-send-order a"); var sendLinkIds = ""; var documentLinks = ""; var documentAttachFiles = ""; $.each(sendLinks, function (i, v) { sendLinkIds += $(this).attr('data-id') + ';'; documentLinks += 'Входящий файл:
    '+ $(this).text() +'
    '; documentAttachFiles += '
  • ' + '' + $(this).text() + '' + '
  • '; }); socket.send_message({ "format_type": "add_message_order", "data": { "sender_id": senderId, "recipent_id": recipentId, "chat_message": chatMessage, "order_id": orderId, "document_send_links": sendLinkIds, "document_data": { "document_links": documentLinks, "document_attach_files": documentAttachFiles, } } }); $("#chat-order-add #chat").val(""); $("#document-send-order").html(""); } else { $("#chat-order-add .errorEmptyMessage").show(); } }); // Добавление сообщения для контакта $('#contact-chat-add-message').on('click', function (e) { e.preventDefault(); var chatMessage = $("#chat").val(); var recipentId = $("#recipentContactId").val(); var senderId = $("#senderContactId").val(); if (chatMessage) { $("#contact-chat-form .errorEmptyMessage").hide(); var sendLinks = $("#document-send-contact a"); var sendLinkIds = ""; var documentLinks = ""; var documentAttachFiles = ""; $.each(sendLinks, function (i, v) { sendLinkIds += $(this).attr('data-id') + ';'; documentLinks += 'Входящий файл:
    '+ $(this).text() +'
    '; documentAttachFiles += '
  • ' + '' + $(this).text() + '' + '
  • '; }); console.log(sendLinkIds); socket.send_message({ "format_type": "add_message_contact", "data": { "sender_id": senderId, "recipent_id": recipentId, "chat_message": chatMessage, "document_send_links": sendLinkIds, "document_data": { "document_links": documentLinks, "document_attach_files": documentAttachFiles, } } }); $("#chat").val(""); $("#document-send-contact").html(""); } else { $("#contact-chat-form .errorEmptyMessage").show(); } }); // Добавление отзыва $('#order-review-add').on('click', function (e) { e.preventDefault(); e.stopPropagation(); var formData = $("#review-adds-form").serialize(); $.ajax({ url: '/api/reviews/', type: 'POST', beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) }, data: formData, dataType: 'json', success: function (json) { console.log("Успешно"); $("#review-add").modal('hide'); $.jGrowl("Ваш отзыв успешно добавлен", { life: 4000 }); }, error: function (e) { console.log('error'); console.log(e); } }); }); // Добавление сообщения в арбитраж $('#order-arbitration-add').on('click', function (e) { e.preventDefault(); e.stopPropagation(); var formData = $("#arbitration-add-form").serialize(); $.ajax({ url: '/projects/arbitration/create/', type: 'POST', beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) }, data: formData, dataType: 'json', success: function (json) { console.log(json); $("#arbitration-add").modal('hide'); $.jGrowl("Обращение в арбитраж добавлено", { life: 4000 }); }, error: function (e) { console.log('error'); console.log(e); } }); }); $("#upload-document-order").bind('fileuploadsubmit', function (e, data) { data.formData = { sender: $("#chat-order-add #senderId").val(), recipent: $("#chat-order-add #recipentId").val(), order: $("#chat-order-add #orderId").val(), } console.log(data.formData); }); //Загрузка документов $('#upload-document-order').fileupload({ url: '/chat/create/', crossDomain: false, beforeSend: function (xhr, settings) { $('#progress .progress-bar').css( 'width', '0%' ); if (!csrfSafeMethod(settings.type)) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, dataType: 'json', done: function (e, data) { $.each(data.result.files, function (index, file) { var htmlImg = '' + file.name + '

    '; var document_send = $(htmlImg).appendTo("#document-send-order"); }); }, fail: function (e) { console.log(e); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .progress-bar').css( 'width', progress + '%' ); } }).prop('disabled', !$.support.fileInput) .parent().addClass($.support.fileInput ? undefined : 'disabled'); //Загрузка документов $("#upload-document-contact").bind('fileuploadsubmit', function (e, data) { data.formData = { sender: $("#contact-chat-form #senderContactId").val(), recipent: $("#contact-chat-form #recipentContactId").val(), } }); $('#upload-document-contact').fileupload({ url: '/chat/create/', crossDomain: false, beforeSend: function (xhr, settings) { console.log(this.formData); $('#progress .progress-bar').css( 'width', '0%' ); if (!csrfSafeMethod(settings.type)) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, dataType: 'json', done: function (e, data) { $.each(data.result.files, function (index, file) { var htmlImg = '' + file.name + ''; var document_send = $(htmlImg).appendTo("#document-send-contact"); }); }, fail: function (e) { console.log(e); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .progress-bar').css( 'width', progress + '%' ); } }).prop('disabled', !$.support.fileInput) .parent().addClass($.support.fileInput ? undefined : 'disabled'); $('#review-add').on('show.bs.modal', function (e) { var related = $(e.relatedTarget); var relatedType = related.attr('data-review-type'); $('input[name="type"]').filter('[value="'+ relatedType+'"]').prop("checked", true); }); });