diff --git a/api/urls.py b/api/urls.py index ecce484..89e3656 100755 --- a/api/urls.py +++ b/api/urls.py @@ -23,6 +23,7 @@ from .views import ( SpecializationViewSetFlat, ConstructionTypeViewSet, StageViewSet, + StageUpdateViewSet, TeamViewSet, UserViewSet, WorkSellPhotoViewSet, @@ -58,8 +59,9 @@ router.register(r'work-sells', WorkSellViewSet) urlpatterns = router.urls -# urlpatterns = [ -# url(r'^demo_realties/(?P\d+)/$', UpdateRealty.as_view()), -# ] +urlpatterns = [ + url(r'^update_stages/$', StageUpdateViewSet.as_view()), + # url(r'^orders/(?P\d+)/$', OrderViewSet.as_view({'delete'})), +] -# urlpatterns += router.urls \ No newline at end of file +urlpatterns += router.urls \ No newline at end of file diff --git a/api/views.py b/api/views.py index a6b3db5..5d9e311 100755 --- a/api/views.py +++ b/api/views.py @@ -1,11 +1,13 @@ from django.conf import settings from django.db.models import Q, F +from django.http import Http404 from rest_framework import permissions from rest_framework.pagination import PageNumberPagination from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import detail_route, list_route from rest_framework.response import Response from rest_framework import generics +from rest_framework import status from chat.filters import MessageFilterSet, NoteFilterSet, DocumentFilterSet from chat.models import Message, Notes, Documents, NewMessage @@ -22,7 +24,7 @@ from projects.models import (Project, Realty, Stage, Portfolio, PortfolioPhoto, from projects.serializers import ( ProjectSerializer, RealtySerializer, StageSerializer, PortfolioSerializer, PortfolioPhotoSerializer, AnswerSerializer, OrderSerializer, BuildingClassificationSerializeFlat, - ConstructionTypeSerializer) + ConstructionTypeSerializer, StageListSerializer) from reviews.filters import ReviewFilterSet from reviews.models import Review from reviews.serializers import ReviewSerializer @@ -59,6 +61,31 @@ class StageViewSet(ModelViewSet): permission_classes = (permissions.IsAuthenticatedOrReadOnly,) +class StageUpdateViewSet(generics.UpdateAPIView): + # def __init__(self, *args, **kwargs): + # many = kwargs.pop('many', True) + # super().__init__(many=many, *args, **kwargs) + model = Stage + queryset = model.objects.all() + serializer_class = StageSerializer + + def put(self, request, *args, **kwargs): + # print("put request = ", request.data) + print(request.data) + result = request.data + print("result = ", result) + # ids = [obj["id"] for obj in result] + # queryset = self.model.objects.filter(pk__in=ids) + # print("count = ", queryset.count()) + serializer = self.serializer_class(data=result, many=True) + serializer.is_valid() + serializer.save() + # print("serializer = ", serializer) + return Response(serializer.data, status=status.HTTP_200_OK) + # print("errors = ", serializer.errors) + # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + class ReviewViewSet(ModelViewSet): queryset = Review.objects.all() serializer_class = ReviewSerializer @@ -231,6 +258,19 @@ class OrderViewSet(ModelViewSet): filter_class = OrderFilterSet permission_classes = (permissions.IsAuthenticatedOrReadOnly,) + def destroy(self, request, *args, **kwargs): + print("destroy request = ", request, 'args = ', args, 'kwargs = ', kwargs) + try: + instance = self.get_object() + project = instance.project + project.state = 'deleted' + project.save() + # self.perform_destroy(instance) + print('inst = ', instance) + except Http404: + pass + return Response(status=status.HTTP_204_NO_CONTENT) + class SpecializationViewSet(ModelViewSet): try: # TODO: dirty diff --git a/archilance/urls.py b/archilance/urls.py index 0028bca..9745da0 100644 --- a/archilance/urls.py +++ b/archilance/urls.py @@ -22,7 +22,7 @@ urlpatterns = [ url(r'^projects/', include('projects.urls')), url(r'^object/(?P\d+)/trash/$', CustomerRealtyTrashView.as_view(), name='customer-object-trash'), url(r'^object/(?P\d+)/delete/$', CustomerRealtyDeleteView.as_view(), name='customer-object-delete'), - url(r'^object/(?P\d+)/edit/$', RealtyUpdateView.as_view(), name='customer-object-delete'), + url(r'^object/(?P\d+)/edit/$', RealtyUpdateView.as_view(), name='customer-object-edit'), url(r'^object/(?P\d+)/restore/$', CustomerRealtyRestoreView.as_view(), name='customer-object-restore'), url(r'^objects/sort/$', SortRealtyBy.as_view(), name='sort-realty-by'), url(r'^reviews/', include('reviews.urls')), diff --git a/assets/css/extra.css b/assets/css/extra.css index f2b4ec5..d9d2a3b 100644 --- a/assets/css/extra.css +++ b/assets/css/extra.css @@ -72,18 +72,6 @@ margin: 0; } -.stepssBlock ul li.reserved::before { - background: rgba(0, 0, 0, 0) url("../img/reserved2.png") no-repeat scroll center center / cover; - height: 16px; - width: 17px; -} - -.stepssBlock ul li.unreserved::before { - background: rgba(0, 0, 0, 0) url("../img/reserved.png") no-repeat scroll center center / cover; - height: 14px; - width: 13px; -} - .chat-textarea { width: 100%; height: 110px; @@ -135,7 +123,7 @@ } .documentsChat > p { - font-size: 20px; + font-size: 16px; } #message-chat-order-space, #message-chat-team-space { @@ -229,6 +217,26 @@ background-color: #ebebeb; } +.count-order { + display: inline-block; + margin-left: 5px; + margin-right: 5px; + width: 20px; + height: 20px; + border-radius: 100%; + line-height: 20px; + text-align: center; + font-size: 10px; + font-family: 'Arial-MT-Regular', sans-serif; + /*position: absolute;*/ + /*top: 14px;*/ + cursor: pointer; + -webkit-transition: all 0.3s ease-out; + -moz-transition: all 0.3s ease-out; + transition: all 0.3s ease-out; + background-color: #ebebeb; +} + li a:active .count-tab, li a:hover .count-tab { background-color: #FF0027; color: white; diff --git a/assets/css/main.css b/assets/css/main.css index 4bbeb2f..5b1dfdc 100644 --- a/assets/css/main.css +++ b/assets/css/main.css @@ -501,15 +501,6 @@ a, a:hover, a:focus, a:active { float: right !important; } -.triangle1 { - position: absolute; - border: 30px solid transparent; - border-top: 17px solid white; - top: 0; - left: 50%; - margin-left: -30px; -} - footer { width: 100%; position: relative; @@ -1964,8 +1955,8 @@ footer:after { font-family: 'pfbeausanspro-reg', sans-serif; position: relative; text-align: left; - padding: 22px 61px 22px 21px; - height: 94px; + padding: 20px 61px 20px 21px; + /*height: 94px;*/ } .profileTabs2 ul .active a:after { @@ -2423,6 +2414,15 @@ footer:after { margin: 32px 0 50px 4px; } +.triangle1 { + position: absolute; + border: 30px solid transparent; + border-top: 17px solid white; + top: 0; + left: 50%; + margin-left: -30px; +} + .triangle2 { position: absolute; border: 30px solid transparent; @@ -3321,12 +3321,12 @@ footer:after { .textCommChat { width: 84%; - float: left; - margin: 11px 0 30px 0; + /*float: left;*/ + margin: 6px 0; font-size: 14px; font-family: 'Arial-MT-Regular', sans-serif; color: #3c1a06; - line-height: 25px; + line-height: 18px; } .greenNCC { @@ -3384,7 +3384,7 @@ footer:after { float: right; border-radius: 40px; font-family: 'pfdintextcomppro-regular', sans-serif; - letter-spacing: 2px; + letter-spacing: 1px; color: #373737; font-size: 15px; border: 1px solid #BEBEBE; @@ -3429,8 +3429,9 @@ footer:after { } .textAreaBlock2 a, .textAreaBlock2 a:link, .textAreaBlock2 a:visited { - border: 1px solid #bebebe; - border-radius: 40px; + border: 1px solid #f1f1f1; + background-color: #f1f1f1; + /*border-radius: 40px;*/ color: #373737; display: inline-block; font-family: "pfdintextcomppro-regular",sans-serif; @@ -3479,6 +3480,8 @@ footer:after { .wrMessages { padding: 0; background-color: #F7F7F7; + border-right: 1px solid #DADADA; + /*border-left: 1px solid #DADADA;*/ } .messageBlock { @@ -3738,18 +3741,18 @@ footer:after { margin: 0 0 0 30px; } -.documentsChat a, .documentsChat a:link, .documentsChat a:visited { - color: #5a5a5a; - border-radius: 40px; - border: 1px solid #BEBEBE; - font-family: Arial, Verdana, Helvetica, sans-serif; - font-size: 12px; - font-style: italic; - padding: 10px 21px 10px 32px; - background: url('../img/btnDoc.png') no-repeat 10px 6px; - float: left; - margin: 19px 0 -10px 0; -} +/*.documentsChat a, .documentsChat a:link, .documentsChat a:visited {*/ + /*color: #5a5a5a;*/ + /*border-radius: 40px;*/ + /*border: 1px solid #BEBEBE;*/ + /*font-family: Arial, Verdana, Helvetica, sans-serif;*/ + /*font-size: 12px;*/ + /*font-style: italic;*/ + /*padding: 10px 21px 10px 32px;*/ + /*background: url('../img/btnDoc.png') no-repeat 10px 6px;*/ + /*float: left;*/ + /*margin: 19px 0 -10px 0;*/ +/*}*/ .wrChat1 .textAreaBlock2 { border: none; @@ -3811,12 +3814,13 @@ footer:after { .titleOB { width: 100%; - float: left; + /*float: left;*/ font-family: 'Arial-MT-Regular', sans-serif; font-size: 18px; color: #2c2c2c; - margin: 0 0 0 0; + margin: 0; line-height: 20px; + padding-right: 20px; } .pOB { @@ -3828,6 +3832,12 @@ footer:after { margin: 10px 0 10px 0; } +.pDB { + font-family: 'Arial-MT-Regular', sans-serif; + font-size: 12px; + color: #5d5d5d; +} + .pOB span { font-family: Arial, Verdana, Helvetica, sans-serif; font-weight: bold; @@ -3899,11 +3909,11 @@ footer:after { transition: all 0.3s ease-out; } -.orderBlock:hover .dimovChat { - -webkit-transform: rotate(90deg); - -moz-transform: rotate(90deg); - transform: rotate(90deg); -} +/*.orderBlock:hover .dimovChat {*/ + /*-webkit-transform: rotate(90deg);*/ + /*-moz-transform: rotate(90deg);*/ + /*transform: rotate(90deg);*/ +/*}*/ .orAct .dimovChat { -webkit-transform: rotate(90deg); @@ -3911,9 +3921,9 @@ footer:after { transform: rotate(90deg); } -.orderBlock:hover .hideOBB { - display: block; -} +/*.orderBlock:hover .hideOBB {*/ + /*display: block;*/ +/*}*/ .orAct .hideOBB { display: block !important; @@ -3921,6 +3931,8 @@ footer:after { .wrstepschat { float: left; + /*border-right: 1px solid #DADADA;*/ + border-left: 1px solid #DADADA; padding: 0; } @@ -3932,6 +3944,36 @@ footer:after { margin: 26px 15px 20px 15px; color: black; } +.remove-margin{ + margin-right: -15px; + margin-left: -15px; + position: relative; +} +.tab-content .header-wrapper { + /*display: inline-block;*/ + font-size: 24px; + font-family: 'pfbeausanspro-reg', sans-serif; + padding: 26px 0px; + width: 100%; + color: black; + background-color: #F3F3F3; + text-align: center; +} + +.tab-content .header-wrapper .header{ + background-color: white; + display: inline-block; + width: 100%; +} + +.triangle-header { + position: absolute; + border: 30px solid transparent; + border-top: 17px solid white; + top: 60px; + left: 50%; + margin-left: -30px; +} .stepssBlock { width: 100%; @@ -3941,12 +3983,12 @@ footer:after { border-bottom: 1px solid black; z-index: 9; position: relative; - margin-bottom: -1px; + /*margin-bottom: -1px;*/ } .titleStepss { width: 100%; - float: left; + /*float: left;*/ font-size: 18px; font-family: 'Arial-MT-Regular', sans-serif; margin: 0 0 15px 0; @@ -3955,7 +3997,7 @@ footer:after { .textStepss { width: 100%; - float: left; + /*float: left;*/ font-size: 14px; line-height: 17px; font-family: 'Arial-MT-Regular', sans-serif; @@ -3968,7 +4010,7 @@ footer:after { border-top: 1px solid transparent; border-bottom: 1px solid transparent; padding: 15px; - margin-bottom: -15px; + /*margin-bottom: -15px;*/ background-color: white; position: relative; -webkit-transition: all 0.3s ease-out; @@ -4058,39 +4100,39 @@ footer:after { margin-top: 15px; } -.stepssBlock ul { - float: left; - margin: 10px 0 0 30px; -} +/*.stepssBlock ul {*/ + /*float: left;*/ + /*margin: 10px 0 0 30px;*/ +/*}*/ -.stepssBlock ul li { - font-size: 12px; - color: #525252; - font-family: 'Arial-MT-Regular', sans-serif; - margin-bottom: 8px; - position: relative; -} +/*.stepssBlock ul li {*/ + /*font-size: 12px;*/ + /*color: #525252;*/ + /*font-family: 'Arial-MT-Regular', sans-serif;*/ + /*margin-bottom: 8px;*/ + /*position: relative;*/ +/*}*/ -.stepssBlock ul li:before { - content: ''; - position: absolute; - left: -30px; - top: 2px; -} +/*.stepssBlock ul li:before {*/ + /*content: '';*/ + /*position: absolute;*/ + /*left: -30px;*/ + /*top: 2px;*/ +/*}*/ -.stepssBlock ul li:first-child:before { - width: 13px; - height: 14px; - background: url('../img/reserved.png') no-repeat center; - background-size: cover; -} +/*.stepssBlock ul li:first-child:before {*/ + /*width: 13px;*/ + /*height: 14px;*/ + /*background: url('../img/reserved.png') no-repeat center;*/ + /*background-size: cover;*/ +/*}*/ -.stepssBlock ul li:last-child:before { - width: 17px; - height: 16px; - background: url('../img/reserved2.png') no-repeat center; - background-size: cover; -} +/*.stepssBlock ul li:last-child:before {*/ + /*width: 17px;*/ + /*height: 16px;*/ + /*background: url('../img/reserved2.png') no-repeat center;*/ + /*background-size: cover;*/ +/*}*/ .infoProfile .dropdown-menu { @@ -4477,12 +4519,12 @@ footer:after { color: #009DD9; } -label { - width: 23px; - height: 23px; - display: block; - position: relative; -} +/*label {*/ + /*width: 23px;*/ + /*height: 23px;*/ + /*display: block;*/ + /*position: relative;*/ +/*}*/ /*input[type="checkbox"] + span {*/ /*position: absolute;*/ @@ -5752,13 +5794,13 @@ input[type="radio"]:checked + span { #order-stages .checkbox label{ margin-top: 0; } -#order-stages > div { - display: table; - width: 100%; - padding-bottom: 14px; - border-bottom: 1px solid #2c2c2c; - margin-bottom: 14px; -} +/*#order-stages > div {*/ + /*!*display: table;*!*/ + /*!*width: 100%;*!*/ + /*padding-bottom: 14px;*/ + /*border-bottom: 1px solid #2c2c2c;*/ + /*margin-bottom: 14px;*/ +/*}*/ #order-stages > div:nth-last-child(2), #order-stages > div:last-child{ border: none; } @@ -5975,19 +6017,19 @@ a.linkS2[data-target="#withdraw-money"]{ display: table; max-height: 845px; overflow-y: scroll; - border-right: 1px solid #DADADA; - border-left: 1px solid #DADADA; - padding-bottom: 300px; + /*border-right: 1px solid #DADADA;*/ + /*border-left: 1px solid #DADADA;*/ + /*padding-bottom: 300px;*/ } #message-chat-space { height: 312px; display: block; overflow: auto; } -#contact-chat-form{ - position: absolute; - bottom: 0; -} +/*#contact-chat-form{*/ + /*position: absolute;*/ + /*bottom: 0;*/ +/*}*/ .dropdown-menu > li > a{ white-space: normal; } diff --git a/assets/img/icons/icon_arbitration.png b/assets/img/icons/icon_arbitration.png new file mode 100644 index 0000000..801cdf5 Binary files /dev/null and b/assets/img/icons/icon_arbitration.png differ diff --git a/assets/img/icons/icon_arrow_gray.png b/assets/img/icons/icon_arrow_gray.png new file mode 100644 index 0000000..6cd29c7 Binary files /dev/null and b/assets/img/icons/icon_arrow_gray.png differ diff --git a/assets/img/icons/icon_books.png b/assets/img/icons/icon_books.png new file mode 100644 index 0000000..4d2221c Binary files /dev/null and b/assets/img/icons/icon_books.png differ diff --git a/assets/img/icons/icon_check.png b/assets/img/icons/icon_check.png new file mode 100644 index 0000000..4789bcf Binary files /dev/null and b/assets/img/icons/icon_check.png differ diff --git a/assets/img/icons/icon_coins_gray.png b/assets/img/icons/icon_coins_gray.png new file mode 100644 index 0000000..3286769 Binary files /dev/null and b/assets/img/icons/icon_coins_gray.png differ diff --git a/assets/img/icons/icon_coins_green.png b/assets/img/icons/icon_coins_green.png new file mode 100644 index 0000000..0addd7b Binary files /dev/null and b/assets/img/icons/icon_coins_green.png differ diff --git a/assets/img/icons/icon_coins_red.png b/assets/img/icons/icon_coins_red.png new file mode 100644 index 0000000..ee8e583 Binary files /dev/null and b/assets/img/icons/icon_coins_red.png differ diff --git a/assets/img/icons/icon_complete_stage.png b/assets/img/icons/icon_complete_stage.png new file mode 100644 index 0000000..89e073f Binary files /dev/null and b/assets/img/icons/icon_complete_stage.png differ diff --git a/assets/img/icons/icon_credit_card.png b/assets/img/icons/icon_credit_card.png new file mode 100644 index 0000000..3d9b29d Binary files /dev/null and b/assets/img/icons/icon_credit_card.png differ diff --git a/assets/img/icons/icon_credit_card_gray.png b/assets/img/icons/icon_credit_card_gray.png new file mode 100644 index 0000000..57a9faf Binary files /dev/null and b/assets/img/icons/icon_credit_card_gray.png differ diff --git a/assets/img/icons/icon_hands_gray.png b/assets/img/icons/icon_hands_gray.png new file mode 100644 index 0000000..201d6e8 Binary files /dev/null and b/assets/img/icons/icon_hands_gray.png differ diff --git a/assets/img/icons/icon_pen_black.png b/assets/img/icons/icon_pen_black.png new file mode 100644 index 0000000..3d902ea Binary files /dev/null and b/assets/img/icons/icon_pen_black.png differ diff --git a/assets/img/icons/icon_print.png b/assets/img/icons/icon_print.png new file mode 100644 index 0000000..42648fb Binary files /dev/null and b/assets/img/icons/icon_print.png differ diff --git a/assets/img/icons/icon_protect.png b/assets/img/icons/icon_protect.png new file mode 100644 index 0000000..8b1e115 Binary files /dev/null and b/assets/img/icons/icon_protect.png differ diff --git a/assets/js/build/chat_contractor_oop.js b/assets/js/build/chat_contractor_oop.js new file mode 100644 index 0000000..a579dcc --- /dev/null +++ b/assets/js/build/chat_contractor_oop.js @@ -0,0 +1,2773 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _ChatContractorPageController = __webpack_require__(1); + + var _BINDS = __webpack_require__(17); + + var _documents = __webpack_require__(19); + + var _notes = __webpack_require__(20); + + var _parts = __webpack_require__(21); + + var _archiveProjects = __webpack_require__(22); + + var _chats = __webpack_require__(23); + + var _wsChatConnect = __webpack_require__(24); + + window.connect = _wsChatConnect.connect; + window.socket = undefined; + + $(function () { + (0, _BINDS.bindArbitrationSend)(); + window.onhashchange = function (e) { + $('a[data-toggle="tab"][href="#' + location.hash.slice(1) + '"]').trigger("click"); + }; + window.chatController = new _ChatContractorPageController.ChatPageController(); + (0, _BINDS.bindOrders)(); + (0, _BINDS.bindTeams)(); + (0, _BINDS.bindOnTabs)(); + (0, _BINDS.bindUserContacts)(); + (0, _BINDS.bindGetUserMessages)(); + (0, _archiveProjects.bindArchiveProjects)(); + (0, _BINDS.bindDeleteContact)(); + + // Chats + (0, _chats.chatContactsInit)(); + (0, _chats.chatOrdersInit)(); + (0, _chats.chatTeamsInit)(); + + //Documents + (0, _documents.uploadDocumentsContactInit)(); + (0, _documents.uploadDocumentsOrderInit)(); + (0, _documents.uploadDocumentsTeamInit)(); + (0, _documents.bindRemoveDocuments)(); + + //Notes + (0, _notes.bindContractorNotes)(); + (0, _notes.bindOrderNotes)(); + (0, _notes.bindTeamNotes)(); + + //restore + (0, _parts.restoreTabFromHash)(); + }); + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.ChatPageController = undefined; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _StagesContractorController = __webpack_require__(2); + + var _MessagesControllers = __webpack_require__(15); + + var _DocumentsControllers = __webpack_require__(16); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var ChatPageController = function () { + function ChatPageController() { + _classCallCheck(this, ChatPageController); + + var self = this; + console.log("NEW CONTRACTOR ChatPageController"); + this.statesController = undefined; + this.messagesController = undefined; + this.documentsController = undefined; + // TODO: не забыть! + + // $('.order-block').on('click', function (event) { + // console.log("CLICK!!!"); + // event.preventDefault(); + // let $this = $(this); + // $('.order-block').each(function (i, v) { + // $(v).removeClass('orAct'); + // }); + // $this.addClass('orAct'); + // let orderId = $this.data('id'); + // let projectId = $this.data('project-id'); + // let recipentId = $this.data('recipent-id'); + // let orderName = $this.data('order-name'); + // // console.log('orderId = ', orderId); + // new StagesController(orderId, projectId, recipentId, orderName); + // new MessagesController(orderId); + // window.location.hash = `order${orderId}`; + // + // $("#chat-order-add #orderId").val(orderId); + // $("#add-form-order-note #orderNote").val(orderId); + // $("#orderArbitrationId").val(orderId); + // $("#projectReviewId").val(projectId); + // // console.log("recipentId = ", recipentId); + // $("#chat-order-add #recipentId").val(recipentId); + // $("#targetCustomerId").val(recipentId); + // $("#add-form-order-note #recipentNote").val(recipentId); + // + // }); + // $('.order-block .dimovChat').on('click', function (event) { + // event.preventDefault(); + // event.stopPropagation(); + // // TODO: доделать сворачивание/разворачивание блока + // // console.log('click on tr'); + // }); + } + + _createClass(ChatPageController, [{ + key: 'create', + value: function create(orderId, projectId, recipentId, orderName, secureOrder) { + this.statesController = new _StagesContractorController.StagesController(orderId, projectId, recipentId, orderName, secureOrder); + this.messagesController = new _MessagesControllers.MessagesController(orderId); + this.documentsController = new _DocumentsControllers.DocumentsController(orderId); + } + + // refresh() + + }]); + + return ChatPageController; + }(); + + exports.ChatPageController = ChatPageController; + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.StagesController = undefined; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _utils = __webpack_require__(3); + + var _loaders = __webpack_require__(4); + + var _Stages = __webpack_require__(14); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var message_format = { + "format_type": "approve_stages", + "data": { + "sender_id": "", + "recipent_id": "", + "order_id": "", + "msg": "", + "is_system": true + } + }; + + var STATUSES = { + 'not_agreed': 'не согласован', + 'send_approve': 'на согласовании', + 'agreed': 'согласовано', + 'cancel_approve': 'исполнитель отказался', + 'in_process': 'в процессе', + 'completed': 'завершен', + 'closed': 'закрыт' + + }; + + //Contractor + + var StagesController = function () { + function StagesController(orderId, projectId, recipentId, orderName, secureOrder) { + _classCallCheck(this, StagesController); + + var self = this; + this.orderId = orderId; + this.projectId = projectId; + this.recipentId = recipentId; + this.orderName = orderName; + this.secureOrder = secureOrder; + // console.log("ids -->", orderId, projectId, recipentId); + this.data = {}; //JSON + this.stages = []; + this.stages_reserved = []; + this.stages_work = []; + this.STAGE_STATUSES = { + 'not_agreed': this.buildStartStage.bind(self), + 'send_approve': this.buildSendApproveStage.bind(self), + 'agreed': this.buildAgreedStage.bind(self), + 'in_process': this.buildProcessStage.bind(self), + 'completed': this.buildProcessStage.bind(self), + 'closed': this.buildProcessStage.bind(self) + }; + this.btnCompleteTmpl = (0, _loaders.loadTemplate)('bntCompleteStage_tmpl'); + this.btnSendReviewTmpl = (0, _loaders.loadTemplate)('btnSendReview_tmpl'); + this.$orderStagesContainer = $('#order-stages'); + this.$orderStagesContainer.html(''); + this.buttons = { + btnApprove: $('#btnApprove'), // "Согласовать" + btnChange: $('#btnChange'), // "Отправить на внесение изменений" + btnsToArchive: $('.js-btnToArchive'), // "Отказаться от заказа" + btnsArbitration: $('.js-btnArbitration'), // "Обратиться в арбитраж" + btnSendReview: $('#order-review-add') // "Оставить отзыв" + }; + this.stages_elements = { + $approve: $('#conditions-approve'), //1. Согласование условия + $reserve: $('#reserveSpace'), //2. Резервирование (Отобразить) + $works: $('#completeWork') //3. Выполненная работа + }; + this.init(); + } + + _createClass(StagesController, [{ + key: 'init', + value: function init() { + var self = this; + + this.dataPromise = this.getOrderData({ orderId: this.orderId }); + this.dataPromise.then(self._onLoadData.bind(self)).catch(self._onLoadDataError.bind(self)); + } + }, { + key: 'getOrderData', + value: function getOrderData(_ref) { + var orderId = _ref.orderId; + + var self = this; + return Promise.resolve($.ajax({ + url: '/api/orders/' + orderId + '/', + dataType: 'json', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + } + })); + } + }, { + key: 'redraw', + value: function redraw() { + /** + * Полностью перерисовываем страницу Заказа + */ + console.log("Redraw contractor stages"); + // $("#orderBlock" + this.orderId).trigger('click'); + this.init(); + } + }, { + key: 'buildStartStage', + value: function buildStartStage() { + /** + * Стадия: "Проект Предложен"(нет этапов) + */ + // Выделить цифру 1. красным + // $('#conditions-approve').find('.select') + this.stages_elements.$approve.show(); + this.stages_elements.$reserve.show(); + this.stages_elements.$works.show(); + this.$orderStagesContainer.parent().hide(); + this.buttons.btnsToArchive.first().hide(); + this.$orderStagesContainer.show(); + this.buttons.btnApprove.hide(); + this.buttons.btnChange.hide(); + this.buttons.btnsArbitration.hide(); + this.stages_elements.$approve.find('.js-help-text').show(); + this.stages_elements.$reserve.find('.stages-paid').html(""); + this.stages_elements.$works.find('.js-help-text').show(); + this.stages_elements.$works.find('#stagesWork').html(""); + if (this.secureOrder) { + this.stages_elements.$reserve.find('.js-help-text').show(); + } else { + this.stages_elements.$reserve.find('.js-help-text').hide(); + // this.stages_elements.$reserve.find('.js-help-text').html('Резервирование не предусмотрено, безопасная сделака не активна'); + } + } // Нет Этапов / "Не согласован" + + // buildNotAgreedStage() { + // console.log("Stage: not_agreed"); + // // this._renderStage('stage_tmpl'); + // this.buttons.btnApprove.hide(); + // this.buttons.btnChange.hide(); + // this.buttons.btnToArchive.hide(); + // this.buttons.btnArbitration.hide(); + // } // Статус "Не согласован" + + }, { + key: 'buildSendApproveStage', + value: function buildSendApproveStage() { + console.log("Stage: send_approve"); + this._renderStage('stage_approved_tmpl', true); + this.$orderStagesContainer.parent().show(); + this.buttons.btnApprove.show(); + this.buttons.btnChange.show(); + this.buttons.btnsToArchive.first().show(); + this.stages_elements.$reserve.hide(); + this.stages_elements.$works.hide(); + } // Статус "На согласовании" + + }, { + key: 'buildAgreedStage', + value: function buildAgreedStage() { + console.log('Stage: agreed'); + this.$orderStagesContainer.parent().show(); + this.buttons.btnApprove.hide(); + this.buttons.btnChange.hide(); + this.buttons.btnsToArchive.hide(); + this.buttons.btnsArbitration.first().hide(); + this.buttons.btnsArbitration.last().show(); + this._renderStage('stage_approved_tmpl', true); + this.stages_elements.$approve.find('.js-help-text').hide(); + this.stages_elements.$reserve.show(); + if (this.secureOrder) { + this._renderStageReserved('reserved_tmpl'); + this.stages_elements.$reserve.find('.js-help-text').show(); + } else { + this.stages_elements.$reserve.find('.stages-paid').html(""); + this.stages_elements.$reserve.find('.js-help-text').hide(); + } + } // Статус "Согласован" + + }, { + key: 'buildProcessStage', + value: function buildProcessStage() { + console.log('Stage: in_process'); + this.buildAgreedStage(); + this.stages_elements.$reserve.find('.js-help-text').hide(); + this.stages_elements.$works.show(); + if (this.secureOrder) { + this._renderStageInWork('work_in_process_tmpl'); + } else { + this.stages_elements.$reserve.find('.stages-paid').html(""); + } + } // Статус "В процессе"/"Завершен"/"Закрыт" + + }, { + key: '_buildPage', + value: function _buildPage() { + // console.log("Build PAge"); + this.stages_elements.$reserve.hide(); + this.stages_elements.$works.hide(); + if (this.data.stages.length == 0) { + this.buildStartStage(); + } else { + var stageStatus = this.data.stages[0].status; + // console.log('stageStatus = ', stageStatus); + this.STAGE_STATUSES[stageStatus](); + } + this._bindEvents(); + } + }, { + key: '_renderStage', + value: function _renderStage(template_name) { + var disable = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var i = 0; + // console.log("this.data.stages = ", this.data.stages); + this.$orderStagesContainer.html(""); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = this.data.stages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var stage_data = _step.value; + + i++; + // console.log('stage_data = ', stage_data); + var stage = new _Stages.StageForm(this.$orderStagesContainer, { + orderId: this.orderId, stage_num: i, stage_status: STATUSES[stage_data.status], + type: 'update', template_name: template_name, data: stage_data + }); + if (disable) stage.disable(); + this.stages.push(stage); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, { + key: '_renderStageReserved', + value: function _renderStageReserved(template_name) { + /** + * Отрисовываем блок "Резервирование" + */ + // console.log("_renderStageReserved"); + var $container = this.stages_elements.$reserve.find('.stages-paid'); + $container.html(""); + this.stages_reserved = []; + // console.log("this.data.stages = ", this.data.stages); + // Нет незарезервированных Этапов + // let has_not_reserved_stages = false; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = this.data.stages[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var stage_data = _step2.value; + + // if (stage_data.status == 'agreed') has_not_reserved_stages = true; + var stage = new _Stages.StageReserved($container, { + template_name: template_name, data: stage_data + }); + this.stages_reserved.push(stage); + } + // if (!has_not_reserved_stages) { + // this.buttons.btnReserve.hide(); + // this.stages_elements.$reserve.find('.js-help-text').hide(); + // } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + }, { + key: '_renderStageInWork', + value: function _renderStageInWork(template_name) { + /** + * Отрисовываем блок "Выволнение работы", включая "Выполненныа работа" и "Оставить отзыв" + */ + var $container = this.stages_elements.$works.find('#stagesWork'); + $container.html(""); + var all_closed = this.data.stages.every(function (el) { + return el.status == 'closed'; + }); + if (all_closed) { + this.stages_elements.$works.find('.titleStepss').html('3. Выполненная работа'); + this.stages_elements.$works.find('.js-btnArbitration').hide(); + this.stages_elements.$works.find('.js-help-text').hide(); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = this.data.stages[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var stage_data = _step3.value; + + var stage = new _Stages.StageInWork($container, { + template_name: template_name, data: stage_data + }); + this.stages_work.push(stage); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + console.log("has_user_review = ", this.data.has_user_review); + if (!this.data.has_user_review) { + var btnReviewOpenModel = $(this.btnSendReviewTmpl()); + btnReviewOpenModel.unbind().on('click', this._onBtnReviewOpenModal.bind(this)); + // Если кнопка "Оставить отзыв" еще не добавлена - добавляем + if (!this.stages_elements.$works.find('#send-review').length) this.stages_elements.$works.append(btnReviewOpenModel); + } else { + if (this.stages_elements.$works.find('#send-review').length) this.stages_elements.$works.find('#send-review').remove(); + } + } else { + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = this.data.stages[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var _stage_data = _step4.value; + + if (_stage_data.status == 'closed' || _stage_data.status == 'agreed') continue; + var note_text = _stage_data.status == 'completed' ? '...НА УТВЕРЖДЕНИИ У ЗАКАЗЧИКА' : ''; + var _stage = new _Stages.StageInWork($container, { + template_name: template_name, data: _stage_data, note_text: note_text + }); + if (_stage_data.status == 'in_process') { + var $btn = $(this.btnCompleteTmpl({ stage: _stage_data, text: 'Завершить этап' })); + $container.html(); + $container.append($btn); + $btn.on('click', this._onBtnComplete.bind(this, _stage)); + } + this.stages_work.push(_stage); + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + } + }, { + key: '_onLoadData', + value: function _onLoadData(json) { + this.data = json; + this._buildPage(); + } + }, { + key: '_bindEvents', + value: function _bindEvents() { + var self = this; + this.buttons.btnApprove.unbind().on("click", this._onBtnAccept.bind(self)); + this.buttons.btnChange.unbind().on("click", this._onBtnChange.bind(self)); + this.buttons.btnsToArchive.unbind().on("click", this._onBtnAToArchive.bind(self)); + this.buttons.btnsArbitration.unbind().on("click", this._onBtnArbitration.bind(self)); + this.buttons.btnSendReview.unbind().on("click", this._onBtnSendReview.bind(self)); + $("#reserve-stage-modal").find('#stage-num').unbind().on('change', function (event) { + // console.log("select stage cost = ", self.stages[this.value - 1].data.cost); + $("#reserve-stage-modal").find('#stage-cost').html(self.stages[this.value - 1].data.cost); + }); + } + + // BINDS + + }, { + key: '_onBtnAccept', + value: function _onBtnAccept(event) { + event.preventDefault(); + var self = this; + Promise.all(this.stages.map(function (el) { + return el.sendAjax_accept(self.secureOrder); + })).then(function () { + console.log('Этапы согласованы'); + self.redraw(); + + var message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = '\u0423\u0441\u043B\u043E\u0432\u0438\u044F \u0437\u0430\u043A\u0430\u0437\u0430 ' + self.orderName + ' \u043F\u0440\u0438\u043D\u044F\u0442\u044B'; + console.log("Send-WS Условия приняты"); + socket.send_stages_approve(message); + //TODO: раскомментировать дурацкое окно + // $('#popupOk').modal('show'); + // }) + }); + } // "Согласовать" + + }, { + key: '_onBtnChange', + value: function _onBtnChange(event) { + event.preventDefault(); + var self = this; + Promise.all(this.stages.map(function (el) { + return el.sendAjax_change(); + })).then(function () { + self.redraw(); + var message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = '\u0417\u0430\u043A\u0430\u0437 ' + self.orderName + ' \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u0435\u043D \u0434\u043B\u044F \u0432\u043D\u0435\u0441\u0435\u043D\u0438\u044F \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439'; + console.log("Send-WS Внести изменения"); + socket.send_stages_approve(message); + }); + } // "Отправить на внесение изменений" + + // TODO: test it + + }, { + key: '_onBtnAToArchive', + value: function _onBtnAToArchive(event) { + event.preventDefault(); + console.error("Отказаться от заказа. Не протестировано!!"); + // TODO: Не только удалять заказ, но и делать его копию со статусом "Открыто" + $.ajax({ + // async: false, + url: '/api/orders/' + this.orderId + '/', + type: 'DELETE', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + dataType: 'json' + }).done(function (json) { + console.log('delete complete'); + window.location.href = window.location.href.replace(getHash(), ""); + }).fail(function (xhr, errorMsg, error) { + console.log("delete fail, json -->", xhr); + }); + } // "Отказаться от заказа" + + }, { + key: '_onBtnComplete', + value: function _onBtnComplete(stage, event) { + event.preventDefault(); + var self = this; + // let stageId = $(event.target).data('stage-id'); + // console.log('Complete stage id = ', stage.data.id); + stage.sendAjax_complete().then(function (json) { + self.redraw(); + var message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = '\u042D\u0442\u0430\u043F ' + json.name + ' \u0437\u0430\u043A\u0440\u044B\u0442'; + console.log("Send-WS Закрытие этапа"); + socket.send_stages_approve(message); + }).catch(function (xhr) { + console.log("При закрытии этапа произошла ошибка -->", xhr); + }); + } // "Закрыть этап" + + }, { + key: '_onBtnReviewOpenModal', + value: function _onBtnReviewOpenModal(event) { + event.preventDefault(); + $('#review-add').modal('show'); + } // Открыть модальное окно "Оставить отзыв" + + }, { + key: '_onBtnSendReview', + value: function _onBtnSendReview(event) { + event.preventDefault(); + var self = this; + $('#projectReviewId').val(this.projectId); + $('#targetCustomerId').val(this.recipentId); + // $('#fromContractorId').val('....current user'); + var formData = $("#review-adds-form").serialize(); + // console.log('Оставить отзыв formdata -->', formData); + $.ajax({ + url: '/api/reviews/', + type: 'POST', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: formData, + dataType: 'json', + success: function success(json) { + console.log('Отзыв успешно отправлен, json -->', json); + // $('#review-add').modal('hide'); + // self.stages_elements.$works.find('.js-btnSendReview').hide(); + $('#review-add').modal('hide'); + self.redraw(); + + var message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = '\u041E\u0442\u0437\u044B\u0432 \u043D\u0430 \u0437\u0430\u043A\u0430\u0437 ' + self.orderName + ' \u043E\u0441\u0442\u0430\u0432\u043B\u0435\u043D'; + console.log("Send-WS Оставить отзыв"); + socket.send_stages_approve(message); + // $("a[href='#tab2']").trigger('click'); + window.location = '/chat/#order'; + location.reload(); + }, + error: function error(e) { + console.log('error'); + console.log(e); + } + }); + } // "Оставить отзыв" + + + }, { + key: '_onBtnArbitration', + value: function _onBtnArbitration(event) { + event.preventDefault(); + $("#arbitration-add").modal('show'); + } // "Обратиться в арбитраж" + + }, { + key: '_onLoadDataError', + value: function _onLoadDataError(error) { + console.log("Error loading data -->", error); + } + }]); + + return StagesController; + }(); + + exports.StagesController = StagesController; + +/***/ }, +/* 3 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + function getCookie(name) { + var cookieValue = null; + if (document.cookie && document.cookie != '') { + var cookies = document.cookie.split(';'); + for (var i = 0; i < cookies.length; i++) { + var cookie = jQuery.trim(cookies[i]); + if (cookie.substring(0, name.length + 1) == name + '=') { + cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); + break; + } + } + } + return cookieValue; + } + + function humanFileSize(bytes, si) { + var thresh = si ? 1000 : 1024; + + if (Math.abs(bytes) < thresh) return bytes + ' B'; + + var units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; + + var u = -1; + + do { + bytes /= thresh; + ++u; + } while (Math.abs(bytes) >= thresh && u < units.length - 1); + + return bytes.toFixed(1) + ' ' + units[u]; + } + + exports.humanFileSize = humanFileSize; + exports.getCookie = getCookie; + +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.loadTemplate = undefined; + + var _stage_tmpl = __webpack_require__(5); + + var _stage_tmpl2 = _interopRequireDefault(_stage_tmpl); + + var _stage_approved_tmpl = __webpack_require__(6); + + var _stage_approved_tmpl2 = _interopRequireDefault(_stage_approved_tmpl); + + var _reserved_tmpl = __webpack_require__(7); + + var _reserved_tmpl2 = _interopRequireDefault(_reserved_tmpl); + + var _message_tmpl = __webpack_require__(8); + + var _message_tmpl2 = _interopRequireDefault(_message_tmpl); + + var _work_in_process_tmpl = __webpack_require__(9); + + var _work_in_process_tmpl2 = _interopRequireDefault(_work_in_process_tmpl); + + var _bntCompleteStage_tmpl = __webpack_require__(10); + + var _bntCompleteStage_tmpl2 = _interopRequireDefault(_bntCompleteStage_tmpl); + + var _btnSendReview_tmpl = __webpack_require__(11); + + var _btnSendReview_tmpl2 = _interopRequireDefault(_btnSendReview_tmpl); + + var _document_attach_file_tmpl = __webpack_require__(12); + + var _document_attach_file_tmpl2 = _interopRequireDefault(_document_attach_file_tmpl); + + var _note_tmpl = __webpack_require__(13); + + var _note_tmpl2 = _interopRequireDefault(_note_tmpl); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function loadTemplate(template_name) { + var templates = { + stage_tmpl: _stage_tmpl2.default, + stage_approved_tmpl: _stage_approved_tmpl2.default, + reserved_tmpl: _reserved_tmpl2.default, + message_tmpl: _message_tmpl2.default, + work_in_process_tmpl: _work_in_process_tmpl2.default, + bntCompleteStage_tmpl: _bntCompleteStage_tmpl2.default, + btnSendReview_tmpl: _btnSendReview_tmpl2.default, + document_attach_file_tmpl: _document_attach_file_tmpl2.default, + note_tmpl: _note_tmpl2.default + }; + + if (!templates[template_name]) throw new Error('Template ' + template_name + ' does not exist'); + return templates[template_name]; + } + + exports.loadTemplate = loadTemplate; + +/***/ }, +/* 5 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return '\n
\n

\u042D\u0422\u0410\u041F ' + this.stage_num + '

\n
\n \n \n

\n \n \n

\n \n

\n \n \n \n \n

\n \n \n

\n
\n
'; + }; + +/***/ }, +/* 6 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n
\n
\n
\n \u042D\u0422\u0410\u041F " + this.stage_num + "\n
\n
\n " + this.stage_status + "\n
\n
\n
\n\n
\n " + this.stage.name + "\n
\n \u0420\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u044D\u0442\u0430\u043F\u0430\n
\n " + this.stage.result + "\n
\n \u0426\u0435\u043D\u0430\n
\n " + this.stage.cost + " \u20BD\n
\n \u0421\u0440\u043E\u043A\n
\n \u0434\u043E " + this.stage.term + "\n
\n\n
"; + }; + +/***/ }, +/* 7 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n\n
  • \u0421\u0443\u043C\u043C\u0430 \u0437\u0430 \u044D\u0442\u0430\u043F " + this.stage.pos + "\n
    " + this.reserved_name + "
    \n
  • "; + }; + +/***/ }, +/* 8 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n
    \n
    \n

    " + this.senderName + "

    " + this.message.created + "\n
    \n

    " + this.message.text + "

    \n
    "; + }; + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n
    \n \u0412 \u0440\u0430\u0431\u043E\u0442\u0435: " + this.stage.name + "
    \n \u0420\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u044D\u0442\u0430\u043F\u0430: " + this.stage.result + "
    \n \u0421\u0440\u043E\u043A \u0441\u0434\u0430\u0447\u0438: " + this.stage.term + "
    \n " + this.stage.cost + " \u0440\n
    \n " + this.note_text + "\n
    \n
    "; + }; + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n"; + }; + +/***/ }, +/* 11 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return ""; + }; + +/***/ }, +/* 12 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n
  • \n " + this.text + "\n
    \n
  • \n\n"; + }; + +/***/ }, +/* 13 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "
    \n
  • \n " + this.text + "\n
  • \n
    \n
    \n"; + }; + +/***/ }, +/* 14 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.StageInWork = exports.StageReserved = exports.StageForm = undefined; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _loaders = __webpack_require__(4); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + // new-stages-form + // update-stages-form + // remove-stages-form + + var StageForm = function () { + function StageForm($container, _ref) + // kwargs - auto generate from name_attributes + { + var orderId = _ref.orderId, + stage_num = _ref.stage_num, + stage_status = _ref.stage_status, + _ref$type = _ref.type, + type = _ref$type === undefined ? 'new' : _ref$type, + _ref$formNamePostfix = _ref.formNamePostfix, + formNamePostfix = _ref$formNamePostfix === undefined ? '-stages-form' : _ref$formNamePostfix, + template_name = _ref.template_name, + _ref$data = _ref.data, + data = _ref$data === undefined ? {} : _ref$data; + var kwargs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + stage_num: stage_num, + stage_status: stage_status, + form_name: type + formNamePostfix, + orderId: orderId, + stage: data + }; + + _classCallCheck(this, StageForm); + + // console.log('Stage form template_name = ', template_name); + this.orderId = orderId; + this._type = type; + this.$container = $container; + this.self_tmpl = (0, _loaders.loadTemplate)(template_name); + this.data = data; + this.$form = undefined; + this.stageId = type != 'new' ? data.id : undefined; + this.create(kwargs); + } + + _createClass(StageForm, [{ + key: 'create', + value: function create(kwargs) { + /** + * Добавление шаблона-формы Этапа на страницу + */ + var el = $(this.self_tmpl(kwargs)); + this.$container.append(el); + this.$form = el.find('form'); + // console.log("form --> ", this.$form); + if (this.$form.length) this.$form.find('input[name=cost]').mask('000000000'); + } + }, { + key: 'remove', + value: function remove() { + /** + * Удаление, при уменьшении кол-ва этапов + * return true - удаляем из [] stages + */ + if (this.type == 'new') { + this.$form.parent().remove(); + return true; + } + this.type = 'remove'; + // this.$form.removeClass('update-stages-form').addClass('remove-stages-form'); + return false; + } + }, { + key: 'restore', + value: function restore() { + /** + * Восстановление, при увеличении кол-ва этапов + */ + if (this.type == 'new') throw new Error("Попытка восстановить элемент с type='new'"); + this.type = 'update'; + // this.$form.removeClass('remove-stages-form').addClass('update-stages-form'); + } + }, { + key: 'disable', + value: function disable() { + this.$form.find('input').attr('readonly', true); + } + }, { + key: 'enable', + value: function enable() { + this.$form.find('input').attr('readonly', false); + } + }, { + key: 'hide', + value: function hide() { + this.$form.parent().hide(); + } + }, { + key: 'show', + value: function show() { + this.$form.parent().show(); + } + }, { + key: 'is_valid', + value: function is_valid() { + var self = this; + var mesage = 'Это поле обязательно'; + var valid = true; + //Очищаем старые ошибки + this.$form.find('.error').html(""); + // Отображаем новые + this.$form.find(":input:not([type=hidden])").each(function (i, v) { + if (!$(v).val()) { + self.$form.find('.error-' + $(v).attr("name")).html(mesage).css('color', 'red'); + valid = false; + } + }); + return valid; + } + }, { + key: 'sendAjax_approve', + value: function sendAjax_approve() { + /** + * Отправка Этапа "на согласование" + */ + var self = this; + // console.log("Send AJAX Approve"); + if (this.type == 'new') { + // console.log('new stages approve'); + return Promise.resolve($.ajax({ + // async: false, + url: '/api/stages/', + type: 'POST', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + data: this.$form.serialize(), + dataType: 'json' + }).done(function (json) { + self.type = 'update'; + self.disable(); + self.$form.find('.error').html(""); + // console.log("json -->", json); + self.stageId = json.id; + // console.log(json); + }).fail(function (xhr, errorMsg, error) { + console.log("ERROR, xhr", xhr); + $.each(xhr.responseJSON, function (i, v) { + self.$form.find('.error-' + i).html(v).css('color', 'red'); + // console.log(self.$form); + // console.log(v); + // console.log(i); + }); + })); + } else if (this.type == 'update') { + this.$form.find('input[name=status]').val('send_approve'); + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PUT', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + data: this.$form.serialize(), + dataType: 'json' + }).done(function (json) { + self.$form.find('.error').html(""); + self.disable(); + }).fail(function (xhr, errorMsg, error) { + $.each(xhr.responseJSON, function (i, v) { + self.$form.find('.error-' + i).html(v).css('color', 'red'); + console.log(v); + console.log(i); + }); + })); + } else if (this.type == 'remove') { + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'DELETE', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + dataType: 'json' + }).done(function (json) {}).fail(function (xhr, errorMsg, error) { + console.log("delete fail, json -->", xhr); + })); + } + } + }, { + key: 'sendAjax_accept', + value: function sendAjax_accept(secureOrder) { + /** + * "Согласовать" Этапы (Исполнителем) + */ + console.log("secureOrder = ", secureOrder); + console.log("set new status =", secureOrder ? 'agreed' : 'in_process'); + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PATCH', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + //TODO: слать только изменения + data: { + status: secureOrder ? 'agreed' : 'in_process' + }, + dataType: 'json' + })); + } + }, { + key: 'sendAjax_change', + value: function sendAjax_change() { + /** + * Отправка Этапа "Внести изменения" + */ + var self = this; + // this.$form.find('input[name=status]').val('not_agreed'); + // console.log("ajax Change form -->", this.$form); + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PATCH', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + //TODO: слать только изменения + data: { status: 'not_agreed' }, + dataType: 'json' + }).done(function (json) { + // enableStageFields(json.id); + // $form.find('.error').html(""); + self.enable(); + }).fail(function (xhr) { + console.log("Ошибка, которой не должно быть json -->", xhr.responseJSON); + })); + } + }, { + key: 'type', + set: function set(newType) { + this.$form.removeClass(this._type + '-stages-form').addClass(newType + '-stages-form'); + if (newType == 'remove') this.hide(); + if (newType == 'update') this.show(); + this._type = newType; + }, + get: function get() { + return this._type; + } + }]); + + return StageForm; + }(); + + var StageReserved = function () { + function StageReserved($container, _ref2) { + var _ref2$template_name = _ref2.template_name, + template_name = _ref2$template_name === undefined ? 'reserved_tmpl' : _ref2$template_name, + data = _ref2.data; + var kwargs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + reserved_cls: '', + reserved_name: '', + stage: data + }; + + _classCallCheck(this, StageReserved); + + // Вывод текста резервирования в зависимости от статуса этапа + var reserved_names = { + agreed: 'Не зарезервирована', + in_process: 'Зарезервирована', + completed: 'Зарезервирована', + closed: 'Переведена исполнителю' + }; + // Вывод текста резервирования в зависимости от статуса этапа + var reserved_classes = { + agreed: 'unreserved', + in_process: 'reserved', + completed: 'reserved', + closed: 'closed' + }; + kwargs.reserved_cls = reserved_classes[data.status]; + kwargs.reserved_name = reserved_names[data.status]; + this.data = data; + this.self_tmpl = (0, _loaders.loadTemplate)(template_name); + this.$container = $container; + this.create(kwargs); + } + + _createClass(StageReserved, [{ + key: 'create', + value: function create(kwargs) { + /** + * Добавление шаблона "Резервирование" Этапа на страницу + */ + this.$self = $(this.self_tmpl(kwargs)); + this.$container.append(this.$self); + // console.log("form --> ", this.$form); + // this.$form.find('input[name=cost]').mask('000000000'); + } + }]); + + return StageReserved; + }(); + + var StageInWork = function () { + function StageInWork($container, _ref3) { + var _ref3$template_name = _ref3.template_name, + template_name = _ref3$template_name === undefined ? 'work_in_process_tmpl' : _ref3$template_name, + _ref3$note_text = _ref3.note_text, + note_text = _ref3$note_text === undefined ? '' : _ref3$note_text, + data = _ref3.data; + var kwargs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { stage: data, note_text: note_text }; + + _classCallCheck(this, StageInWork); + + this.stageId = data.id; + this.data = data; + this.self_tmpl = (0, _loaders.loadTemplate)(template_name); + this.$container = $container; + this.create(kwargs); + } + + _createClass(StageInWork, [{ + key: 'create', + value: function create(kwargs) { + /** + * Добавление шаблона "Выполнение работы" Этапа на страницу + */ + this.$self = $(this.self_tmpl(kwargs)); + this.$container.append(this.$self); + } + }, { + key: 'hide', + value: function hide() { + this.$self.hide(); + } + }, { + key: 'sendAjax_complete', + value: function sendAjax_complete() { + /** + * Отправка Этапа "Закрыть этап" + */ + var self = this; + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PATCH', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + data: { status: 'completed' }, + dataType: 'json' + }).done(function (json) { + // enableStageFields(json.id); + // $form.find('.error').html(""); + // self.enable(); + }).fail(function (xhr) { + console.log("Ошибка, которой не должно быть json -->", xhr.responseJSON); + })); + } + }, { + key: 'sendAjax_close', + value: function sendAjax_close() { + /** + * Отправка Этапа "Закрыть этап" + */ + var self = this; + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PATCH', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + //TODO: слать только изменения + data: { status: 'closed' }, + dataType: 'json' + }).done(function (json) { + // enableStageFields(json.id); + // $form.find('.error').html(""); + // self.enable(); + }).fail(function (xhr) { + console.log("Ошибка, которой не должно быть json -->", xhr.responseJSON); + })); + } + }]); + + return StageInWork; + }(); + + exports.StageForm = StageForm; + exports.StageReserved = StageReserved; + exports.StageInWork = StageInWork; + +/***/ }, +/* 15 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.MessagesController = undefined; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _utils = __webpack_require__(3); + + var _loaders = __webpack_require__(4); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var MessagesController = function () { + function MessagesController(orderId) { + _classCallCheck(this, MessagesController); + + console.log('Create MessagesController'); + var self = this; + this.orderId = orderId; + this.$inbox = $('#message-chat-order-space'); + this.$inbox.html(""); + this.messageTemplate = (0, _loaders.loadTemplate)('message_tmpl'); + this.dataPromise = this.getMessagesData(); + this.dataPromise.then(self._onLoadData.bind(self)); + } + + _createClass(MessagesController, [{ + key: 'getMessagesData', + value: function getMessagesData() { + var self = this; + return Promise.resolve($.ajax({ + url: '/api/message', + type: 'GET', + data: { 'order': self.orderId, 'team__isnull': 'true' }, + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + dataType: 'json', + success: function success(json) { + console.log('Success Messages'); + } + })); + } + }, { + key: '_onLoadData', + value: function _onLoadData(json) { + var self = this; + // console.log('mesages json = ', json); + // console.log('$inbox = ', this.$inbox); + // console.log("messages render start"); + self.$inbox.html(""); + $.each(json.results, function (i, v) { + var senderName = 'Вы'; + var className = 'youChat'; + + if (v.sender.id !== userId) { + senderName = v.sender.username; + className = ''; + } + if (v.is_system) { + senderName = 'Системное'; + className = 'systemChat'; + } + var message = $(self.messageTemplate({ className: className, senderName: senderName, message: v })); + self.$inbox.append(message); + }); + // console.log("messages render complete"); + self.$inbox.scrollTop(self.$inbox.prop("scrollHeight")); + } + }]); + + return MessagesController; + }(); + + exports.MessagesController = MessagesController; + +/***/ }, +/* 16 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.DocumentsController = undefined; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _utils = __webpack_require__(3); + + var _loaders = __webpack_require__(4); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var DocumentsController = function () { + function DocumentsController(orderId) { + _classCallCheck(this, DocumentsController); + + console.log('Create MessagesController'); + var self = this; + this.orderId = orderId; + this.$container = $('#documentOrderSpace'); + this.$container.html(""); + + this.messageTemplate = (0, _loaders.loadTemplate)('document_attach_file_tmpl'); + this.dataPromise = this.getMessagesData(); + this.dataPromise.then(self._onLoadData.bind(self)); + } + + _createClass(DocumentsController, [{ + key: 'getMessagesData', + value: function getMessagesData() { + var self = this; + return Promise.resolve($.ajax({ + url: '/api/documents', + type: 'GET', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { + 'order': self.orderId, + 'is_delete': false, + 'is_send': true + }, + dataType: 'json', + // success: function (json) { + // + // }, + error: function error(e) { + console.log(e); + } + })); + } + }, { + key: 'addDocument', + value: function addDocument(json) {} + }, { + key: '_onLoadData', + value: function _onLoadData(json) { + var self = this; + // console.log('mesages json = ', json); + // console.log('$inbox = ', this.$inbox); + // console.log("messages render start"); + this.$container.html(""); + $.each(json.results, function (i, v) { + var document = $(self.messageTemplate({ + href: '/chat/download/\' + ' + v.file, + text: v.file, + document_id: v.id + })); + self.$container.append(document); + }); + // console.log("messages render complete"); + // self.$inbox.scrollTop(self.$inbox.prop("scrollHeight")); + } + }]); + + return DocumentsController; + }(); + + exports.DocumentsController = DocumentsController; + +/***/ }, +/* 17 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.bindDeleteContact = exports.bindTeams = exports.bindGetUserMessages = exports.bindUserContacts = exports.bindOnTabs = exports.bindArbitrationSend = exports.bindOrders = undefined; + + var _utils = __webpack_require__(3); + + var _messageCounters = __webpack_require__(18); + + var _loaders = __webpack_require__(4); + + 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'); + }); + } + + function bindOrders() { + $('.order-block').on('click', function (event) { + event.preventDefault(); + var $this = $(this); + (0, _messageCounters.onClickCardWithCount)($this); + $('.order-block').each(function (i, v) { + $(v).removeClass('orAct'); + }); + $this.addClass('orAct'); + var orderId = $this.data('id'); + var projectId = $this.data('project-id'); + var recipentId = $this.data('recipent-id'); + var orderName = $this.data('order-name'); + var secureOrder = $(this).data('secure-deal'); + secureOrder = Boolean(secureOrder); + window.location.hash = 'order' + orderId; + + $("#chat-order-add #orderId").val(orderId); + $("#add-form-order-note #orderNote").val(orderId); + $("#orderArbitrationId").val(orderId); + $("#projectReviewId").val(projectId); + $("#reserve-button").attr('data-order-id', orderId); + + $("#chat-order-add #recipentId").val(recipentId); + window.chatController.create(orderId, projectId, recipentId, orderName, secureOrder); + }); + $('.order-block .dimovChat').on('click', function (event) { + event.preventDefault(); + event.stopPropagation(); + // console.log('click on tr'); + }); + } + + function bindTeams() { + $('.team-block').on('click', function () { + (0, _messageCounters.onClickCardWithCount)($(this)); + $('.team-order-block, .team-block').each(function () { + $(this).removeClass('orAct'); + }); + $(this).addClass('orAct'); + + var teamIds = ''; + $.each($(this).find('.team-chat-user'), function (i, v) { + teamIds += $(this).attr('data-id') + ";"; + }); + $("#team-chat-form #teamIds").val(teamIds); + + var inbox = document.getElementById('message-chat-team-space'); + inbox.innerHTML = ''; + + var docList = document.getElementById('documentTeamSpace'); + docList.innerHTML = ''; + + var teamId = $(this).attr('data-team-id'); + location.hash = '#myteam' + teamId; + + // var newCount = parseInt($("#count-tab-team").text()); + // var currNewCount = parseInt($(".team-count-" + teamId).text()); + // var resCount = newCount - currNewCount; + // $("#count-tab-team").text(resCount); + $(".team-count-" + teamId).text(0); + + $("#team-chat-form #teamId").val(teamId); + $("#add-form-team-note #teamNote").val(teamId); + $("#team-chat-form #recipentTeamId").val(""); + $("#team-chat-form #orderTeamId").val(""); + $("#add-form-team-note #orderNote").val(""); + + $.ajax({ + url: '/api/message', + type: 'GET', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { 'team': teamId, 'order__isnull': 'true' }, + dataType: 'json', + success: function success(json) { + $.each(json.results, function (i, v) { + var senderName = 'Вы'; + var className = 'youChat'; + if (v.sender.id !== userId) { + 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', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { + 'team': teamId, + 'is_delete': false, + 'is_send': true + }, + dataType: 'json', + success: function success(json) { + $.each(json.results, function (i, v) { + docList.innerHTML += '
  • ' + v.file + '
  • '; + }); + }, + error: function error(e) { + console.log(e); + } + }); + + $.ajax({ + url: '/api/note/', + type: 'GET', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { 'team': teamId }, + dataType: 'json', + success: function success(json) { + console.log(json.results); + var noteHtmlInbox = ''; + var note_tmpl = (0, _loaders.loadTemplate)('note_tmpl'); + $.each(json.results, function (i, v) { + noteHtmlInbox += note_tmpl({ text: v.text }); + }); + $(".team-notes-block").html(noteHtmlInbox); + } + }); + }); + } + + function bindArbitrationSend() { + // TODO: Test it + $('#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 beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: formData, + dataType: 'json', + success: function success(json) { + console.log(json); + $("#arbitration-add").modal('hide'); + $.jGrowl("Обращение в арбитраж добавлено", { + life: 4000 + }); + }, + error: function error(e) { + console.log('error'); + console.log(e); + } + }); + }); + } + + function bindOnTabs() { + /** + * Биндит обработчики на Закладки + */ + $('a[data-toggle="tab"]').unbind().on('show.bs.tab', function (e) { + console.log("TAB!"); + var activeTab = $(this).attr('href').substring(1); + var liveHash = URI(location.href).hash(); + + switch (activeTab) { + case 'tab1': + setTimeout(function () { + if (liveHash.indexOf("#user") != -1) { + var userHashId = liveHash.replace("#user", ""); + $("#userBlock" + userHashId).trigger('click'); + } else { + $(".user-block").first().trigger('click'); + } + }, 100); + break; + + case 'tab2': + // console.log("tab2"); + setTimeout(function () { + if (liveHash.indexOf("#order") != -1) { + var ordHashId = liveHash.replace("#order", ""); + $("#orderBlock" + ordHashId).trigger('click'); + } else { + $(".order-block").first().trigger('click'); + } + }, 100); + break; + + case 'tab3': + setTimeout(function () { + console.log("on active TAB team"); + if (liveHash.indexOf("#teamorder") != -1) { + var teamHashId = liveHash.replace("#teamorder", ""); + $("#teamOrderBlock" + teamHashId).trigger('click'); + } else if (liveHash.indexOf("#myteam") != -1) { + 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); + + } + }); + } + + function bindUserContacts() { + $(".conMess").click('on', function (e) { + e.preventDefault(); + e.stopPropagation(); + + var userId = $(this).attr('data-id'); + $.ajax({ + url: '/api/users/' + userId + '/', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + dataType: 'json', + success: function success(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 error(e, jqxhr) { + console.log(e); + } + }); + }); + } + + function bindGetUserMessages() { + $('.user-block').on('click', function () { + (0, _messageCounters.onClickCardWithCount)($(this)); + // var newCount = parseInt($("#count-tab-contact").text()); + 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); + // var currNewCount = parseInt($(".contact-count-" + sumSenderRecipent).text()); + // var resCount = newCount - currNewCount; + // $("#count-tab-contact").text(resCount); + $(".contact-count-" + sumSenderRecipent).text(0); + var docList = document.getElementById('documentSpace'); + inbox.innerHTML = ''; + docList.innerHTML = ''; + + $.ajax({ + url: '/api/message', + type: 'GET', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { + 'operand': 'in', + 'sender_id': userId, + 'recipent_id': contactId + }, + dataType: 'json', + success: function success(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', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { + 'operand': 'in', + 'sender_id': userId, + 'recipent_id': contactId, + 'is_delete': false, + 'is_send': true + }, + dataType: 'json', + + success: function success(json) { + console.log(json); + + $.each(json.results, function (i, v) { + docList.innerHTML += '
  • ' + v.file + '
  • '; + }); + }, + error: function error(e) { + console.log(e); + } + }); + + $.ajax({ + url: '/api/note/', + type: 'GET', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { + 'operand': 'in', + 'sender_id': userId, + 'recipent_id': contactId + }, + dataType: 'json', + success: function success(json) { + console.log(json.results); + var noteHtmlInbox = ''; + var note_tmpl = (0, _loaders.loadTemplate)('note_tmpl'); + $.each(json.results, function (i, v) { + noteHtmlInbox += note_tmpl({ text: v.text }); + }); + $(".contractor-notes-block").html(noteHtmlInbox); + } + }); + }); + } + + function bindDeleteContact() { + $('.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 beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { 'sender_id': senderId, 'recipent_id': recipentId }, + dataType: 'json', + success: function success(json) { + + if (json.status == 'ok') { + _this.parent().remove(); + $("#message-chat-space").html(""); + } + }, + error: function error(e) { + console.log('error'); + console.log(e); + } + }); + }.bind(null, senderId, recipentId, _this), function () {}); + }); + } + + exports.bindOrders = bindOrders; + exports.bindArbitrationSend = bindArbitrationSend; + exports.bindOnTabs = bindOnTabs; + exports.bindUserContacts = bindUserContacts; + exports.bindGetUserMessages = bindGetUserMessages; + exports.bindTeams = bindTeams; + exports.bindDeleteContact = bindDeleteContact; + +/***/ }, +/* 18 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + function recalculateTabsCounter() { + // let tabs = [$('#count-tab-contact'), $('#count-tab-order'), $('#count-tab-team')] + var tabs = [$('#tab1'), $('#tab2'), $('#tab3')]; + var total_messages_count = 0; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = tabs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var tab = _step.value; + + var count_sum = Array.from(tab.find('.js-count').map(function (i, el) { + return parseInt($(el).html()); + })).reduce(function (a, b) { + return a + b; + }, 0); + var $tab_counter = $('a[href="#' + tab.attr('id') + '"]').find('.count-tab'); + $tab_counter.html(count_sum); + total_messages_count += count_sum; + // console.log($tab_counter, 'new value -->', count_sum); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var $header_counter = $('.js-all-messages'); + $header_counter.html(total_messages_count); + } + + function countPlus(message, place) { + /** + * Увеличиваем счетчик соответствующий сообщению(message) + */ + // console.log("MESSAGE = ", message); + var $container = void 0; + if (message.answer_type == "add_message_contact") { + $container = $('.contact-count-' + message.sender_id); + } else if (message.answer_type == "add_message_order") { + $container = $('#count-order-' + message.order_id); + } else if (message.answer_type == "add_message_team") { + $container = $('#count-team-' + message.team_id); + } + // console.log("container = ", $container); + $container.html(parseInt($container.html()) + 1); + recalculateTabsCounter(); + } + + function onClickCardWithCount($card) { + /** + * При нажатии на карточку со счетчиком новых сообщений + */ + // console.log('Обнулем счетчик ', $card); + $card.find('.js-count').html(0); + recalculateTabsCounter(); + } + + exports.countPlus = countPlus; + exports.onClickCardWithCount = onClickCardWithCount; + +/***/ }, +/* 19 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.bindRemoveDocuments = exports.uploadDocumentsTeamInit = exports.uploadDocumentsOrderInit = exports.uploadDocumentsContactInit = undefined; + + var _utils = __webpack_require__(3); + + function uploadDocumentsContactInit() { + $("#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 beforeSend(xhr, settings) { + console.log("Upload form data -->", this.formData); + $('#progress .progress-bar').css('width', '0%'); + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + dataType: 'json', + done: function done(e, data) { + $.each(data.result.files, function (index, file) { + var htmlImg = ''; + var document_send = $(htmlImg).appendTo("#document-send-contact"); + }); + }, + fail: function fail(e) { + console.log(e); + }, + progressall: function progressall(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'); + } + + function uploadDocumentsOrderInit() { + $("#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 beforeSend(xhr, settings) { + $('#progress .progress-bar').css('width', '0%'); + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + dataType: 'json', + done: function done(e, data) { + $.each(data.result.files, function (index, file) { + var htmlImg = ''; + var document_send = $(htmlImg).appendTo("#document-send-order"); + }); + }, + fail: function fail(e) { + console.log(e); + }, + progressall: function progressall(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'); + } + + function uploadDocumentsTeamInit() { + $("#upload-document-team").bind('fileuploadsubmit', function (e, data) { + data.formData = { + sender: $("#team-chat-form #senderTeamId").val(), + recipent: $("#team-chat-form #recipentTeamId").val(), + order: $("#team-chat-form #orderTeamId").val(), + team: $("#team-chat-form #teamId").val() + }; + console.log(data.formData); + }); + + $('#upload-document-team').fileupload({ + url: '/chat/create/', + crossDomain: false, + beforeSend: function beforeSend(xhr, settings) { + $('#progress .progress-bar').css('width', '0%'); + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + dataType: 'json', + done: function done(e, data) { + $.each(data.result.files, function (index, file) { + var currentValue = $("#documentSendIds").val(); + currentValue += file.id + ';'; + $("#documentSendIds").val(currentValue); + var htmlImg = ''; + var document_send = $(htmlImg).appendTo("#document-send"); + }); + }, + fail: function fail(e) { + console.log(e); + }, + progressall: function progressall(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'); + } + + function bindRemoveDocuments() { + $('.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 beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { is_delete: true }, + dataType: 'json', + success: function success(json) { + _this.parent().remove(); + console.log(json); + }, + error: function error(e, jqxhr) { + console.log(jqxhr); + } + }); + }); + } + + exports.uploadDocumentsContactInit = uploadDocumentsContactInit; + exports.uploadDocumentsOrderInit = uploadDocumentsOrderInit; + exports.uploadDocumentsTeamInit = uploadDocumentsTeamInit; + exports.bindRemoveDocuments = bindRemoveDocuments; + +/***/ }, +/* 20 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.bindTeamNotes = exports.bindOrderNotes = exports.bindContractorNotes = undefined; + + var _loaders = __webpack_require__(4); + + var note_tmpl = (0, _loaders.loadTemplate)('note_tmpl'); + + function bindContractorNotes() { + $('#add-note-contractor').on('click', function (e) { + e.preventDefault(); + $.ajax({ + url: '/api/note/', + type: 'POST', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + data: $("#add-form-contractor-note").serialize(), + dataType: 'json', + success: function success(json) { + console.log(json); + $("#add-form-contractor-note #chat2").val(""); + var li = note_tmpl({ text: json.text }); + $(li).appendTo(".contractor-notes-block"); + }, + error: function error(e) { + console.log('error'); + console.log(e); + } + }); + }); + } + + function bindOrderNotes() { + $('#add-note-button').on('click', function (e) { + e.preventDefault(); + $.ajax({ + url: '/api/note/', + type: 'POST', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + data: $("#add-form-order-note").serialize(), + dataType: 'json', + success: function success(json) { + // $("
  • " + json.text + "
  • ").appendTo(".order-notes-block"); + var li = note_tmpl({ text: json.text }); + $(li).appendTo(".order-notes-block"); + $("#add-form-order-note #chat2").val(""); + }, + error: function error(e) { + console.log('error'); + console.log(e); + } + }); + }); + } + + function bindTeamNotes() { + $('#add-team-note-button').on('click', function (e) { + e.preventDefault(); + $.ajax({ + url: '/api/note/', + type: 'POST', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + data: $("#add-form-team-note").serialize(), + dataType: 'json', + success: function success(json) { + $("
  • " + json.text + "
  • ").appendTo(".team-notes-block"); + $("#add-form-team-note #chat2").val(""); + }, + error: function error(e) { + console.log('error'); + console.log(e); + } + }); + }); + } + + exports.bindContractorNotes = bindContractorNotes; + exports.bindOrderNotes = bindOrderNotes; + exports.bindTeamNotes = bindTeamNotes; + +/***/ }, +/* 21 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.restoreTabFromHash = undefined; + + var _utils = __webpack_require__(3); + + function restoreTabFromHash() { + var currentHash = URI(location.href).hash(); + if (currentHash.indexOf("#order") == 0) { + $("a[href='#tab2']").trigger('click'); + // console.log("click on ", "#orderBlock" + currentHash.replace("#order", "")); + var obj_id = currentHash.replace("#order", ""); + console.log("obj_id = ", obj_id); + if (obj_id) { + $("#orderBlock" + currentHash.replace("#order", "")).trigger('click'); + } else { + $('.order-block').first().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'); + } + } + + exports.restoreTabFromHash = restoreTabFromHash; + +/***/ }, +/* 22 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.bindArchiveProjects = undefined; + + var _utils = __webpack_require__(3); + + function bindArchiveProjects() { + // Нажимаем на кнопку архивные сообщения + $("#trashed-button").on('click', function (e) { + e.preventDefault(); + var state = $(this).attr('data-show'); + var trashedOrderHtml = ""; + + if (state == 'true') { + $(this).attr('data-show', 'false'); + $(this).text("Скрыть архивные заказы"); + + $("#archive-space").show(); + $("#show-archive-label").show(); + } else { + $(this).attr('data-show', 'true'); + $(this).text("Показать архивные заказы"); + $("#archive-space").hide(); + $("#show-archive-label").hide(); + } + }); + + // Нажимаем на заказ в архмвных заказах + $(".messageBlock").on('click', '.trashedOrderBlock', function () { + var $this = $(this); + $("#chat-order-add").css("display", "none"); + $('.order-block, .trashedOrderBlock').each(function () { + $(this).removeClass('orAct'); + }); + $this.addClass('orAct'); + // var inbox = document.getElementById('message-chat-order-space'); + // var docList = document.getElementById('documentOrderSpace'); + // inbox.innerHTML = ''; + // docList.innerHTML = ''; + + + var orderId = $this.data('id'); + // let projectId = $this.data('project-id'); + // let recipentId = $this.data('recipent-id'); + // let orderName = $this.data('order-name'); + location.hash = '#order' + orderId; + // console.log(orderId); + window.chatController.create(orderId); + // $.ajax({ + // url: '/api/message', + // type: 'GET', + // beforeSend: function (xhr) { + // xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + // }, + // data: {'order': orderId, 'team__isnull': 'true'}, + // dataType: 'json', + // success: function (json) { + // $.each(json.results, function (i, v) { + // var senderName = 'Вы'; + // var className = 'youChat'; + // + // if (v.sender.id !== userId) { + // senderName = v.sender.username; + // className = ''; + // } + // + // inbox.innerHTML += '
    ' + + // '

    ' + senderName + '

    ' + v.created + '
    ' + + // '

    ' + v.text + '

    '; + // + // }); + // var height = inbox.scrollHeight; + // inbox.scrollTop = height; + // } + // }); + + // $("#order-stages").html(""); + // $("#completeWork").hide(); + // $("#add-form-order-note").hide(); + // $("#reserveSpace").hide(); + }); + } + + exports.bindArchiveProjects = bindArchiveProjects; + +/***/ }, +/* 23 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + function chatContactsInit() { + /** + * Bind на кнопку "Отправить" в Закладке "Личные контакты" + */ + $('#contact-chat-add-message').on('click', function (e) { + e.preventDefault(); + var chatMessage = $("#chat").val(); + var recipentId = $("#recipentContactId").val(); + var senderId = $("#senderContactId").val(); + var sendLinks = $("#document-send-contact a"); + + if (chatMessage || sendLinks.length > 0) { + $("#contact-chat-form .errorEmptyMessage").hide(); + + 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 = ", 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(); + } + }); + } + + function chatOrdersInit() { + /** + * Bind на кнопку "Отправить" в Закладке "Исполнители/Заказчики" + */ + $('#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(); + var sendLinks = $("#document-send-order a"); + if (chatMessage || sendLinks.length > 0) { + 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(); + } + }); + } + + function chatTeamsInit() { + $("#add-team-chat-message").on('click', function (e) { + e.preventDefault(); + var chatMessage = $("#team-chat-form #chatText").val(); + // var recipentId = $("#team-chat-form #recipentTeamId").val(); + var senderId = $("#team-chat-form #senderTeamId").val(); + var teamId = $("#team-chat-form #teamId").val(); + // var orderId = $("#team-chat-form #orderTeamId").val(); + var documentSendIds = $("#documentSendIds").val(); + var teamIds = $("#team-chat-form #teamIds").val(); + var sendLinks = $("#document-send a"); + if (chatMessage || sendLinks.length > 0) { + 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_team", + "data": { + "sender_id": senderId, + // "recipent_id": recipentId, + "chat_message": chatMessage, + "team_id": teamId, + "team_ids": teamIds, + // "order_id": orderId, + "document_send_links": sendLinkIds, + "document_data": { + "document_links": documentLinks, + "document_attach_files": documentAttachFiles + } + } + }); + + $("#team-chat-form #chatText").val(""); + $("#document-send").html(""); + $("#documentSendIds").val(""); + } else { + $("#team-chat-form .errorEmptyMessage").show(); + } + }); + } + + exports.chatContactsInit = chatContactsInit; + exports.chatOrdersInit = chatOrdersInit; + exports.chatTeamsInit = chatTeamsInit; + +/***/ }, +/* 24 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.connect = undefined; + + var _loaders = __webpack_require__(4); + + var _messageCounters = __webpack_require__(18); + + function getUserPlace() { + /** + * Определяем в какой закладке Чата пользователь + */ + var hash = location.hash; + var tab = void 0, + id = void 0; + + var _arr = ["user", "order", "myteam"]; + for (var _i = 0; _i < _arr.length; _i++) { + var str = _arr[_i]; + if (hash.indexOf('#' + str) != -1) { + tab = str; + id = hash.replace('#' + str, ''); + } + } + return { tab: tab, id: id }; + } + + function checkMessageInPlace(message, place) { + /** + * Проверяем, направлено ли входящее сообщение на текущую вкладку пользователя + */ + // message.answer_type=place.tab + var eq = ['add_message_contact=user', 'add_message_order=order', 'add_message_team=myteam', 'approve_stages=order']; + console.log([message.answer_type, place.tab].join('=')); + console.log(message.order_id, '==', place.id, message.order_id == place.id); + if (eq.indexOf([message.answer_type, place.tab].join('=')) != -1 && (message.order_id == place.id || message.recipent_id == place.id || message.sender_id == place.id || message.team_id == place.id)) { + + return true; + } + return false; + } + + function connect() { + wsConnect.then(function (_socket) { + socket = _socket; + // Onmessage in Chat page + socket.addEventListener("message", function (event) { + var data = JSON.parse(event.data); + print.ws_print("new message on Chat page"); + console.log(", message =", data); + + var user_place = getUserPlace(); + // console.log("User place ", place.tab, place.id); + + if (checkMessageInPlace(data, user_place)) { + console.log("Сообщение принято открытым чатом"); + var chat_container_selectors = { + "user": "#message-chat-space", + "order": "#message-chat-order-space", + "myteam": "#message-chat-team-space" + }; + var documents_container_seletors = { + "user": "#documentSpace", + "order": "#documentOrderSpace", + "myteam": "#documentTeamSpace" + }; + var $chat_container = $(chat_container_selectors[user_place.tab]); + var $documents_container = $(documents_container_seletors[user_place.tab]); + var classMessage = 'youChat'; + var senderName = 'Вы'; + if (data.sender_id != userId) { + senderName = data.sender_name; + classMessage = ''; + } + if (data.is_system) { + senderName = 'Системное'; + classMessage = 'systemChat'; + } + + var chat_message = (0, _loaders.loadTemplate)('message_tmpl')({ + className: classMessage, + senderName: senderName, + message: { created: data.msg_time, text: data.msg } + }); + $chat_container.append(chat_message); + $chat_container.scrollTop($chat_container.prop("scrollHeight")); + + $documents_container.append(data.docs_attach); + + if (data.answer_type == 'approve_stages') { + window.chatController.statesController.redraw(); + } + } else { + console.log("Сообщение учтено счетчиком"); + (0, _messageCounters.countPlus)(data, user_place); + } + }); + + socket.addEventListener("close", function () { + console.error("Connection Lost"); + connect(); + }); + + socket.send_message = function (messageData) { + console.log('send message -->', messageData); + socket.send(JSON.stringify(messageData)); + }; + + socket.send_stages_approve = function (messageData) { + // TODO: Пометить сообщения как "системные" + socket.send(JSON.stringify(messageData)); + }; + }); + wsConnect.catch(function (reason) { + console.error("Server is not available", reason); + }); + } + + exports.connect = connect; + +/***/ } +/******/ ]); \ No newline at end of file diff --git a/assets/js/build/chat_customer_oop.js b/assets/js/build/chat_customer_oop.js new file mode 100644 index 0000000..4d49282 --- /dev/null +++ b/assets/js/build/chat_customer_oop.js @@ -0,0 +1,2584 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _ChatCustomerPageController = __webpack_require__(25); + + var _BINDS = __webpack_require__(17); + + var _parts = __webpack_require__(21); + + var _chats = __webpack_require__(23); + + var _wsChatConnect = __webpack_require__(24); + + var _archiveProjects = __webpack_require__(22); + + window.connect = _wsChatConnect.connect; + window.socket = undefined; + + $(function () { + $('body').on('focus', ".term-picker", function () { + $(this).datepicker({ + minDate: 0 + }); + }); + + (0, _BINDS.bindArbitrationSend)(); + window.onhashchange = function (e) { + // console.log("Change Hash!!! ", 'a[data-toggle="tab"][href="#' + location.hash.slice(1) + '"]'); + $('a[data-toggle="tab"][href="#' + location.hash.slice(1) + '"]').trigger("click"); + }; + + window.chatController = new _ChatCustomerPageController.ChatPageController(); + (0, _BINDS.bindOrders)(); + (0, _BINDS.bindOnTabs)(); + (0, _parts.restoreTabFromHash)(); + (0, _BINDS.bindUserContacts)(); + (0, _BINDS.bindGetUserMessages)(); + (0, _archiveProjects.bindArchiveProjects)(); + (0, _BINDS.bindDeleteContact)(); + + //Chats + (0, _chats.chatContactsInit)(); + (0, _chats.chatOrdersInit)(); + }); + +/***/ }, +/* 1 */, +/* 2 */, +/* 3 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + function getCookie(name) { + var cookieValue = null; + if (document.cookie && document.cookie != '') { + var cookies = document.cookie.split(';'); + for (var i = 0; i < cookies.length; i++) { + var cookie = jQuery.trim(cookies[i]); + if (cookie.substring(0, name.length + 1) == name + '=') { + cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); + break; + } + } + } + return cookieValue; + } + + function humanFileSize(bytes, si) { + var thresh = si ? 1000 : 1024; + + if (Math.abs(bytes) < thresh) return bytes + ' B'; + + var units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; + + var u = -1; + + do { + bytes /= thresh; + ++u; + } while (Math.abs(bytes) >= thresh && u < units.length - 1); + + return bytes.toFixed(1) + ' ' + units[u]; + } + + exports.humanFileSize = humanFileSize; + exports.getCookie = getCookie; + +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.loadTemplate = undefined; + + var _stage_tmpl = __webpack_require__(5); + + var _stage_tmpl2 = _interopRequireDefault(_stage_tmpl); + + var _stage_approved_tmpl = __webpack_require__(6); + + var _stage_approved_tmpl2 = _interopRequireDefault(_stage_approved_tmpl); + + var _reserved_tmpl = __webpack_require__(7); + + var _reserved_tmpl2 = _interopRequireDefault(_reserved_tmpl); + + var _message_tmpl = __webpack_require__(8); + + var _message_tmpl2 = _interopRequireDefault(_message_tmpl); + + var _work_in_process_tmpl = __webpack_require__(9); + + var _work_in_process_tmpl2 = _interopRequireDefault(_work_in_process_tmpl); + + var _bntCompleteStage_tmpl = __webpack_require__(10); + + var _bntCompleteStage_tmpl2 = _interopRequireDefault(_bntCompleteStage_tmpl); + + var _btnSendReview_tmpl = __webpack_require__(11); + + var _btnSendReview_tmpl2 = _interopRequireDefault(_btnSendReview_tmpl); + + var _document_attach_file_tmpl = __webpack_require__(12); + + var _document_attach_file_tmpl2 = _interopRequireDefault(_document_attach_file_tmpl); + + var _note_tmpl = __webpack_require__(13); + + var _note_tmpl2 = _interopRequireDefault(_note_tmpl); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function loadTemplate(template_name) { + var templates = { + stage_tmpl: _stage_tmpl2.default, + stage_approved_tmpl: _stage_approved_tmpl2.default, + reserved_tmpl: _reserved_tmpl2.default, + message_tmpl: _message_tmpl2.default, + work_in_process_tmpl: _work_in_process_tmpl2.default, + bntCompleteStage_tmpl: _bntCompleteStage_tmpl2.default, + btnSendReview_tmpl: _btnSendReview_tmpl2.default, + document_attach_file_tmpl: _document_attach_file_tmpl2.default, + note_tmpl: _note_tmpl2.default + }; + + if (!templates[template_name]) throw new Error('Template ' + template_name + ' does not exist'); + return templates[template_name]; + } + + exports.loadTemplate = loadTemplate; + +/***/ }, +/* 5 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return '\n
    \n

    \u042D\u0422\u0410\u041F ' + this.stage_num + '

    \n
    \n \n \n

    \n \n \n

    \n \n

    \n \n \n \n \n

    \n \n \n

    \n
    \n
    '; + }; + +/***/ }, +/* 6 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n
    \n
    \n
    \n \u042D\u0422\u0410\u041F " + this.stage_num + "\n
    \n
    \n " + this.stage_status + "\n
    \n
    \n
    \n\n
    \n " + this.stage.name + "\n
    \n \u0420\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u044D\u0442\u0430\u043F\u0430\n
    \n " + this.stage.result + "\n
    \n \u0426\u0435\u043D\u0430\n
    \n " + this.stage.cost + " \u20BD\n
    \n \u0421\u0440\u043E\u043A\n
    \n \u0434\u043E " + this.stage.term + "\n
    \n\n
    "; + }; + +/***/ }, +/* 7 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n\n
  • \u0421\u0443\u043C\u043C\u0430 \u0437\u0430 \u044D\u0442\u0430\u043F " + this.stage.pos + "\n
    " + this.reserved_name + "
    \n
  • "; + }; + +/***/ }, +/* 8 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n
    \n
    \n

    " + this.senderName + "

    " + this.message.created + "\n
    \n

    " + this.message.text + "

    \n
    "; + }; + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n
    \n \u0412 \u0440\u0430\u0431\u043E\u0442\u0435: " + this.stage.name + "
    \n \u0420\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u044D\u0442\u0430\u043F\u0430: " + this.stage.result + "
    \n \u0421\u0440\u043E\u043A \u0441\u0434\u0430\u0447\u0438: " + this.stage.term + "
    \n " + this.stage.cost + " \u0440\n
    \n " + this.note_text + "\n
    \n
    "; + }; + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n"; + }; + +/***/ }, +/* 11 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return ""; + }; + +/***/ }, +/* 12 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "\n
  • \n " + this.text + "\n
    \n
  • \n\n"; + }; + +/***/ }, +/* 13 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.default = function (ctx) { + return _template.call(ctx, ctx); + }; + + function _template() { + return "
    \n
  • \n " + this.text + "\n
  • \n
    \n
    \n"; + }; + +/***/ }, +/* 14 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.StageInWork = exports.StageReserved = exports.StageForm = undefined; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _loaders = __webpack_require__(4); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + // new-stages-form + // update-stages-form + // remove-stages-form + + var StageForm = function () { + function StageForm($container, _ref) + // kwargs - auto generate from name_attributes + { + var orderId = _ref.orderId, + stage_num = _ref.stage_num, + stage_status = _ref.stage_status, + _ref$type = _ref.type, + type = _ref$type === undefined ? 'new' : _ref$type, + _ref$formNamePostfix = _ref.formNamePostfix, + formNamePostfix = _ref$formNamePostfix === undefined ? '-stages-form' : _ref$formNamePostfix, + template_name = _ref.template_name, + _ref$data = _ref.data, + data = _ref$data === undefined ? {} : _ref$data; + var kwargs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + stage_num: stage_num, + stage_status: stage_status, + form_name: type + formNamePostfix, + orderId: orderId, + stage: data + }; + + _classCallCheck(this, StageForm); + + // console.log('Stage form template_name = ', template_name); + this.orderId = orderId; + this._type = type; + this.$container = $container; + this.self_tmpl = (0, _loaders.loadTemplate)(template_name); + this.data = data; + this.$form = undefined; + this.stageId = type != 'new' ? data.id : undefined; + this.create(kwargs); + } + + _createClass(StageForm, [{ + key: 'create', + value: function create(kwargs) { + /** + * Добавление шаблона-формы Этапа на страницу + */ + var el = $(this.self_tmpl(kwargs)); + this.$container.append(el); + this.$form = el.find('form'); + // console.log("form --> ", this.$form); + if (this.$form.length) this.$form.find('input[name=cost]').mask('000000000'); + } + }, { + key: 'remove', + value: function remove() { + /** + * Удаление, при уменьшении кол-ва этапов + * return true - удаляем из [] stages + */ + if (this.type == 'new') { + this.$form.parent().remove(); + return true; + } + this.type = 'remove'; + // this.$form.removeClass('update-stages-form').addClass('remove-stages-form'); + return false; + } + }, { + key: 'restore', + value: function restore() { + /** + * Восстановление, при увеличении кол-ва этапов + */ + if (this.type == 'new') throw new Error("Попытка восстановить элемент с type='new'"); + this.type = 'update'; + // this.$form.removeClass('remove-stages-form').addClass('update-stages-form'); + } + }, { + key: 'disable', + value: function disable() { + this.$form.find('input').attr('readonly', true); + } + }, { + key: 'enable', + value: function enable() { + this.$form.find('input').attr('readonly', false); + } + }, { + key: 'hide', + value: function hide() { + this.$form.parent().hide(); + } + }, { + key: 'show', + value: function show() { + this.$form.parent().show(); + } + }, { + key: 'is_valid', + value: function is_valid() { + var self = this; + var mesage = 'Это поле обязательно'; + var valid = true; + //Очищаем старые ошибки + this.$form.find('.error').html(""); + // Отображаем новые + this.$form.find(":input:not([type=hidden])").each(function (i, v) { + if (!$(v).val()) { + self.$form.find('.error-' + $(v).attr("name")).html(mesage).css('color', 'red'); + valid = false; + } + }); + return valid; + } + }, { + key: 'sendAjax_approve', + value: function sendAjax_approve() { + /** + * Отправка Этапа "на согласование" + */ + var self = this; + // console.log("Send AJAX Approve"); + if (this.type == 'new') { + // console.log('new stages approve'); + return Promise.resolve($.ajax({ + // async: false, + url: '/api/stages/', + type: 'POST', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + data: this.$form.serialize(), + dataType: 'json' + }).done(function (json) { + self.type = 'update'; + self.disable(); + self.$form.find('.error').html(""); + // console.log("json -->", json); + self.stageId = json.id; + // console.log(json); + }).fail(function (xhr, errorMsg, error) { + console.log("ERROR, xhr", xhr); + $.each(xhr.responseJSON, function (i, v) { + self.$form.find('.error-' + i).html(v).css('color', 'red'); + // console.log(self.$form); + // console.log(v); + // console.log(i); + }); + })); + } else if (this.type == 'update') { + this.$form.find('input[name=status]').val('send_approve'); + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PUT', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + data: this.$form.serialize(), + dataType: 'json' + }).done(function (json) { + self.$form.find('.error').html(""); + self.disable(); + }).fail(function (xhr, errorMsg, error) { + $.each(xhr.responseJSON, function (i, v) { + self.$form.find('.error-' + i).html(v).css('color', 'red'); + console.log(v); + console.log(i); + }); + })); + } else if (this.type == 'remove') { + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'DELETE', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + dataType: 'json' + }).done(function (json) {}).fail(function (xhr, errorMsg, error) { + console.log("delete fail, json -->", xhr); + })); + } + } + }, { + key: 'sendAjax_accept', + value: function sendAjax_accept(secureOrder) { + /** + * "Согласовать" Этапы (Исполнителем) + */ + console.log("secureOrder = ", secureOrder); + console.log("set new status =", secureOrder ? 'agreed' : 'in_process'); + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PATCH', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + //TODO: слать только изменения + data: { + status: secureOrder ? 'agreed' : 'in_process' + }, + dataType: 'json' + })); + } + }, { + key: 'sendAjax_change', + value: function sendAjax_change() { + /** + * Отправка Этапа "Внести изменения" + */ + var self = this; + // this.$form.find('input[name=status]').val('not_agreed'); + // console.log("ajax Change form -->", this.$form); + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PATCH', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + //TODO: слать только изменения + data: { status: 'not_agreed' }, + dataType: 'json' + }).done(function (json) { + // enableStageFields(json.id); + // $form.find('.error').html(""); + self.enable(); + }).fail(function (xhr) { + console.log("Ошибка, которой не должно быть json -->", xhr.responseJSON); + })); + } + }, { + key: 'type', + set: function set(newType) { + this.$form.removeClass(this._type + '-stages-form').addClass(newType + '-stages-form'); + if (newType == 'remove') this.hide(); + if (newType == 'update') this.show(); + this._type = newType; + }, + get: function get() { + return this._type; + } + }]); + + return StageForm; + }(); + + var StageReserved = function () { + function StageReserved($container, _ref2) { + var _ref2$template_name = _ref2.template_name, + template_name = _ref2$template_name === undefined ? 'reserved_tmpl' : _ref2$template_name, + data = _ref2.data; + var kwargs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + reserved_cls: '', + reserved_name: '', + stage: data + }; + + _classCallCheck(this, StageReserved); + + // Вывод текста резервирования в зависимости от статуса этапа + var reserved_names = { + agreed: 'Не зарезервирована', + in_process: 'Зарезервирована', + completed: 'Зарезервирована', + closed: 'Переведена исполнителю' + }; + // Вывод текста резервирования в зависимости от статуса этапа + var reserved_classes = { + agreed: 'unreserved', + in_process: 'reserved', + completed: 'reserved', + closed: 'closed' + }; + kwargs.reserved_cls = reserved_classes[data.status]; + kwargs.reserved_name = reserved_names[data.status]; + this.data = data; + this.self_tmpl = (0, _loaders.loadTemplate)(template_name); + this.$container = $container; + this.create(kwargs); + } + + _createClass(StageReserved, [{ + key: 'create', + value: function create(kwargs) { + /** + * Добавление шаблона "Резервирование" Этапа на страницу + */ + this.$self = $(this.self_tmpl(kwargs)); + this.$container.append(this.$self); + // console.log("form --> ", this.$form); + // this.$form.find('input[name=cost]').mask('000000000'); + } + }]); + + return StageReserved; + }(); + + var StageInWork = function () { + function StageInWork($container, _ref3) { + var _ref3$template_name = _ref3.template_name, + template_name = _ref3$template_name === undefined ? 'work_in_process_tmpl' : _ref3$template_name, + _ref3$note_text = _ref3.note_text, + note_text = _ref3$note_text === undefined ? '' : _ref3$note_text, + data = _ref3.data; + var kwargs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { stage: data, note_text: note_text }; + + _classCallCheck(this, StageInWork); + + this.stageId = data.id; + this.data = data; + this.self_tmpl = (0, _loaders.loadTemplate)(template_name); + this.$container = $container; + this.create(kwargs); + } + + _createClass(StageInWork, [{ + key: 'create', + value: function create(kwargs) { + /** + * Добавление шаблона "Выполнение работы" Этапа на страницу + */ + this.$self = $(this.self_tmpl(kwargs)); + this.$container.append(this.$self); + } + }, { + key: 'hide', + value: function hide() { + this.$self.hide(); + } + }, { + key: 'sendAjax_complete', + value: function sendAjax_complete() { + /** + * Отправка Этапа "Закрыть этап" + */ + var self = this; + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PATCH', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + data: { status: 'completed' }, + dataType: 'json' + }).done(function (json) { + // enableStageFields(json.id); + // $form.find('.error').html(""); + // self.enable(); + }).fail(function (xhr) { + console.log("Ошибка, которой не должно быть json -->", xhr.responseJSON); + })); + } + }, { + key: 'sendAjax_close', + value: function sendAjax_close() { + /** + * Отправка Этапа "Закрыть этап" + */ + var self = this; + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PATCH', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + //TODO: слать только изменения + data: { status: 'closed' }, + dataType: 'json' + }).done(function (json) { + // enableStageFields(json.id); + // $form.find('.error').html(""); + // self.enable(); + }).fail(function (xhr) { + console.log("Ошибка, которой не должно быть json -->", xhr.responseJSON); + })); + } + }]); + + return StageInWork; + }(); + + exports.StageForm = StageForm; + exports.StageReserved = StageReserved; + exports.StageInWork = StageInWork; + +/***/ }, +/* 15 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.MessagesController = undefined; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _utils = __webpack_require__(3); + + var _loaders = __webpack_require__(4); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var MessagesController = function () { + function MessagesController(orderId) { + _classCallCheck(this, MessagesController); + + console.log('Create MessagesController'); + var self = this; + this.orderId = orderId; + this.$inbox = $('#message-chat-order-space'); + this.$inbox.html(""); + this.messageTemplate = (0, _loaders.loadTemplate)('message_tmpl'); + this.dataPromise = this.getMessagesData(); + this.dataPromise.then(self._onLoadData.bind(self)); + } + + _createClass(MessagesController, [{ + key: 'getMessagesData', + value: function getMessagesData() { + var self = this; + return Promise.resolve($.ajax({ + url: '/api/message', + type: 'GET', + data: { 'order': self.orderId, 'team__isnull': 'true' }, + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + dataType: 'json', + success: function success(json) { + console.log('Success Messages'); + } + })); + } + }, { + key: '_onLoadData', + value: function _onLoadData(json) { + var self = this; + // console.log('mesages json = ', json); + // console.log('$inbox = ', this.$inbox); + // console.log("messages render start"); + self.$inbox.html(""); + $.each(json.results, function (i, v) { + var senderName = 'Вы'; + var className = 'youChat'; + + if (v.sender.id !== userId) { + senderName = v.sender.username; + className = ''; + } + if (v.is_system) { + senderName = 'Системное'; + className = 'systemChat'; + } + var message = $(self.messageTemplate({ className: className, senderName: senderName, message: v })); + self.$inbox.append(message); + }); + // console.log("messages render complete"); + self.$inbox.scrollTop(self.$inbox.prop("scrollHeight")); + } + }]); + + return MessagesController; + }(); + + exports.MessagesController = MessagesController; + +/***/ }, +/* 16 */, +/* 17 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.bindDeleteContact = exports.bindTeams = exports.bindGetUserMessages = exports.bindUserContacts = exports.bindOnTabs = exports.bindArbitrationSend = exports.bindOrders = undefined; + + var _utils = __webpack_require__(3); + + var _messageCounters = __webpack_require__(18); + + var _loaders = __webpack_require__(4); + + 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'); + }); + } + + function bindOrders() { + $('.order-block').on('click', function (event) { + event.preventDefault(); + var $this = $(this); + (0, _messageCounters.onClickCardWithCount)($this); + $('.order-block').each(function (i, v) { + $(v).removeClass('orAct'); + }); + $this.addClass('orAct'); + var orderId = $this.data('id'); + var projectId = $this.data('project-id'); + var recipentId = $this.data('recipent-id'); + var orderName = $this.data('order-name'); + var secureOrder = $(this).data('secure-deal'); + secureOrder = Boolean(secureOrder); + window.location.hash = 'order' + orderId; + + $("#chat-order-add #orderId").val(orderId); + $("#add-form-order-note #orderNote").val(orderId); + $("#orderArbitrationId").val(orderId); + $("#projectReviewId").val(projectId); + $("#reserve-button").attr('data-order-id', orderId); + + $("#chat-order-add #recipentId").val(recipentId); + window.chatController.create(orderId, projectId, recipentId, orderName, secureOrder); + }); + $('.order-block .dimovChat').on('click', function (event) { + event.preventDefault(); + event.stopPropagation(); + // console.log('click on tr'); + }); + } + + function bindTeams() { + $('.team-block').on('click', function () { + (0, _messageCounters.onClickCardWithCount)($(this)); + $('.team-order-block, .team-block').each(function () { + $(this).removeClass('orAct'); + }); + $(this).addClass('orAct'); + + var teamIds = ''; + $.each($(this).find('.team-chat-user'), function (i, v) { + teamIds += $(this).attr('data-id') + ";"; + }); + $("#team-chat-form #teamIds").val(teamIds); + + var inbox = document.getElementById('message-chat-team-space'); + inbox.innerHTML = ''; + + var docList = document.getElementById('documentTeamSpace'); + docList.innerHTML = ''; + + var teamId = $(this).attr('data-team-id'); + location.hash = '#myteam' + teamId; + + // var newCount = parseInt($("#count-tab-team").text()); + // var currNewCount = parseInt($(".team-count-" + teamId).text()); + // var resCount = newCount - currNewCount; + // $("#count-tab-team").text(resCount); + $(".team-count-" + teamId).text(0); + + $("#team-chat-form #teamId").val(teamId); + $("#add-form-team-note #teamNote").val(teamId); + $("#team-chat-form #recipentTeamId").val(""); + $("#team-chat-form #orderTeamId").val(""); + $("#add-form-team-note #orderNote").val(""); + + $.ajax({ + url: '/api/message', + type: 'GET', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { 'team': teamId, 'order__isnull': 'true' }, + dataType: 'json', + success: function success(json) { + $.each(json.results, function (i, v) { + var senderName = 'Вы'; + var className = 'youChat'; + if (v.sender.id !== userId) { + 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', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { + 'team': teamId, + 'is_delete': false, + 'is_send': true + }, + dataType: 'json', + success: function success(json) { + $.each(json.results, function (i, v) { + docList.innerHTML += '
  • ' + v.file + '
  • '; + }); + }, + error: function error(e) { + console.log(e); + } + }); + + $.ajax({ + url: '/api/note/', + type: 'GET', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { 'team': teamId }, + dataType: 'json', + success: function success(json) { + console.log(json.results); + var noteHtmlInbox = ''; + var note_tmpl = (0, _loaders.loadTemplate)('note_tmpl'); + $.each(json.results, function (i, v) { + noteHtmlInbox += note_tmpl({ text: v.text }); + }); + $(".team-notes-block").html(noteHtmlInbox); + } + }); + }); + } + + function bindArbitrationSend() { + // TODO: Test it + $('#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 beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: formData, + dataType: 'json', + success: function success(json) { + console.log(json); + $("#arbitration-add").modal('hide'); + $.jGrowl("Обращение в арбитраж добавлено", { + life: 4000 + }); + }, + error: function error(e) { + console.log('error'); + console.log(e); + } + }); + }); + } + + function bindOnTabs() { + /** + * Биндит обработчики на Закладки + */ + $('a[data-toggle="tab"]').unbind().on('show.bs.tab', function (e) { + console.log("TAB!"); + var activeTab = $(this).attr('href').substring(1); + var liveHash = URI(location.href).hash(); + + switch (activeTab) { + case 'tab1': + setTimeout(function () { + if (liveHash.indexOf("#user") != -1) { + var userHashId = liveHash.replace("#user", ""); + $("#userBlock" + userHashId).trigger('click'); + } else { + $(".user-block").first().trigger('click'); + } + }, 100); + break; + + case 'tab2': + // console.log("tab2"); + setTimeout(function () { + if (liveHash.indexOf("#order") != -1) { + var ordHashId = liveHash.replace("#order", ""); + $("#orderBlock" + ordHashId).trigger('click'); + } else { + $(".order-block").first().trigger('click'); + } + }, 100); + break; + + case 'tab3': + setTimeout(function () { + console.log("on active TAB team"); + if (liveHash.indexOf("#teamorder") != -1) { + var teamHashId = liveHash.replace("#teamorder", ""); + $("#teamOrderBlock" + teamHashId).trigger('click'); + } else if (liveHash.indexOf("#myteam") != -1) { + 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); + + } + }); + } + + function bindUserContacts() { + $(".conMess").click('on', function (e) { + e.preventDefault(); + e.stopPropagation(); + + var userId = $(this).attr('data-id'); + $.ajax({ + url: '/api/users/' + userId + '/', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + dataType: 'json', + success: function success(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 error(e, jqxhr) { + console.log(e); + } + }); + }); + } + + function bindGetUserMessages() { + $('.user-block').on('click', function () { + (0, _messageCounters.onClickCardWithCount)($(this)); + // var newCount = parseInt($("#count-tab-contact").text()); + 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); + // var currNewCount = parseInt($(".contact-count-" + sumSenderRecipent).text()); + // var resCount = newCount - currNewCount; + // $("#count-tab-contact").text(resCount); + $(".contact-count-" + sumSenderRecipent).text(0); + var docList = document.getElementById('documentSpace'); + inbox.innerHTML = ''; + docList.innerHTML = ''; + + $.ajax({ + url: '/api/message', + type: 'GET', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { + 'operand': 'in', + 'sender_id': userId, + 'recipent_id': contactId + }, + dataType: 'json', + success: function success(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', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { + 'operand': 'in', + 'sender_id': userId, + 'recipent_id': contactId, + 'is_delete': false, + 'is_send': true + }, + dataType: 'json', + + success: function success(json) { + console.log(json); + + $.each(json.results, function (i, v) { + docList.innerHTML += '
  • ' + v.file + '
  • '; + }); + }, + error: function error(e) { + console.log(e); + } + }); + + $.ajax({ + url: '/api/note/', + type: 'GET', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { + 'operand': 'in', + 'sender_id': userId, + 'recipent_id': contactId + }, + dataType: 'json', + success: function success(json) { + console.log(json.results); + var noteHtmlInbox = ''; + var note_tmpl = (0, _loaders.loadTemplate)('note_tmpl'); + $.each(json.results, function (i, v) { + noteHtmlInbox += note_tmpl({ text: v.text }); + }); + $(".contractor-notes-block").html(noteHtmlInbox); + } + }); + }); + } + + function bindDeleteContact() { + $('.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 beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { 'sender_id': senderId, 'recipent_id': recipentId }, + dataType: 'json', + success: function success(json) { + + if (json.status == 'ok') { + _this.parent().remove(); + $("#message-chat-space").html(""); + } + }, + error: function error(e) { + console.log('error'); + console.log(e); + } + }); + }.bind(null, senderId, recipentId, _this), function () {}); + }); + } + + exports.bindOrders = bindOrders; + exports.bindArbitrationSend = bindArbitrationSend; + exports.bindOnTabs = bindOnTabs; + exports.bindUserContacts = bindUserContacts; + exports.bindGetUserMessages = bindGetUserMessages; + exports.bindTeams = bindTeams; + exports.bindDeleteContact = bindDeleteContact; + +/***/ }, +/* 18 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + function recalculateTabsCounter() { + // let tabs = [$('#count-tab-contact'), $('#count-tab-order'), $('#count-tab-team')] + var tabs = [$('#tab1'), $('#tab2'), $('#tab3')]; + var total_messages_count = 0; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = tabs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var tab = _step.value; + + var count_sum = Array.from(tab.find('.js-count').map(function (i, el) { + return parseInt($(el).html()); + })).reduce(function (a, b) { + return a + b; + }, 0); + var $tab_counter = $('a[href="#' + tab.attr('id') + '"]').find('.count-tab'); + $tab_counter.html(count_sum); + total_messages_count += count_sum; + // console.log($tab_counter, 'new value -->', count_sum); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var $header_counter = $('.js-all-messages'); + $header_counter.html(total_messages_count); + } + + function countPlus(message, place) { + /** + * Увеличиваем счетчик соответствующий сообщению(message) + */ + // console.log("MESSAGE = ", message); + var $container = void 0; + if (message.answer_type == "add_message_contact") { + $container = $('.contact-count-' + message.sender_id); + } else if (message.answer_type == "add_message_order") { + $container = $('#count-order-' + message.order_id); + } else if (message.answer_type == "add_message_team") { + $container = $('#count-team-' + message.team_id); + } + // console.log("container = ", $container); + $container.html(parseInt($container.html()) + 1); + recalculateTabsCounter(); + } + + function onClickCardWithCount($card) { + /** + * При нажатии на карточку со счетчиком новых сообщений + */ + // console.log('Обнулем счетчик ', $card); + $card.find('.js-count').html(0); + recalculateTabsCounter(); + } + + exports.countPlus = countPlus; + exports.onClickCardWithCount = onClickCardWithCount; + +/***/ }, +/* 19 */, +/* 20 */, +/* 21 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.restoreTabFromHash = undefined; + + var _utils = __webpack_require__(3); + + function restoreTabFromHash() { + var currentHash = URI(location.href).hash(); + if (currentHash.indexOf("#order") == 0) { + $("a[href='#tab2']").trigger('click'); + // console.log("click on ", "#orderBlock" + currentHash.replace("#order", "")); + var obj_id = currentHash.replace("#order", ""); + console.log("obj_id = ", obj_id); + if (obj_id) { + $("#orderBlock" + currentHash.replace("#order", "")).trigger('click'); + } else { + $('.order-block').first().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'); + } + } + + exports.restoreTabFromHash = restoreTabFromHash; + +/***/ }, +/* 22 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.bindArchiveProjects = undefined; + + var _utils = __webpack_require__(3); + + function bindArchiveProjects() { + // Нажимаем на кнопку архивные сообщения + $("#trashed-button").on('click', function (e) { + e.preventDefault(); + var state = $(this).attr('data-show'); + var trashedOrderHtml = ""; + + if (state == 'true') { + $(this).attr('data-show', 'false'); + $(this).text("Скрыть архивные заказы"); + + $("#archive-space").show(); + $("#show-archive-label").show(); + } else { + $(this).attr('data-show', 'true'); + $(this).text("Показать архивные заказы"); + $("#archive-space").hide(); + $("#show-archive-label").hide(); + } + }); + + // Нажимаем на заказ в архмвных заказах + $(".messageBlock").on('click', '.trashedOrderBlock', function () { + var $this = $(this); + $("#chat-order-add").css("display", "none"); + $('.order-block, .trashedOrderBlock').each(function () { + $(this).removeClass('orAct'); + }); + $this.addClass('orAct'); + // var inbox = document.getElementById('message-chat-order-space'); + // var docList = document.getElementById('documentOrderSpace'); + // inbox.innerHTML = ''; + // docList.innerHTML = ''; + + + var orderId = $this.data('id'); + // let projectId = $this.data('project-id'); + // let recipentId = $this.data('recipent-id'); + // let orderName = $this.data('order-name'); + location.hash = '#order' + orderId; + // console.log(orderId); + window.chatController.create(orderId); + // $.ajax({ + // url: '/api/message', + // type: 'GET', + // beforeSend: function (xhr) { + // xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + // }, + // data: {'order': orderId, 'team__isnull': 'true'}, + // dataType: 'json', + // success: function (json) { + // $.each(json.results, function (i, v) { + // var senderName = 'Вы'; + // var className = 'youChat'; + // + // if (v.sender.id !== userId) { + // senderName = v.sender.username; + // className = ''; + // } + // + // inbox.innerHTML += '
    ' + + // '

    ' + senderName + '

    ' + v.created + '
    ' + + // '

    ' + v.text + '

    '; + // + // }); + // var height = inbox.scrollHeight; + // inbox.scrollTop = height; + // } + // }); + + // $("#order-stages").html(""); + // $("#completeWork").hide(); + // $("#add-form-order-note").hide(); + // $("#reserveSpace").hide(); + }); + } + + exports.bindArchiveProjects = bindArchiveProjects; + +/***/ }, +/* 23 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + function chatContactsInit() { + /** + * Bind на кнопку "Отправить" в Закладке "Личные контакты" + */ + $('#contact-chat-add-message').on('click', function (e) { + e.preventDefault(); + var chatMessage = $("#chat").val(); + var recipentId = $("#recipentContactId").val(); + var senderId = $("#senderContactId").val(); + var sendLinks = $("#document-send-contact a"); + + if (chatMessage || sendLinks.length > 0) { + $("#contact-chat-form .errorEmptyMessage").hide(); + + 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 = ", 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(); + } + }); + } + + function chatOrdersInit() { + /** + * Bind на кнопку "Отправить" в Закладке "Исполнители/Заказчики" + */ + $('#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(); + var sendLinks = $("#document-send-order a"); + if (chatMessage || sendLinks.length > 0) { + 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(); + } + }); + } + + function chatTeamsInit() { + $("#add-team-chat-message").on('click', function (e) { + e.preventDefault(); + var chatMessage = $("#team-chat-form #chatText").val(); + // var recipentId = $("#team-chat-form #recipentTeamId").val(); + var senderId = $("#team-chat-form #senderTeamId").val(); + var teamId = $("#team-chat-form #teamId").val(); + // var orderId = $("#team-chat-form #orderTeamId").val(); + var documentSendIds = $("#documentSendIds").val(); + var teamIds = $("#team-chat-form #teamIds").val(); + var sendLinks = $("#document-send a"); + if (chatMessage || sendLinks.length > 0) { + 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_team", + "data": { + "sender_id": senderId, + // "recipent_id": recipentId, + "chat_message": chatMessage, + "team_id": teamId, + "team_ids": teamIds, + // "order_id": orderId, + "document_send_links": sendLinkIds, + "document_data": { + "document_links": documentLinks, + "document_attach_files": documentAttachFiles + } + } + }); + + $("#team-chat-form #chatText").val(""); + $("#document-send").html(""); + $("#documentSendIds").val(""); + } else { + $("#team-chat-form .errorEmptyMessage").show(); + } + }); + } + + exports.chatContactsInit = chatContactsInit; + exports.chatOrdersInit = chatOrdersInit; + exports.chatTeamsInit = chatTeamsInit; + +/***/ }, +/* 24 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.connect = undefined; + + var _loaders = __webpack_require__(4); + + var _messageCounters = __webpack_require__(18); + + function getUserPlace() { + /** + * Определяем в какой закладке Чата пользователь + */ + var hash = location.hash; + var tab = void 0, + id = void 0; + + var _arr = ["user", "order", "myteam"]; + for (var _i = 0; _i < _arr.length; _i++) { + var str = _arr[_i]; + if (hash.indexOf('#' + str) != -1) { + tab = str; + id = hash.replace('#' + str, ''); + } + } + return { tab: tab, id: id }; + } + + function checkMessageInPlace(message, place) { + /** + * Проверяем, направлено ли входящее сообщение на текущую вкладку пользователя + */ + // message.answer_type=place.tab + var eq = ['add_message_contact=user', 'add_message_order=order', 'add_message_team=myteam', 'approve_stages=order']; + console.log([message.answer_type, place.tab].join('=')); + console.log(message.order_id, '==', place.id, message.order_id == place.id); + if (eq.indexOf([message.answer_type, place.tab].join('=')) != -1 && (message.order_id == place.id || message.recipent_id == place.id || message.sender_id == place.id || message.team_id == place.id)) { + + return true; + } + return false; + } + + function connect() { + wsConnect.then(function (_socket) { + socket = _socket; + // Onmessage in Chat page + socket.addEventListener("message", function (event) { + var data = JSON.parse(event.data); + print.ws_print("new message on Chat page"); + console.log(", message =", data); + + var user_place = getUserPlace(); + // console.log("User place ", place.tab, place.id); + + if (checkMessageInPlace(data, user_place)) { + console.log("Сообщение принято открытым чатом"); + var chat_container_selectors = { + "user": "#message-chat-space", + "order": "#message-chat-order-space", + "myteam": "#message-chat-team-space" + }; + var documents_container_seletors = { + "user": "#documentSpace", + "order": "#documentOrderSpace", + "myteam": "#documentTeamSpace" + }; + var $chat_container = $(chat_container_selectors[user_place.tab]); + var $documents_container = $(documents_container_seletors[user_place.tab]); + var classMessage = 'youChat'; + var senderName = 'Вы'; + if (data.sender_id != userId) { + senderName = data.sender_name; + classMessage = ''; + } + if (data.is_system) { + senderName = 'Системное'; + classMessage = 'systemChat'; + } + + var chat_message = (0, _loaders.loadTemplate)('message_tmpl')({ + className: classMessage, + senderName: senderName, + message: { created: data.msg_time, text: data.msg } + }); + $chat_container.append(chat_message); + $chat_container.scrollTop($chat_container.prop("scrollHeight")); + + $documents_container.append(data.docs_attach); + + if (data.answer_type == 'approve_stages') { + window.chatController.statesController.redraw(); + } + } else { + console.log("Сообщение учтено счетчиком"); + (0, _messageCounters.countPlus)(data, user_place); + } + }); + + socket.addEventListener("close", function () { + console.error("Connection Lost"); + connect(); + }); + + socket.send_message = function (messageData) { + console.log('send message -->', messageData); + socket.send(JSON.stringify(messageData)); + }; + + socket.send_stages_approve = function (messageData) { + // TODO: Пометить сообщения как "системные" + socket.send(JSON.stringify(messageData)); + }; + }); + wsConnect.catch(function (reason) { + console.error("Server is not available", reason); + }); + } + + exports.connect = connect; + +/***/ }, +/* 25 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.ChatPageController = undefined; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _StagesCustomerController = __webpack_require__(26); + + var _MessagesControllers = __webpack_require__(15); + + var _messageCounters = __webpack_require__(18); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var ChatPageController = function () { + function ChatPageController() { + _classCallCheck(this, ChatPageController); + + var self = this; + // console.log("NEW Chat CUSTOMER PageController"); + this.statesController = undefined; + this.messagesController = undefined; + // TODO: не забыть! + // recalculateMessages(); + } + + _createClass(ChatPageController, [{ + key: 'create', + value: function create(orderId, projectId, recipentId, orderName, secureOrder) { + this.statesController = new _StagesCustomerController.StagesController(orderId, projectId, recipentId, orderName, secureOrder); + this.messagesController = new _MessagesControllers.MessagesController(orderId); + } + }]); + + return ChatPageController; + }(); + + exports.ChatPageController = ChatPageController; + +/***/ }, +/* 26 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.StagesController = undefined; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _utils = __webpack_require__(3); + + var _loaders = __webpack_require__(4); + + var _Stages = __webpack_require__(14); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var message_format = { + "format_type": "approve_stages", + "data": { + "sender_id": "", + "recipent_id": "", + "order_id": "", + "msg": "", + "is_system": true + } + }; + + var STATUSES = { + 'not_agreed': 'не согласован', + 'send_approve': 'на согласовании', + 'agreed': 'согласовано', + 'cancel_approve': 'исполнитель отказался', + 'in_process': 'в процессе', + 'completed': 'завершен', + 'closed': 'закрыт' + + }; + + var StagesController = function () { + function StagesController(orderId, projectId, recipentId, orderName, secureOrder) { + _classCallCheck(this, StagesController); + + var self = this; + this.orderId = orderId; + this.orderName = orderName; + this.projectId = projectId; + this.recipentId = recipentId; + this.secureOrder = secureOrder; + this.data = {}; //JSON + this.stages = []; + this.stages_reserved = []; + this.stages_work = []; + this.STAGE_STATUSES = { + 'not_agreed': this.buildNotAgreedStage.bind(self), + 'send_approve': this.buildSendApproveStage.bind(self), + 'agreed': this.buildAgreedStage.bind(self), + 'in_process': this.buildProcessStage.bind(self), + 'completed': this.buildProcessStage.bind(self), + 'closed': this.buildProcessStage.bind(self) + }; + this.btnCompleteTmpl = (0, _loaders.loadTemplate)('bntCompleteStage_tmpl'); + this.btnSendReviewTmpl = (0, _loaders.loadTemplate)('btnSendReview_tmpl'); + this.$orderStagesContainer = $('#order-stages'); + this.$orderStagesContainer.html(''); + this.$stagesCount = $('#countStage'); + this.$stagesCount.unbind().on("change", this._changeNumStages.bind(self)); + this.$stagesCount.parent().show(); + this.buttons = { + btnApprove: $('#btnApprove'), + btnChange: $('#btnChange'), + btnToArchive: $('#btnToArchive'), + btnReserve: $('#btnReserve'), + btnsArbitration: $('.js-btnArbitration'), + btnSendReview: $('#order-review-add') + }; + this.stages_elements = { + $approve: $('#conditions-approve'), //1. Согласование условия + $reserve: $('#reserveSpace'), //2. Резервирование + $works: $('#completeWork') //3. Выполненная работа + }; + this.init(); + } + + _createClass(StagesController, [{ + key: 'init', + value: function init() { + var self = this; + + this.dataPromise = this.getOrderData({ orderId: this.orderId }); + this.dataPromise.then(self._onLoadData.bind(self)).catch(self._onLoadDataError.bind(self)); + } + }, { + key: 'getOrderData', + value: function getOrderData(_ref) { + var orderId = _ref.orderId; + + var self = this; + return Promise.resolve($.ajax({ + url: '/api/orders/' + orderId + '/', + dataType: 'json', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + } + })); + } + }, { + key: 'redraw', + value: function redraw() { + /** + * Полностью перерисовываем страницу Заказа + */ + console.log("Redraw customer stages"); + // $("#orderBlock" + this.orderId).trigger('click'); + this.init(); + } + }, { + key: 'buildStartStage', + value: function buildStartStage() { + /** + * Стадия: "Проект Предложен"(нет этапов) + */ + // Выделить цифру 1. красным + // $('#conditions-approve').find('.select') + this.$orderStagesContainer.show(); + this.buttons.btnApprove.show(); + this.buttons.btnChange.hide(); + this.buttons.btnToArchive.hide(); + this.$stagesCount.removeAttr('disabled'); + this.$stagesCount.val(1); + this.$stagesCount.trigger('change'); + // this.stages_elements.$approve.find('.js-help-text').show(); + // this.stages_elements.$reserve.find('.js-help-text').show(); + // this.stages_elements.$reserve.find('.stages-paid').hide(); + // this.stages_elements.$works.find('.js-help-text').show(); + // this.stages_elements.$works.find('#stagesWork').show(); + } // Нет Этапов + + }, { + key: 'buildNotAgreedStage', + value: function buildNotAgreedStage() { + console.log("Stage: not_agreed"); + this._renderStage('stage_tmpl'); + this.buttons.btnApprove.show(); + this.buttons.btnChange.hide(); + this.buttons.btnToArchive.hide(); + } // Статус "Не согласован" + + }, { + key: 'buildSendApproveStage', + value: function buildSendApproveStage() { + console.log("Stage: send_approve"); + this._renderStage('stage_tmpl', true); + this.$stagesCount.attr('disabled', true); + this.stages_elements.$reserve.hide(); + this.stages_elements.$works.hide(); + this.buttons.btnApprove.hide(); + this.buttons.btnChange.show(); + this.buttons.btnToArchive.show(); + } // Статус "На согласовании" + + }, { + key: 'buildAgreedStage', + value: function buildAgreedStage() { + console.log('Stage: agreed'); + this.buttons.btnApprove.hide(); + this.buttons.btnChange.hide(); + this.buttons.btnToArchive.hide(); + this.$stagesCount.parent().hide(); + this._renderStage('stage_approved_tmpl', true); + this.stages_elements.$approve.find('.js-help-text').hide(); + this.stages_elements.$reserve.find('.js-help-text').show(); + this.stages_elements.$reserve.show(); + this.buttons.btnReserve.show(); + this.buttons.btnsArbitration.show(); + this._renderStageReserved('reserved_tmpl'); + } // Статус "Согласован" + + }, { + key: 'buildProcessStage', + value: function buildProcessStage() { + console.log('Stage: in_process'); + this.buildAgreedStage(); + this.stages_elements.$reserve.find('.js-btnArbitration').hide(); + this.stages_elements.$works.show(); + this._renderStageInWork('work_in_process_tmpl'); + } // Статус "В процессе"/"Завершен"/"Закрыт" + + }, { + key: '_buildPage', + value: function _buildPage() { + // console.log("Build PAge"); + this.stages_elements.$reserve.hide(); + this.stages_elements.$works.hide(); + if (this.data.stages.length == 0) { + this.buildStartStage(); + } else { + var stageStatus = this.data.stages[0].status; + // console.log('stageStatus = ', stageStatus); + this.STAGE_STATUSES[stageStatus](); + } + this._bindEvents(); + } + }, { + key: '_renderStage', + value: function _renderStage(template_name) { + var disable = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var i = 0; + this.$orderStagesContainer.html(""); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = this.data.stages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var stage_data = _step.value; + + i++; + var stage = new _Stages.StageForm(this.$orderStagesContainer, { + orderId: this.orderId, stage_num: i, stage_status: STATUSES[stage_data.status], + type: 'update', template_name: template_name, data: stage_data + }); + if (disable) stage.disable(); + this.stages.push(stage); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + this.$stagesCount.val(i); + } + }, { + key: '_renderStageReserved', + value: function _renderStageReserved(template_name) { + var $container = this.stages_elements.$reserve.find('.stages-paid'); + $container.html(""); + this.stages_reserved = []; + // Нет незарезервированных Этапов + var has_not_reserved_stages = false; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = this.data.stages[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var stage_data = _step2.value; + + if (stage_data.status == 'agreed') has_not_reserved_stages = true; + var stage = new _Stages.StageReserved($container, { + template_name: template_name, data: stage_data + }); + this.stages_reserved.push(stage); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + if (!has_not_reserved_stages) { + this.buttons.btnReserve.hide(); + this.stages_elements.$reserve.find('.js-help-text').hide(); + } + } + }, { + key: '_renderStageInWork', + value: function _renderStageInWork(template_name) { + /** + * Отрисовываем блок "Выволнение работы", включая "Выполненныа работа" и "Оставить отзыв" + */ + var $container = this.stages_elements.$works.find('#stagesWork'); + $container.html(""); + var all_closed = this.data.stages.every(function (el) { + return el.status == 'closed'; + }); + if (all_closed) { + this.stages_elements.$works.find('.titleStepss').html('3. Выполненная работа'); + this.stages_elements.$works.find('.js-btnArbitration').hide(); + this.stages_elements.$works.find('.js-help-text').hide(); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = this.data.stages[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var stage_data = _step3.value; + + var stage = new _Stages.StageInWork($container, { + template_name: template_name, + data: stage_data, + note_text: 'Закройте этап или подробно опишите замечания в чате' + }); + this.stages_work.push(stage); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + if (!this.data.has_user_review) { + var btnReviewOpenModel = $(this.btnSendReviewTmpl()); + btnReviewOpenModel.unbind().on('click', this._onBtnReviewOpenModal.bind(this)); + // Если кнопка "Оставить отзыв" еще не добавлена - добавляем + if (!this.stages_elements.$works.find('#send-review').length) this.stages_elements.$works.append(btnReviewOpenModel); + } else { + if (this.stages_elements.$works.find('#send-review').length) this.stages_elements.$works.find('#send-review').remove(); + } + } else { + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = this.data.stages[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var _stage_data = _step4.value; + + if (_stage_data.status == 'closed') continue; + var _stage = new _Stages.StageInWork($container, { + template_name: template_name, data: _stage_data + }); + if (_stage_data.status == 'completed') { + var $btn = $(this.btnCompleteTmpl({ stage: _stage_data, text: 'Закрыть этап' })); + $container.html(); + $container.append($btn); + $btn.on('click', this._onBtnClose.bind(this, _stage)); + } + this.stages_work.push(_stage); + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + } + }, { + key: '_onLoadData', + value: function _onLoadData(json) { + this.data = json; + this._buildPage(); + } + }, { + key: '_changeNumStages', + value: function _changeNumStages(event) { + /** + * Изменяет кол-во этапов(stages) + */ + var newNumStages = parseInt($(event.target).val()); + if (newNumStages < 1 || isNaN(newNumStages)) { + newNumStages = 1; + this.$stagesCount.val(newNumStages); + } + var currentNumStages = $('.js-stage-form:not(.remove-stages-form)').length; + if (currentNumStages == newNumStages) return; + if (currentNumStages > newNumStages) { + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = this.stages.slice().reverse()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var stage = _step5.value; + + if (stage.remove()) { + var index = this.stages.indexOf(stage); + if (index >= 0) { + this.stages.splice(index, 1); + } + } + currentNumStages--; + if (currentNumStages == newNumStages) break; + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + } else { + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = this.stages.slice()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var _stage3 = _step6.value; + + if (_stage3.type == 'remove') { + _stage3.restore(); + } else continue; + currentNumStages++; + if (currentNumStages == newNumStages) break; + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + + while (currentNumStages < newNumStages) { + currentNumStages++; + var _stage2 = new _Stages.StageForm(this.$orderStagesContainer, { orderId: this.orderId, stage_num: currentNumStages, type: 'new', template_name: 'stage_tmpl' }); + this.stages.push(_stage2); + } + } + } //При изменении кол-ва этапов + + }, { + key: '_bindEvents', + value: function _bindEvents() { + var self = this; + this.buttons.btnApprove.unbind().on("click", this._onBtnApprove.bind(self)); + this.buttons.btnChange.unbind().on("click", this._onBtnChange.bind(self)); + this.buttons.btnToArchive.unbind().on("click", this._onBtnAToArchive.bind(self)); + this.buttons.btnReserve.unbind().on("click", this._onBtnReserve.bind(self)); + this.buttons.btnsArbitration.unbind().on("click", this._onBtnArbitration.bind(self)); + this.buttons.btnSendReview.unbind().on("click", this._onBtnSendReview.bind(self)); + $('#paymentfromSite').unbind().on('click', this._onBtnPaymentFromSite.bind(self)); + $("#reserve-stage-modal").find('#stage-num').unbind().on('change', function (event) { + // console.log("select stage cost = ", self.stages[this.value - 1].data.cost); + $("#reserve-stage-modal").find('#stage-cost').html(self.stages[this.value - 1].data.cost); + }); + } + + // BINDS + + }, { + key: '_onBtnApprove', + value: function _onBtnApprove(event) { + var _this = this; + + event.preventDefault(); + var self = this; + if (!this.stages.every(function (el) { + return el.is_valid(); + })) { + console.error('Не все поля форм валидны'); + return; + } + // При выполнении всех ajax запросов + Promise.all(this.stages.map(function (el) { + return el.sendAjax_approve(); + })).then(function () { + _this.buttons.btnApprove.hide(); + _this.buttons.btnChange.show(); + _this.buttons.btnToArchive.show(); + _this.$stagesCount.attr('disabled', true); + // var currentRecipentId = $(self).data('id'); + // var secureOrder = true; + // + var message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = '\u0423\u0441\u043B\u043E\u0432\u0438\u044F \u0437\u0430\u043A\u0430\u0437\u0430 ' + self.orderName + ' \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u044B \u043D\u0430 \u0441\u043E\u0433\u043B\u0430\u0441\u043E\u0432\u0430\u043D\u0438\u0435'; + console.log("Send-WS Отправить на согласование"); + socket.send_stages_approve(message); + //TODO: раскомментировать дурацкое окно + // $('#popupOk').modal('show'); + // }) + }); + } // "Отправить на согласование" + + }, { + key: '_onBtnChange', + value: function _onBtnChange(event) { + var _this2 = this; + + event.preventDefault(); + var self = this; + Promise.all(this.stages.map(function (el) { + return el.sendAjax_change(); + })).then(function () { + _this2.buttons.btnApprove.show(); + _this2.buttons.btnChange.hide(); + _this2.buttons.btnToArchive.hide(); + _this2.$stagesCount.attr('disabled', false); + var message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = '\u0417\u0430\u043A\u0430\u0437 ' + self.orderName + ' \u043E\u0442\u043E\u0437\u0432\u0430\u043D \u0434\u043B\u044F \u0432\u043D\u0435\u0441\u0435\u043D\u0438\u044F \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439'; + console.log("Send-WS Внести изменения"); + socket.send_stages_approve(message); + }); + } // "Внести изменения" + + // TODO: test it + + }, { + key: '_onBtnAToArchive', + value: function _onBtnAToArchive(event) { + event.preventDefault(); + var self = this; + $.ajax({ + // async: false, + url: '/api/orders/' + this.orderId + '/', + type: 'DELETE', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + dataType: 'json' + }).done(function (json) { + console.log('delete complete'); + window.location.href = window.location.href.replace(getHash(), ""); + var message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = '\u0417\u0430\u043A\u0430\u0437\u0430 ' + self.orderName + ' \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u0435\u043D \u0432 \u0430\u0440\u0445\u0438\u0432'; + console.log("Send-WS Отправить в архив"); + socket.send_stages_approve(message); + }).fail(function (xhr, errorMsg, error) { + console.log("delete fail, json -->", xhr); + }); + } // "Отказаться и отправить в архив" + + }, { + key: '_onBtnReserve', + value: function _onBtnReserve(event) { + var self = this; + event.preventDefault(); + // Set modal-window params + var $modal = $("#reserve-stage-modal"); + var total_cost = this.stages.map(function (el) { + return parseInt(el.data.cost); + }).reduce(function (a, b) { + return a + b; + }, 0); + // console.log('total cost = ', total_cost); + $modal.find('#total-cost').html(total_cost); + + var $select_stageNum = $modal.find('#stage-num'); + $select_stageNum.find('option').remove().end(); + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = this.stages[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var stage = _step7.value; + + if (stage.data.is_paid) continue; + $select_stageNum.append(''); + } + // let $stage_cost = $modal.find('#stage-cost'); + // $stage_cost.html(self.stages[this.value - 1].data.cost); + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + + $modal.find('#stage-num').trigger('change'); + + $modal.modal('show'); + } // "Зарезервировать" --> Открывает модальное окно для резервирования + + }, { + key: '_onBtnPaymentFromSite', + value: function _onBtnPaymentFromSite(event) { + var self = this; + event.preventDefault(); + var $modal = $("#reserve-stage-modal"); + var sum = void 0, + stages_id = void 0; + if ($modal.find('input[name=choice_way]:checked').val() == 'all_stages') { + sum = $modal.find('#total-cost').html(); + stages_id = this.stages.map(function (el) { + return el.data.id; + }); + } else { + sum = $modal.find('#stage-cost').html(); + var num_stage = $modal.find('#stage-num').val() - 1; + stages_id = [this.stages[num_stage].data.id]; + } + $.ajax({ + url: '/wallets/payfromscore/', + type: 'POST', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: { + sum: sum, + stages_id: stages_id.join(';') + }, + dataType: 'json', + success: function success(json) { + // console.log('success pay stage, json ', json); + $("#reserve-stage-modal").modal('toggle'); + var message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = '\u0417\u0430\u043A\u0430\u0437\u0447\u0438\u043A \u0437\u0430\u0440\u0435\u0437\u0435\u0440\u0432\u0438\u0440\u043E\u0432\u0430\u043B \u0441\u0443\u043C\u043C\u0443 \u0434\u043B\u044F \u044D\u0442\u0430\u043F\u043E\u0432'; + console.log("Send-WS Оплата Этапа/Этапов"); + socket.send_stages_approve(message); + self.redraw(); + }, + error: function error(xhr) { + console.log('error pay stage, json', xhr.responseJSON); + $.jGrowl(xhr.responseJSON.message_error); + } + }); + } // Оплата с сайта(Счет на Proekton) + + }, { + key: '_onBtnClose', + value: function _onBtnClose(stage, event) { + event.preventDefault(); + var self = this; + stage.sendAjax_close().then(function (json) { + console.log("Этап закрыт успешно"); + var message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = '\u0417\u0430\u043A\u0430\u0437\u0447\u0438\u043A \u0437\u0430\u043A\u0440\u044B\u043B \u044D\u0442\u0430\u043F ' + json.name; + console.log("Send-WS Оплата Этапа/Этапов"); + socket.send_stages_approve(message); + self.redraw(); + }).catch(function (xhr) { + console.log("При закрытии этапа произошла ошибка -->", xhr); + }); + } // "Закрыть этап" + + }, { + key: '_onBtnReviewOpenModal', + value: function _onBtnReviewOpenModal(event) { + event.preventDefault(); + $('#review-add').modal('show'); + } // Открыть модальное окно "Оставить отзыв" + + }, { + key: '_onBtnSendReview', + value: function _onBtnSendReview(event) { + event.preventDefault(); + var self = this; + $('#projectReviewId').val(this.projectId); + $('#targetContractorId').val(this.recipentId); + var formData = $("#review-adds-form").serialize(); + $.ajax({ + url: '/api/reviews/', + type: 'POST', + beforeSend: function beforeSend(xhr) { + xhr.setRequestHeader("X-CSRFToken", (0, _utils.getCookie)('csrftoken')); + }, + data: formData, + dataType: 'json', + success: function success(json) { + $('#review-add').modal('hide'); + var message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = '\u041E\u0442\u0437\u044B\u0432 \u043D\u0430 \u0437\u0430\u043A\u0430\u0437 ' + self.orderName + ' \u043E\u0441\u0442\u0430\u0432\u043B\u0435\u043D'; + console.log("Send-WS Оставить отзыв"); + socket.send_stages_approve(message); + window.location = '/chat/#order'; + location.reload(); + // $("a[href='#tab2']").trigger('click'); + }, + error: function error(e) { + console.log('error'); + console.log(e); + } + }); + } // "Оставить отзыв" + + + }, { + key: '_onBtnArbitration', + value: function _onBtnArbitration(event) { + event.preventDefault(); + $("#arbitration-add").modal('show'); + } // "Обратиться в арбитраж" + + }, { + key: '_onLoadDataError', + value: function _onLoadDataError(error) { + console.log("Error loading data -->", error); + } + }]); + + return StagesController; + }(); + + exports.StagesController = StagesController; + +/***/ } +/******/ ]); \ No newline at end of file diff --git a/assets/js/build/contractor_filter.js b/assets/js/build/contractor_filter.js index 9c2e0fd..b2ec298 100644 --- a/assets/js/build/contractor_filter.js +++ b/assets/js/build/contractor_filter.js @@ -40,19 +40,20 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _custom_check = __webpack_require__(1); + var _custom_check = __webpack_require__(27); - var _extended_field = __webpack_require__(2); + var _extended_field = __webpack_require__(28); - var _ajax_set_filter = __webpack_require__(3); + var _ajax_set_filter = __webpack_require__(29); - var _filter_toggle = __webpack_require__(4); + var _filter_toggle = __webpack_require__(30); function paginateTo(pageNum) { var $form = $('#filter-form'); @@ -73,7 +74,8 @@ }); /***/ }, -/* 1 */ + +/***/ 27: /***/ function(module, exports) { "use strict"; @@ -102,7 +104,8 @@ exports.customCheckInit = customCheckInit; /***/ }, -/* 2 */ + +/***/ 28: /***/ function(module, exports) { 'use strict'; @@ -132,7 +135,8 @@ exports.extendedFieldInit = extendedFieldInit; /***/ }, -/* 3 */ + +/***/ 29: /***/ function(module, exports) { 'use strict'; @@ -195,7 +199,8 @@ exports.modUrl = modUrl; /***/ }, -/* 4 */ + +/***/ 30: /***/ function(module, exports) { 'use strict'; @@ -225,4 +230,5 @@ exports.filterToggleInit = filterToggleInit; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/create_project.js b/assets/js/build/create_project.js index a1c6db0..4ef741f 100644 --- a/assets/js/build/create_project.js +++ b/assets/js/build/create_project.js @@ -46,23 +46,23 @@ 'use strict'; - var _file_upload = __webpack_require__(5); + var _file_upload = __webpack_require__(31); - var _extended_field = __webpack_require__(2); + var _extended_field = __webpack_require__(28); - var _custom_check = __webpack_require__(1); + var _custom_check = __webpack_require__(27); - var _read_more = __webpack_require__(7); + var _read_more = __webpack_require__(32); - var _only_one_checkbox = __webpack_require__(8); + var _only_one_checkbox = __webpack_require__(33); - var _popups = __webpack_require__(9); + var _popups = __webpack_require__(34); - var _scroll_on_required = __webpack_require__(10); + var _scroll_on_required = __webpack_require__(35); - var _ajax_registration = __webpack_require__(11); + var _ajax_registration = __webpack_require__(36); - var _test_seeds = __webpack_require__(12); + var _test_seeds = __webpack_require__(37); function showHideRealry() { var check = $('#checkbox-sb-realty'); @@ -97,7 +97,76 @@ }); /***/ }, -/* 1 */ +/* 1 */, +/* 2 */, +/* 3 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + function getCookie(name) { + var cookieValue = null; + if (document.cookie && document.cookie != '') { + var cookies = document.cookie.split(';'); + for (var i = 0; i < cookies.length; i++) { + var cookie = jQuery.trim(cookies[i]); + if (cookie.substring(0, name.length + 1) == name + '=') { + cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); + break; + } + } + } + return cookieValue; + } + + function humanFileSize(bytes, si) { + var thresh = si ? 1000 : 1024; + + if (Math.abs(bytes) < thresh) return bytes + ' B'; + + var units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; + + var u = -1; + + do { + bytes /= thresh; + ++u; + } while (Math.abs(bytes) >= thresh && u < units.length - 1); + + return bytes.toFixed(1) + ' ' + units[u]; + } + + exports.humanFileSize = humanFileSize; + exports.getCookie = getCookie; + +/***/ }, +/* 4 */, +/* 5 */, +/* 6 */, +/* 7 */, +/* 8 */, +/* 9 */, +/* 10 */, +/* 11 */, +/* 12 */, +/* 13 */, +/* 14 */, +/* 15 */, +/* 16 */, +/* 17 */, +/* 18 */, +/* 19 */, +/* 20 */, +/* 21 */, +/* 22 */, +/* 23 */, +/* 24 */, +/* 25 */, +/* 26 */, +/* 27 */ /***/ function(module, exports) { "use strict"; @@ -126,7 +195,7 @@ exports.customCheckInit = customCheckInit; /***/ }, -/* 2 */ +/* 28 */ /***/ function(module, exports) { 'use strict'; @@ -156,9 +225,9 @@ exports.extendedFieldInit = extendedFieldInit; /***/ }, -/* 3 */, -/* 4 */, -/* 5 */ +/* 29 */, +/* 30 */, +/* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -168,7 +237,7 @@ }); exports.fileUploadInit = undefined; - var _utils = __webpack_require__(6); + var _utils = __webpack_require__(3); function fileUploadInit() { var $fileUploadContainer = $('#fileUploadContainer'); @@ -206,51 +275,7 @@ exports.fileUploadInit = fileUploadInit; /***/ }, -/* 6 */ -/***/ function(module, exports) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - function getCookie(name) { - var cookieValue = null; - if (document.cookie && document.cookie != '') { - var cookies = document.cookie.split(';'); - for (var i = 0; i < cookies.length; i++) { - var cookie = jQuery.trim(cookies[i]); - if (cookie.substring(0, name.length + 1) == name + '=') { - cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); - break; - } - } - } - return cookieValue; - } - - function humanFileSize(bytes, si) { - var thresh = si ? 1000 : 1024; - - if (Math.abs(bytes) < thresh) return bytes + ' B'; - - var units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; - - var u = -1; - - do { - bytes /= thresh; - ++u; - } while (Math.abs(bytes) >= thresh && u < units.length - 1); - - return bytes.toFixed(1) + ' ' + units[u]; - } - - exports.humanFileSize = humanFileSize; - exports.getCookie = getCookie; - -/***/ }, -/* 7 */ +/* 32 */ /***/ function(module, exports) { "use strict"; @@ -265,18 +290,12 @@ $target.siblings(".complete").toggle(); $target.toggleClass("less"); }); - - // $(".more").toggle(function () { - // $(this).text("less..").siblings(".complete").show(); - // }, function () { - // $(this).text("more..").siblings(".complete").hide(); - // }); } exports.readMoreInit = readMoreInit; /***/ }, -/* 8 */ +/* 33 */ /***/ function(module, exports) { "use strict"; @@ -307,7 +326,7 @@ exports.onlyOneCheckboxInit = onlyOneCheckboxInit; /***/ }, -/* 9 */ +/* 34 */ /***/ function(module, exports) { 'use strict'; @@ -362,7 +381,7 @@ exports.addMessage = addMessage; /***/ }, -/* 10 */ +/* 35 */ /***/ function(module, exports) { 'use strict'; @@ -382,7 +401,7 @@ exports.scrollOnRequiredInit = scrollOnRequiredInit; /***/ }, -/* 11 */ +/* 36 */ /***/ function(module, exports) { 'use strict'; @@ -480,7 +499,7 @@ exports.ajaxRegistrationInit = ajaxRegistrationInit; /***/ }, -/* 12 */ +/* 37 */ /***/ function(module, exports) { "use strict"; diff --git a/assets/js/build/create_worksell.js b/assets/js/build/create_worksell.js index 2bfaada..1312f0f 100644 --- a/assets/js/build/create_worksell.js +++ b/assets/js/build/create_worksell.js @@ -40,21 +40,22 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _image_upload = __webpack_require__(13); + var _image_upload = __webpack_require__(38); - var _scroll_on_required = __webpack_require__(10); + var _scroll_on_required = __webpack_require__(35); - var _popups = __webpack_require__(9); + var _popups = __webpack_require__(34); - var _ajax_registration = __webpack_require__(11); + var _ajax_registration = __webpack_require__(36); - var _ajax_send_form_data = __webpack_require__(14); + var _ajax_send_form_data = __webpack_require__(39); $(function () { (0, _image_upload.imageUploadInit)(); @@ -67,12 +68,8 @@ }); /***/ }, -/* 1 */, -/* 2 */, -/* 3 */, -/* 4 */, -/* 5 */, -/* 6 */ + +/***/ 3: /***/ function(module, exports) { 'use strict'; @@ -116,9 +113,8 @@ exports.getCookie = getCookie; /***/ }, -/* 7 */, -/* 8 */, -/* 9 */ + +/***/ 34: /***/ function(module, exports) { 'use strict'; @@ -173,7 +169,8 @@ exports.addMessage = addMessage; /***/ }, -/* 10 */ + +/***/ 35: /***/ function(module, exports) { 'use strict'; @@ -193,7 +190,8 @@ exports.scrollOnRequiredInit = scrollOnRequiredInit; /***/ }, -/* 11 */ + +/***/ 36: /***/ function(module, exports) { 'use strict'; @@ -291,8 +289,8 @@ exports.ajaxRegistrationInit = ajaxRegistrationInit; /***/ }, -/* 12 */, -/* 13 */ + +/***/ 38: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -302,7 +300,7 @@ }); exports.imageUploadInit = undefined; - var _utils = __webpack_require__(6); + var _utils = __webpack_require__(3); // function previewImg() { // let $fileUploadWidgets = $('.file-upload-widget'); @@ -371,7 +369,8 @@ // export {imageUploadInit, previewImg} /***/ }, -/* 14 */ + +/***/ 39: /***/ function(module, exports, __webpack_require__) { "use strict"; @@ -381,7 +380,7 @@ }); exports.sendFormData = undefined; - var _utils = __webpack_require__(6); + var _utils = __webpack_require__(3); function sendFormData(e) { e.preventDefault(); @@ -430,4 +429,5 @@ exports.sendFormData = sendFormData; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/custom_components.js b/assets/js/build/custom_components.js index 55dc7fe..b44253f 100644 --- a/assets/js/build/custom_components.js +++ b/assets/js/build/custom_components.js @@ -47,9 +47,9 @@ 'use strict'; - var _custom_select = __webpack_require__(15); + var _custom_select = __webpack_require__(40); - var _custom_check = __webpack_require__(1); + var _custom_check = __webpack_require__(27); $(function () { (0, _custom_select.customSelectInit)(); @@ -58,7 +58,7 @@ /***/ }, -/***/ 1: +/***/ 27: /***/ function(module, exports) { "use strict"; @@ -88,7 +88,7 @@ /***/ }, -/***/ 15: +/***/ 40: /***/ function(module, exports) { 'use strict'; diff --git a/assets/js/build/customer_profile.js b/assets/js/build/customer_profile.js index 1ace80c..aeffe42 100644 --- a/assets/js/build/customer_profile.js +++ b/assets/js/build/customer_profile.js @@ -40,19 +40,20 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _show_hide = __webpack_require__(16); + var _show_hide = __webpack_require__(41); - var _bootstrap_tabs = __webpack_require__(17); + var _bootstrap_tabs = __webpack_require__(42); - var _sort_by = __webpack_require__(18); + var _sort_by = __webpack_require__(43); - var _custom_check = __webpack_require__(1); + var _custom_check = __webpack_require__(27); $(function () { (0, _bootstrap_tabs.restoreTab)(); @@ -64,40 +65,8 @@ }); /***/ }, -/* 1 */ -/***/ function(module, exports) { - - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - function customCheckInit() { - function tuneCheckBoxes($boxes) { - var currentState = $boxes.find("input").prop("checked") ? 'checked' : 'not-checked'; - $boxes.find("div").hide(); - $boxes.find("div." + currentState).show(); - } - var $boxes = $('.custom-check'); - tuneCheckBoxes($boxes); - $boxes.on("click", function (e) { - var inside_checkBox = $(e.target).parent().find("input"); - inside_checkBox.prop("checked", !inside_checkBox.prop("checked")); - tuneCheckBoxes($boxes); - e.preventDefault(); - return false; - }); - } - - exports.customCheckInit = customCheckInit; - -/***/ }, -/* 2 */, -/* 3 */, -/* 4 */, -/* 5 */, -/* 6 */ +/***/ 3: /***/ function(module, exports) { 'use strict'; @@ -141,16 +110,38 @@ exports.getCookie = getCookie; /***/ }, -/* 7 */, -/* 8 */, -/* 9 */, -/* 10 */, -/* 11 */, -/* 12 */, -/* 13 */, -/* 14 */, -/* 15 */, -/* 16 */ + +/***/ 27: +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + function customCheckInit() { + function tuneCheckBoxes($boxes) { + var currentState = $boxes.find("input").prop("checked") ? 'checked' : 'not-checked'; + $boxes.find("div").hide(); + $boxes.find("div." + currentState).show(); + } + + var $boxes = $('.custom-check'); + tuneCheckBoxes($boxes); + $boxes.on("click", function (e) { + var inside_checkBox = $(e.target).parent().find("input"); + inside_checkBox.prop("checked", !inside_checkBox.prop("checked")); + tuneCheckBoxes($boxes); + e.preventDefault(); + return false; + }); + } + + exports.customCheckInit = customCheckInit; + +/***/ }, + +/***/ 41: /***/ function(module, exports) { "use strict"; @@ -166,7 +157,8 @@ exports.toggler = toggler; /***/ }, -/* 17 */ + +/***/ 42: /***/ function(module, exports) { "use strict"; @@ -201,7 +193,8 @@ exports.restoreTab = restoreTab; /***/ }, -/* 18 */ + +/***/ 43: /***/ function(module, exports, __webpack_require__) { "use strict"; @@ -211,7 +204,7 @@ }); exports.sortRealtyBy = undefined; - var _utils = __webpack_require__(6); + var _utils = __webpack_require__(3); function sortRealtyBy(data, container_id) { console.log("sort_by = ", data); @@ -234,4 +227,5 @@ exports.sortRealtyBy = sortRealtyBy; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/debugUtilsInit.js b/assets/js/build/debugUtilsInit.js new file mode 100644 index 0000000..ce4e128 --- /dev/null +++ b/assets/js/build/debugUtilsInit.js @@ -0,0 +1,79 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ 0: +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _utils_debug = __webpack_require__(44); + + // DEBUG + window.print = {}; + window.print.ws_print = _utils_debug.ws_print; + +/***/ }, + +/***/ 44: +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + function ws_print() { + for (var _len = arguments.length, messages = Array(_len), _key = 0; _key < _len; _key++) { + messages[_key] = arguments[_key]; + } + + var message = messages.join(' '); + console.log('%c WS: ' + message, 'background: white; color: blue'); + } + + exports.ws_print = ws_print; + +/***/ } + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/home_page.js b/assets/js/build/home_page.js index 1043326..e6f7512 100644 --- a/assets/js/build/home_page.js +++ b/assets/js/build/home_page.js @@ -47,7 +47,7 @@ 'use strict'; - var _popupYoutube = __webpack_require__(19); + var _popupYoutube = __webpack_require__(45); $(function () { (0, _popupYoutube.popupYoutubeInit)(); @@ -55,7 +55,7 @@ /***/ }, -/***/ 19: +/***/ 45: /***/ function(module, exports) { 'use strict'; diff --git a/assets/js/build/init_contractor_filter.js b/assets/js/build/init_contractor_filter.js index 40e1cd2..d267aef 100644 --- a/assets/js/build/init_contractor_filter.js +++ b/assets/js/build/init_contractor_filter.js @@ -40,21 +40,22 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _SelectedContainer = __webpack_require__(20); + var _SelectedContainer = __webpack_require__(46); var _SelectedContainer2 = _interopRequireDefault(_SelectedContainer); - var _NoTreeSelect = __webpack_require__(24); + var _NoTreeSelect = __webpack_require__(50); var _NoTreeSelect2 = _interopRequireDefault(_NoTreeSelect); - var _TreeSelect = __webpack_require__(26); + var _TreeSelect = __webpack_require__(52); var _TreeSelect2 = _interopRequireDefault(_TreeSelect); @@ -120,26 +121,8 @@ }); /***/ }, -/* 1 */, -/* 2 */, -/* 3 */, -/* 4 */, -/* 5 */, -/* 6 */, -/* 7 */, -/* 8 */, -/* 9 */, -/* 10 */, -/* 11 */, -/* 12 */, -/* 13 */, -/* 14 */, -/* 15 */, -/* 16 */, -/* 17 */, -/* 18 */, -/* 19 */, -/* 20 */ + +/***/ 46: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -154,15 +137,15 @@ var _desc, _value, _class; // ` - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); - var _decorators = __webpack_require__(23); + var _decorators = __webpack_require__(49); var _decorators2 = _interopRequireDefault(_decorators); @@ -394,7 +377,8 @@ exports.default = SelectedContainer; /***/ }, -/* 21 */ + +/***/ 47: /***/ function(module, exports) { "use strict"; @@ -549,7 +533,8 @@ exports.default = DataTree; /***/ }, -/* 22 */ + +/***/ 48: /***/ function(module, exports) { "use strict"; @@ -605,7 +590,8 @@ exports.default = NoTreeData; /***/ }, -/* 23 */ + +/***/ 49: /***/ function(module, exports) { "use strict"; @@ -689,7 +675,8 @@ // export {onBind}; /***/ }, -/* 24 */ + +/***/ 50: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -703,9 +690,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); @@ -766,7 +753,8 @@ exports.default = NoTreeSelect; /***/ }, -/* 25 */ + +/***/ 51: /***/ function(module, exports) { "use strict"; @@ -1317,7 +1305,8 @@ exports.AbsBaseSelect = AbsBaseSelect; /***/ }, -/* 26 */ + +/***/ 52: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1331,9 +1320,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); @@ -1442,4 +1431,5 @@ exports.default = TreeSelect; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/init_create_worksell.js b/assets/js/build/init_create_worksell.js index dc2922f..b101cd1 100644 --- a/assets/js/build/init_create_worksell.js +++ b/assets/js/build/init_create_worksell.js @@ -40,33 +40,34 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _SelectedContainer = __webpack_require__(20); + var _SelectedContainer = __webpack_require__(46); var _SelectedContainer2 = _interopRequireDefault(_SelectedContainer); - var _SelectedContainerCreate = __webpack_require__(27); + var _SelectedContainerCreate = __webpack_require__(53); var _SelectedContainerCreate2 = _interopRequireDefault(_SelectedContainerCreate); - var _NoTreeSelect = __webpack_require__(24); + var _NoTreeSelect = __webpack_require__(50); var _NoTreeSelect2 = _interopRequireDefault(_NoTreeSelect); - var _TreeSelect = __webpack_require__(26); + var _TreeSelect = __webpack_require__(52); var _TreeSelect2 = _interopRequireDefault(_TreeSelect); - var _SingleTreeSelect = __webpack_require__(28); + var _SingleTreeSelect = __webpack_require__(54); var _SingleTreeSelect2 = _interopRequireDefault(_SingleTreeSelect); - var _SelectOrCreate = __webpack_require__(29); + var _SelectOrCreate = __webpack_require__(55); var _SelectOrCreate2 = _interopRequireDefault(_SelectOrCreate); @@ -167,26 +168,8 @@ }); /***/ }, -/* 1 */, -/* 2 */, -/* 3 */, -/* 4 */, -/* 5 */, -/* 6 */, -/* 7 */, -/* 8 */, -/* 9 */, -/* 10 */, -/* 11 */, -/* 12 */, -/* 13 */, -/* 14 */, -/* 15 */, -/* 16 */, -/* 17 */, -/* 18 */, -/* 19 */, -/* 20 */ + +/***/ 46: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -201,15 +184,15 @@ var _desc, _value, _class; // ` - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); - var _decorators = __webpack_require__(23); + var _decorators = __webpack_require__(49); var _decorators2 = _interopRequireDefault(_decorators); @@ -441,7 +424,8 @@ exports.default = SelectedContainer; /***/ }, -/* 21 */ + +/***/ 47: /***/ function(module, exports) { "use strict"; @@ -596,7 +580,8 @@ exports.default = DataTree; /***/ }, -/* 22 */ + +/***/ 48: /***/ function(module, exports) { "use strict"; @@ -652,7 +637,8 @@ exports.default = NoTreeData; /***/ }, -/* 23 */ + +/***/ 49: /***/ function(module, exports) { "use strict"; @@ -736,7 +722,8 @@ // export {onBind}; /***/ }, -/* 24 */ + +/***/ 50: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -750,9 +737,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); @@ -813,7 +800,8 @@ exports.default = NoTreeSelect; /***/ }, -/* 25 */ + +/***/ 51: /***/ function(module, exports) { "use strict"; @@ -1364,7 +1352,8 @@ exports.AbsBaseSelect = AbsBaseSelect; /***/ }, -/* 26 */ + +/***/ 52: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1378,9 +1367,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); @@ -1489,7 +1478,8 @@ exports.default = TreeSelect; /***/ }, -/* 27 */ + +/***/ 53: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1505,11 +1495,11 @@ var _desc, _value, _class; - var _SelectedContainer2 = __webpack_require__(20); + var _SelectedContainer2 = __webpack_require__(46); var _SelectedContainer3 = _interopRequireDefault(_SelectedContainer2); - var _decorators = __webpack_require__(23); + var _decorators = __webpack_require__(49); var _decorators2 = _interopRequireDefault(_decorators); @@ -1590,7 +1580,8 @@ exports.default = SelectedContainerCreate; /***/ }, -/* 28 */ + +/***/ 54: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1602,9 +1593,9 @@ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - var _AbsBaseSelect = __webpack_require__(25); + var _AbsBaseSelect = __webpack_require__(51); - var _TreeSelect2 = __webpack_require__(26); + var _TreeSelect2 = __webpack_require__(52); var _TreeSelect3 = _interopRequireDefault(_TreeSelect2); @@ -1685,7 +1676,8 @@ exports.default = SingleTreeSelect; /***/ }, -/* 29 */ + +/***/ 55: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1699,9 +1691,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); @@ -1923,4 +1915,5 @@ exports.default = SelectOrCreate; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/init_customer_project_create.js b/assets/js/build/init_customer_project_create.js index 6fd9edd..c6ea8eb 100644 --- a/assets/js/build/init_customer_project_create.js +++ b/assets/js/build/init_customer_project_create.js @@ -40,33 +40,34 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _SelectedContainer = __webpack_require__(20); + var _SelectedContainer = __webpack_require__(46); var _SelectedContainer2 = _interopRequireDefault(_SelectedContainer); - var _SelectedContainerCreate = __webpack_require__(27); + var _SelectedContainerCreate = __webpack_require__(53); var _SelectedContainerCreate2 = _interopRequireDefault(_SelectedContainerCreate); - var _NoTreeSelect = __webpack_require__(24); + var _NoTreeSelect = __webpack_require__(50); var _NoTreeSelect2 = _interopRequireDefault(_NoTreeSelect); - var _TreeSelect = __webpack_require__(26); + var _TreeSelect = __webpack_require__(52); var _TreeSelect2 = _interopRequireDefault(_TreeSelect); - var _SingleTreeSelect = __webpack_require__(28); + var _SingleTreeSelect = __webpack_require__(54); var _SingleTreeSelect2 = _interopRequireDefault(_SingleTreeSelect); - var _SelectOrCreate = __webpack_require__(29); + var _SelectOrCreate = __webpack_require__(55); var _SelectOrCreate2 = _interopRequireDefault(_SelectOrCreate); @@ -176,8 +177,10 @@ } else { //Если перешли со страницы профиля по кнопке "Добавить заказ" var id = window.location.hash.replace("#", ""); - if (id) sb_realty_top.setElementById(id); - select_realty.add(id); + if (id) { + sb_realty_top.setElementById(id); + select_realty.add(id); + } } }); select_realty.on("add", function (args) { @@ -212,26 +215,8 @@ }); /***/ }, -/* 1 */, -/* 2 */, -/* 3 */, -/* 4 */, -/* 5 */, -/* 6 */, -/* 7 */, -/* 8 */, -/* 9 */, -/* 10 */, -/* 11 */, -/* 12 */, -/* 13 */, -/* 14 */, -/* 15 */, -/* 16 */, -/* 17 */, -/* 18 */, -/* 19 */, -/* 20 */ + +/***/ 46: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -246,15 +231,15 @@ var _desc, _value, _class; // ` - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); - var _decorators = __webpack_require__(23); + var _decorators = __webpack_require__(49); var _decorators2 = _interopRequireDefault(_decorators); @@ -486,7 +471,8 @@ exports.default = SelectedContainer; /***/ }, -/* 21 */ + +/***/ 47: /***/ function(module, exports) { "use strict"; @@ -641,7 +627,8 @@ exports.default = DataTree; /***/ }, -/* 22 */ + +/***/ 48: /***/ function(module, exports) { "use strict"; @@ -697,7 +684,8 @@ exports.default = NoTreeData; /***/ }, -/* 23 */ + +/***/ 49: /***/ function(module, exports) { "use strict"; @@ -781,7 +769,8 @@ // export {onBind}; /***/ }, -/* 24 */ + +/***/ 50: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -795,9 +784,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); @@ -858,7 +847,8 @@ exports.default = NoTreeSelect; /***/ }, -/* 25 */ + +/***/ 51: /***/ function(module, exports) { "use strict"; @@ -1409,7 +1399,8 @@ exports.AbsBaseSelect = AbsBaseSelect; /***/ }, -/* 26 */ + +/***/ 52: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1423,9 +1414,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); @@ -1534,7 +1525,8 @@ exports.default = TreeSelect; /***/ }, -/* 27 */ + +/***/ 53: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1550,11 +1542,11 @@ var _desc, _value, _class; - var _SelectedContainer2 = __webpack_require__(20); + var _SelectedContainer2 = __webpack_require__(46); var _SelectedContainer3 = _interopRequireDefault(_SelectedContainer2); - var _decorators = __webpack_require__(23); + var _decorators = __webpack_require__(49); var _decorators2 = _interopRequireDefault(_decorators); @@ -1635,7 +1627,8 @@ exports.default = SelectedContainerCreate; /***/ }, -/* 28 */ + +/***/ 54: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1647,9 +1640,9 @@ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - var _AbsBaseSelect = __webpack_require__(25); + var _AbsBaseSelect = __webpack_require__(51); - var _TreeSelect2 = __webpack_require__(26); + var _TreeSelect2 = __webpack_require__(52); var _TreeSelect3 = _interopRequireDefault(_TreeSelect2); @@ -1730,7 +1723,8 @@ exports.default = SingleTreeSelect; /***/ }, -/* 29 */ + +/***/ 55: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1744,9 +1738,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); @@ -1968,4 +1962,5 @@ exports.default = SelectOrCreate; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/init_modal_realty_edit.js b/assets/js/build/init_modal_realty_edit.js index cfa039c..40767ed 100644 --- a/assets/js/build/init_modal_realty_edit.js +++ b/assets/js/build/init_modal_realty_edit.js @@ -40,37 +40,38 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _SelectedContainer = __webpack_require__(20); + var _SelectedContainer = __webpack_require__(46); var _SelectedContainer2 = _interopRequireDefault(_SelectedContainer); - var _SelectedContainerCreate = __webpack_require__(27); + var _SelectedContainerCreate = __webpack_require__(53); var _SelectedContainerCreate2 = _interopRequireDefault(_SelectedContainerCreate); - var _NoTreeSelect = __webpack_require__(24); + var _NoTreeSelect = __webpack_require__(50); var _NoTreeSelect2 = _interopRequireDefault(_NoTreeSelect); - var _TreeSelect = __webpack_require__(26); + var _TreeSelect = __webpack_require__(52); var _TreeSelect2 = _interopRequireDefault(_TreeSelect); - var _SingleTreeSelect = __webpack_require__(28); + var _SingleTreeSelect = __webpack_require__(54); var _SingleTreeSelect2 = _interopRequireDefault(_SingleTreeSelect); - var _SelectOrCreate = __webpack_require__(29); + var _SelectOrCreate = __webpack_require__(55); var _SelectOrCreate2 = _interopRequireDefault(_SelectOrCreate); - var _utils = __webpack_require__(6); + var _utils = __webpack_require__(3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -229,12 +230,8 @@ }); /***/ }, -/* 1 */, -/* 2 */, -/* 3 */, -/* 4 */, -/* 5 */, -/* 6 */ + +/***/ 3: /***/ function(module, exports) { 'use strict'; @@ -278,20 +275,8 @@ exports.getCookie = getCookie; /***/ }, -/* 7 */, -/* 8 */, -/* 9 */, -/* 10 */, -/* 11 */, -/* 12 */, -/* 13 */, -/* 14 */, -/* 15 */, -/* 16 */, -/* 17 */, -/* 18 */, -/* 19 */, -/* 20 */ + +/***/ 46: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -306,15 +291,15 @@ var _desc, _value, _class; // ` - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); - var _decorators = __webpack_require__(23); + var _decorators = __webpack_require__(49); var _decorators2 = _interopRequireDefault(_decorators); @@ -546,7 +531,8 @@ exports.default = SelectedContainer; /***/ }, -/* 21 */ + +/***/ 47: /***/ function(module, exports) { "use strict"; @@ -701,7 +687,8 @@ exports.default = DataTree; /***/ }, -/* 22 */ + +/***/ 48: /***/ function(module, exports) { "use strict"; @@ -757,7 +744,8 @@ exports.default = NoTreeData; /***/ }, -/* 23 */ + +/***/ 49: /***/ function(module, exports) { "use strict"; @@ -841,7 +829,8 @@ // export {onBind}; /***/ }, -/* 24 */ + +/***/ 50: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -855,9 +844,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); @@ -918,7 +907,8 @@ exports.default = NoTreeSelect; /***/ }, -/* 25 */ + +/***/ 51: /***/ function(module, exports) { "use strict"; @@ -1469,7 +1459,8 @@ exports.AbsBaseSelect = AbsBaseSelect; /***/ }, -/* 26 */ + +/***/ 52: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1483,9 +1474,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); @@ -1594,7 +1585,8 @@ exports.default = TreeSelect; /***/ }, -/* 27 */ + +/***/ 53: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1610,11 +1602,11 @@ var _desc, _value, _class; - var _SelectedContainer2 = __webpack_require__(20); + var _SelectedContainer2 = __webpack_require__(46); var _SelectedContainer3 = _interopRequireDefault(_SelectedContainer2); - var _decorators = __webpack_require__(23); + var _decorators = __webpack_require__(49); var _decorators2 = _interopRequireDefault(_decorators); @@ -1695,7 +1687,8 @@ exports.default = SelectedContainerCreate; /***/ }, -/* 28 */ + +/***/ 54: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1707,9 +1700,9 @@ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - var _AbsBaseSelect = __webpack_require__(25); + var _AbsBaseSelect = __webpack_require__(51); - var _TreeSelect2 = __webpack_require__(26); + var _TreeSelect2 = __webpack_require__(52); var _TreeSelect3 = _interopRequireDefault(_TreeSelect2); @@ -1790,7 +1783,8 @@ exports.default = SingleTreeSelect; /***/ }, -/* 29 */ + +/***/ 55: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1804,9 +1798,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); @@ -2028,4 +2022,5 @@ exports.default = SelectOrCreate; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/init_portfolio_create_edit.js b/assets/js/build/init_portfolio_create_edit.js index 120f626..c6dd2c7 100644 --- a/assets/js/build/init_portfolio_create_edit.js +++ b/assets/js/build/init_portfolio_create_edit.js @@ -40,29 +40,30 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _SelectedContainer = __webpack_require__(20); + var _SelectedContainer = __webpack_require__(46); var _SelectedContainer2 = _interopRequireDefault(_SelectedContainer); - var _SelectedContainerCreate = __webpack_require__(27); + var _SelectedContainerCreate = __webpack_require__(53); var _SelectedContainerCreate2 = _interopRequireDefault(_SelectedContainerCreate); - var _NoTreeSelect = __webpack_require__(24); + var _NoTreeSelect = __webpack_require__(50); var _NoTreeSelect2 = _interopRequireDefault(_NoTreeSelect); - var _TreeSelect = __webpack_require__(26); + var _TreeSelect = __webpack_require__(52); var _TreeSelect2 = _interopRequireDefault(_TreeSelect); - var _SelectOrCreate = __webpack_require__(29); + var _SelectOrCreate = __webpack_require__(55); var _SelectOrCreate2 = _interopRequireDefault(_SelectOrCreate); @@ -122,26 +123,8 @@ // import SingleTreeSelect from 'components/SingleTreeSelect' /***/ }, -/* 1 */, -/* 2 */, -/* 3 */, -/* 4 */, -/* 5 */, -/* 6 */, -/* 7 */, -/* 8 */, -/* 9 */, -/* 10 */, -/* 11 */, -/* 12 */, -/* 13 */, -/* 14 */, -/* 15 */, -/* 16 */, -/* 17 */, -/* 18 */, -/* 19 */, -/* 20 */ + +/***/ 46: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -156,15 +139,15 @@ var _desc, _value, _class; // ` - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); - var _decorators = __webpack_require__(23); + var _decorators = __webpack_require__(49); var _decorators2 = _interopRequireDefault(_decorators); @@ -396,7 +379,8 @@ exports.default = SelectedContainer; /***/ }, -/* 21 */ + +/***/ 47: /***/ function(module, exports) { "use strict"; @@ -551,7 +535,8 @@ exports.default = DataTree; /***/ }, -/* 22 */ + +/***/ 48: /***/ function(module, exports) { "use strict"; @@ -607,7 +592,8 @@ exports.default = NoTreeData; /***/ }, -/* 23 */ + +/***/ 49: /***/ function(module, exports) { "use strict"; @@ -691,7 +677,8 @@ // export {onBind}; /***/ }, -/* 24 */ + +/***/ 50: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -705,9 +692,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); @@ -768,7 +755,8 @@ exports.default = NoTreeSelect; /***/ }, -/* 25 */ + +/***/ 51: /***/ function(module, exports) { "use strict"; @@ -1319,7 +1307,8 @@ exports.AbsBaseSelect = AbsBaseSelect; /***/ }, -/* 26 */ + +/***/ 52: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1333,9 +1322,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); @@ -1444,7 +1433,8 @@ exports.default = TreeSelect; /***/ }, -/* 27 */ + +/***/ 53: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1460,11 +1450,11 @@ var _desc, _value, _class; - var _SelectedContainer2 = __webpack_require__(20); + var _SelectedContainer2 = __webpack_require__(46); var _SelectedContainer3 = _interopRequireDefault(_SelectedContainer2); - var _decorators = __webpack_require__(23); + var _decorators = __webpack_require__(49); var _decorators2 = _interopRequireDefault(_decorators); @@ -1545,8 +1535,8 @@ exports.default = SelectedContainerCreate; /***/ }, -/* 28 */, -/* 29 */ + +/***/ 55: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1560,9 +1550,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); @@ -1784,4 +1774,5 @@ exports.default = SelectOrCreate; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/init_worksell_filter.js b/assets/js/build/init_worksell_filter.js index 257de54..f31a639 100644 --- a/assets/js/build/init_worksell_filter.js +++ b/assets/js/build/init_worksell_filter.js @@ -40,21 +40,22 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _SelectedContainer = __webpack_require__(20); + var _SelectedContainer = __webpack_require__(46); var _SelectedContainer2 = _interopRequireDefault(_SelectedContainer); - var _NoTreeSelect = __webpack_require__(24); + var _NoTreeSelect = __webpack_require__(50); var _NoTreeSelect2 = _interopRequireDefault(_NoTreeSelect); - var _TreeSelect = __webpack_require__(26); + var _TreeSelect = __webpack_require__(52); var _TreeSelect2 = _interopRequireDefault(_TreeSelect); @@ -120,26 +121,8 @@ }); // ` /***/ }, -/* 1 */, -/* 2 */, -/* 3 */, -/* 4 */, -/* 5 */, -/* 6 */, -/* 7 */, -/* 8 */, -/* 9 */, -/* 10 */, -/* 11 */, -/* 12 */, -/* 13 */, -/* 14 */, -/* 15 */, -/* 16 */, -/* 17 */, -/* 18 */, -/* 19 */, -/* 20 */ + +/***/ 46: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -154,15 +137,15 @@ var _desc, _value, _class; // ` - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); - var _decorators = __webpack_require__(23); + var _decorators = __webpack_require__(49); var _decorators2 = _interopRequireDefault(_decorators); @@ -394,7 +377,8 @@ exports.default = SelectedContainer; /***/ }, -/* 21 */ + +/***/ 47: /***/ function(module, exports) { "use strict"; @@ -549,7 +533,8 @@ exports.default = DataTree; /***/ }, -/* 22 */ + +/***/ 48: /***/ function(module, exports) { "use strict"; @@ -605,7 +590,8 @@ exports.default = NoTreeData; /***/ }, -/* 23 */ + +/***/ 49: /***/ function(module, exports) { "use strict"; @@ -689,7 +675,8 @@ // export {onBind}; /***/ }, -/* 24 */ + +/***/ 50: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -703,9 +690,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _NoTreeData = __webpack_require__(22); + var _NoTreeData = __webpack_require__(48); var _NoTreeData2 = _interopRequireDefault(_NoTreeData); @@ -766,7 +753,8 @@ exports.default = NoTreeSelect; /***/ }, -/* 25 */ + +/***/ 51: /***/ function(module, exports) { "use strict"; @@ -1317,7 +1305,8 @@ exports.AbsBaseSelect = AbsBaseSelect; /***/ }, -/* 26 */ + +/***/ 52: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1331,9 +1320,9 @@ var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; - var _AbsBaseSelect2 = __webpack_require__(25); + var _AbsBaseSelect2 = __webpack_require__(51); - var _DataTree = __webpack_require__(21); + var _DataTree = __webpack_require__(47); var _DataTree2 = _interopRequireDefault(_DataTree); @@ -1442,4 +1431,5 @@ exports.default = TreeSelect; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/portfolio_create_edit.js b/assets/js/build/portfolio_create_edit.js index 691fc28..54b253e 100644 --- a/assets/js/build/portfolio_create_edit.js +++ b/assets/js/build/portfolio_create_edit.js @@ -40,17 +40,18 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _image_upload = __webpack_require__(13); + var _image_upload = __webpack_require__(38); - var _scroll_on_required = __webpack_require__(10); + var _scroll_on_required = __webpack_require__(35); - var _ajax_send_form_data = __webpack_require__(14); + var _ajax_send_form_data = __webpack_require__(39); $(function () { (0, _image_upload.imageUploadInit)(); @@ -60,12 +61,8 @@ }); /***/ }, -/* 1 */, -/* 2 */, -/* 3 */, -/* 4 */, -/* 5 */, -/* 6 */ + +/***/ 3: /***/ function(module, exports) { 'use strict'; @@ -109,10 +106,8 @@ exports.getCookie = getCookie; /***/ }, -/* 7 */, -/* 8 */, -/* 9 */, -/* 10 */ + +/***/ 35: /***/ function(module, exports) { 'use strict'; @@ -132,9 +127,8 @@ exports.scrollOnRequiredInit = scrollOnRequiredInit; /***/ }, -/* 11 */, -/* 12 */, -/* 13 */ + +/***/ 38: /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -144,7 +138,7 @@ }); exports.imageUploadInit = undefined; - var _utils = __webpack_require__(6); + var _utils = __webpack_require__(3); // function previewImg() { // let $fileUploadWidgets = $('.file-upload-widget'); @@ -213,7 +207,8 @@ // export {imageUploadInit, previewImg} /***/ }, -/* 14 */ + +/***/ 39: /***/ function(module, exports, __webpack_require__) { "use strict"; @@ -223,7 +218,7 @@ }); exports.sendFormData = undefined; - var _utils = __webpack_require__(6); + var _utils = __webpack_require__(3); function sendFormData(e) { e.preventDefault(); @@ -272,4 +267,5 @@ exports.sendFormData = sendFormData; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/project_filter.js b/assets/js/build/project_filter.js index 5a1d1e1..650c753 100644 --- a/assets/js/build/project_filter.js +++ b/assets/js/build/project_filter.js @@ -40,17 +40,18 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _custom_check = __webpack_require__(1); + var _custom_check = __webpack_require__(27); - var _extended_field = __webpack_require__(2); + var _extended_field = __webpack_require__(28); - var _ajax_set_filter = __webpack_require__(3); + var _ajax_set_filter = __webpack_require__(29); function paginateTo(pageNum) { var $form = $('#filter-form'); @@ -70,7 +71,8 @@ }); /***/ }, -/* 1 */ + +/***/ 27: /***/ function(module, exports) { "use strict"; @@ -99,7 +101,8 @@ exports.customCheckInit = customCheckInit; /***/ }, -/* 2 */ + +/***/ 28: /***/ function(module, exports) { 'use strict'; @@ -129,7 +132,8 @@ exports.extendedFieldInit = extendedFieldInit; /***/ }, -/* 3 */ + +/***/ 29: /***/ function(module, exports) { 'use strict'; @@ -192,4 +196,5 @@ exports.modUrl = modUrl; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/build/registration.js b/assets/js/build/registration.js index 47bfc2c..41b0ee2 100644 --- a/assets/js/build/registration.js +++ b/assets/js/build/registration.js @@ -47,7 +47,7 @@ 'use strict'; - var _popups = __webpack_require__(9); + var _popups = __webpack_require__(34); function checkHash() { // on load of the page: switch to the currently selected tab @@ -65,7 +65,7 @@ /***/ }, -/***/ 9: +/***/ 34: /***/ function(module, exports) { 'use strict'; diff --git a/assets/js/build/user_profile_edit.js b/assets/js/build/user_profile_edit.js index d022c14..5c9fe2d 100644 --- a/assets/js/build/user_profile_edit.js +++ b/assets/js/build/user_profile_edit.js @@ -47,13 +47,13 @@ 'use strict'; - var _avatar_upload = __webpack_require__(30); + var _avatar_upload = __webpack_require__(56); - var _bootstrap_tabs = __webpack_require__(17); + var _bootstrap_tabs = __webpack_require__(42); - var _user_check_statuses = __webpack_require__(31); + var _user_check_statuses = __webpack_require__(57); - var _custom_select = __webpack_require__(15); + var _custom_select = __webpack_require__(40); $(function () { (0, _avatar_upload.avatarUploadInit)(); @@ -64,7 +64,7 @@ /***/ }, -/***/ 15: +/***/ 40: /***/ function(module, exports) { 'use strict'; @@ -108,7 +108,7 @@ /***/ }, -/***/ 17: +/***/ 42: /***/ function(module, exports) { "use strict"; @@ -144,7 +144,7 @@ /***/ }, -/***/ 30: +/***/ 56: /***/ function(module, exports) { 'use strict'; @@ -197,7 +197,7 @@ /***/ }, -/***/ 31: +/***/ 57: /***/ function(module, exports) { 'use strict'; diff --git a/assets/js/build/worksell_filter.js b/assets/js/build/worksell_filter.js index 9c2e0fd..b2ec298 100644 --- a/assets/js/build/worksell_filter.js +++ b/assets/js/build/worksell_filter.js @@ -40,19 +40,20 @@ /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ -/******/ ([ -/* 0 */ +/******/ ({ + +/***/ 0: /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _custom_check = __webpack_require__(1); + var _custom_check = __webpack_require__(27); - var _extended_field = __webpack_require__(2); + var _extended_field = __webpack_require__(28); - var _ajax_set_filter = __webpack_require__(3); + var _ajax_set_filter = __webpack_require__(29); - var _filter_toggle = __webpack_require__(4); + var _filter_toggle = __webpack_require__(30); function paginateTo(pageNum) { var $form = $('#filter-form'); @@ -73,7 +74,8 @@ }); /***/ }, -/* 1 */ + +/***/ 27: /***/ function(module, exports) { "use strict"; @@ -102,7 +104,8 @@ exports.customCheckInit = customCheckInit; /***/ }, -/* 2 */ + +/***/ 28: /***/ function(module, exports) { 'use strict'; @@ -132,7 +135,8 @@ exports.extendedFieldInit = extendedFieldInit; /***/ }, -/* 3 */ + +/***/ 29: /***/ function(module, exports) { 'use strict'; @@ -195,7 +199,8 @@ exports.modUrl = modUrl; /***/ }, -/* 4 */ + +/***/ 30: /***/ function(module, exports) { 'use strict'; @@ -225,4 +230,5 @@ exports.filterToggleInit = filterToggleInit; /***/ } -/******/ ]); \ No newline at end of file + +/******/ }); \ No newline at end of file diff --git a/assets/js/src/chat/BINDS.js b/assets/js/src/chat/BINDS.js new file mode 100644 index 0000000..025478d --- /dev/null +++ b/assets/js/src/chat/BINDS.js @@ -0,0 +1,445 @@ +import {getCookie} from '../utils' +import {onClickCardWithCount} from './messageCounters' +import {loadTemplate} from './loaders' + +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'); + }); +} + +function bindOrders() { + $('.order-block').on('click', function (event) { + event.preventDefault(); + let $this = $(this); + onClickCardWithCount($this); + $('.order-block').each(function (i, v) { + $(v).removeClass('orAct'); + }); + $this.addClass('orAct'); + let orderId = $this.data('id'); + let projectId = $this.data('project-id'); + let recipentId = $this.data('recipent-id'); + let orderName = $this.data('order-name'); + var secureOrder = $(this).data('secure-deal'); + secureOrder = Boolean(secureOrder); + window.location.hash = `order${orderId}`; + + $("#chat-order-add #orderId").val(orderId); + $("#add-form-order-note #orderNote").val(orderId); + $("#orderArbitrationId").val(orderId); + $("#projectReviewId").val(projectId); + $("#reserve-button").attr('data-order-id', orderId); + + $("#chat-order-add #recipentId").val(recipentId); + window.chatController.create(orderId, projectId, recipentId, orderName, secureOrder); + }); + $('.order-block .dimovChat').on('click', function (event) { + event.preventDefault(); + event.stopPropagation(); + // console.log('click on tr'); + }); +} + +function bindTeams() { + $('.team-block').on('click', function () { + onClickCardWithCount($(this)); + $('.team-order-block, .team-block').each(function () { + $(this).removeClass('orAct'); + }); + $(this).addClass('orAct'); + + var teamIds = ''; + $.each($(this).find('.team-chat-user'), function (i, v) { + teamIds += $(this).attr('data-id') + ";"; + }); + $("#team-chat-form #teamIds").val(teamIds); + + var inbox = document.getElementById('message-chat-team-space'); + inbox.innerHTML = ''; + + var docList = document.getElementById('documentTeamSpace'); + docList.innerHTML = ''; + + var teamId = $(this).attr('data-team-id'); + location.hash = '#myteam' + teamId; + + // var newCount = parseInt($("#count-tab-team").text()); + // var currNewCount = parseInt($(".team-count-" + teamId).text()); + // var resCount = newCount - currNewCount; + // $("#count-tab-team").text(resCount); + $(".team-count-" + teamId).text(0) + + $("#team-chat-form #teamId").val(teamId); + $("#add-form-team-note #teamNote").val(teamId); + $("#team-chat-form #recipentTeamId").val(""); + $("#team-chat-form #orderTeamId").val(""); + $("#add-form-team-note #orderNote").val(""); + + $.ajax({ + url: '/api/message', + type: 'GET', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: {'team': teamId, 'order__isnull': 'true'}, + dataType: 'json', + success: function (json) { + $.each(json.results, function (i, v) { + var senderName = 'Вы'; + var className = 'youChat'; + if (v.sender.id !== userId) { + 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', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: { + 'team': teamId, + 'is_delete': false, + 'is_send': true, + }, + dataType: 'json', + success: function (json) { + $.each(json.results, function (i, v) { + docList.innerHTML += '
  • ' + v.file + '
  • '; + }); + }, + error: function (e) { + console.log(e); + } + }); + + $.ajax({ + url: '/api/note/', + type: 'GET', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: {'team': teamId}, + dataType: 'json', + success: function (json) { + // console.log(json.results); + var noteHtmlInbox = ''; + var note_tmpl = loadTemplate('note_tmpl'); + $.each(json.results, function (i, v) { + noteHtmlInbox += note_tmpl({text: v.text}); + + }); + $(".team-notes-block").html(noteHtmlInbox); + } + }); + + }); +} + +function bindArbitrationSend() { + // TODO: Test it + $('#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); + } + }); + }); +} + +function bindOnTabs() { + /** + * Биндит обработчики на Закладки + */ + $('a[data-toggle="tab"]').unbind().on('show.bs.tab', function (e) { + // console.log("TAB!"); + var activeTab = $(this).attr('href').substring(1); + var liveHash = URI(location.href).hash(); + + switch (activeTab) { + case 'tab1': + setTimeout(function () { + if (liveHash.indexOf("#user") != -1) { + var userHashId = liveHash.replace("#user", ""); + $("#userBlock" + userHashId).trigger('click'); + } else { + $(".user-block").first().trigger('click'); + } + }, 100); + break; + + case 'tab2': + // console.log("tab2"); + setTimeout(function () { + if (liveHash.indexOf("#order") != -1) { + var ordHashId = liveHash.replace("#order", ""); + $("#orderBlock" + ordHashId).trigger('click'); + } else { + $(".order-block").first().trigger('click'); + } + }, 100); + break; + + case 'tab3': + setTimeout(function () { + // console.log("on active TAB team"); + if (liveHash.indexOf("#teamorder") != -1) { + var teamHashId = liveHash.replace("#teamorder", ""); + $("#teamOrderBlock" + teamHashId).trigger('click'); + } else if (liveHash.indexOf("#myteam") != -1) { + 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); + + } + + }); +} + +function bindUserContacts() { + $(".conMess").click('on', function (e) { + e.preventDefault(); + e.stopPropagation(); + + var userId = $(this).attr('data-id'); + $.ajax({ + url: '/api/users/' + userId + '/', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('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); + } + }); + }); +} + +function bindGetUserMessages() { + $('.user-block').on('click', function () { + onClickCardWithCount($(this)); + // var newCount = parseInt($("#count-tab-contact").text()); + 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); + // var currNewCount = parseInt($(".contact-count-" + sumSenderRecipent).text()); + // var resCount = newCount - currNewCount; + // $("#count-tab-contact").text(resCount); + $(".contact-count-" + sumSenderRecipent).text(0); + var docList = document.getElementById('documentSpace'); + inbox.innerHTML = ''; + docList.innerHTML = ''; + + $.ajax({ + url: '/api/message', + type: 'GET', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: { + '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', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: { + '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', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: { + 'operand': 'in', + 'sender_id': userId, + 'recipent_id': contactId + }, + dataType: 'json', + success: function (json) { + // console.log(json.results); + var noteHtmlInbox = ''; + var note_tmpl = loadTemplate('note_tmpl'); + $.each(json.results, function (i, v) { + noteHtmlInbox += note_tmpl({text: v.text}); + }); + $(".contractor-notes-block").html(noteHtmlInbox); + } + }); + + }); +} + +function bindDeleteContact() { + $('.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 () { + }); + + + }); +} + +export { + bindOrders, + bindArbitrationSend, + bindOnTabs, + bindUserContacts, + bindGetUserMessages, + bindTeams, + bindDeleteContact, +} \ No newline at end of file diff --git a/assets/js/src/chat/ChatContractorPageController.js b/assets/js/src/chat/ChatContractorPageController.js new file mode 100644 index 0000000..6e18d8c --- /dev/null +++ b/assets/js/src/chat/ChatContractorPageController.js @@ -0,0 +1 @@ +import {StagesController} from './StagesContractorController' import {MessagesController} from './MessagesControllers' import {DocumentsController} from './DocumentsControllers' class ChatPageController { constructor() { let self = this; console.log("NEW CONTRACTOR ChatPageController"); this.statesController = undefined; this.messagesController = undefined; this.documentsController = undefined; // TODO: не забыть! // $('.order-block').on('click', function (event) { // console.log("CLICK!!!"); // event.preventDefault(); // let $this = $(this); // $('.order-block').each(function (i, v) { // $(v).removeClass('orAct'); // }); // $this.addClass('orAct'); // let orderId = $this.data('id'); // let projectId = $this.data('project-id'); // let recipentId = $this.data('recipent-id'); // let orderName = $this.data('order-name'); // // console.log('orderId = ', orderId); // new StagesController(orderId, projectId, recipentId, orderName); // new MessagesController(orderId); // window.location.hash = `order${orderId}`; // // $("#chat-order-add #orderId").val(orderId); // $("#add-form-order-note #orderNote").val(orderId); // $("#orderArbitrationId").val(orderId); // $("#projectReviewId").val(projectId); // // console.log("recipentId = ", recipentId); // $("#chat-order-add #recipentId").val(recipentId); // $("#targetCustomerId").val(recipentId); // $("#add-form-order-note #recipentNote").val(recipentId); // // }); // $('.order-block .dimovChat').on('click', function (event) { // event.preventDefault(); // event.stopPropagation(); // // TODO: доделать сворачивание/разворачивание блока // // console.log('click on tr'); // }); } create(orderId, projectId, recipentId, orderName, secureOrder) { this.statesController = new StagesController(orderId, projectId, recipentId, orderName, secureOrder); this.messagesController = new MessagesController(orderId); this.documentsController = new DocumentsController(orderId); } // refresh() } export {ChatPageController} \ No newline at end of file diff --git a/assets/js/src/chat/ChatCustomerPageController.js b/assets/js/src/chat/ChatCustomerPageController.js new file mode 100644 index 0000000..679d9c3 --- /dev/null +++ b/assets/js/src/chat/ChatCustomerPageController.js @@ -0,0 +1 @@ +import {StagesController} from './StagesCustomerController' import {MessagesController} from './MessagesControllers' import {recalculateMessages} from './messageCounters' class ChatPageController { constructor() { let self = this; // console.log("NEW Chat CUSTOMER PageController"); this.statesController = undefined; this.messagesController = undefined; // TODO: не забыть! // recalculateMessages(); } create(orderId, projectId, recipentId, orderName, secureOrder) { this.statesController = new StagesController(orderId, projectId, recipentId, orderName, secureOrder); this.messagesController = new MessagesController(orderId); } } export {ChatPageController} \ No newline at end of file diff --git a/assets/js/src/chat/DocumentsControllers.js b/assets/js/src/chat/DocumentsControllers.js new file mode 100644 index 0000000..c5b8e87 --- /dev/null +++ b/assets/js/src/chat/DocumentsControllers.js @@ -0,0 +1,67 @@ +import {getCookie} from '../utils' +import {loadTemplate} from './loaders' + +class DocumentsController { + constructor(orderId) { + console.log('Create MessagesController'); + const self = this; + this.orderId = orderId; + this.$container = $('#documentOrderSpace'); + this.$container.html(""); + + this.messageTemplate = loadTemplate('document_attach_file_tmpl'); + this.dataPromise = this.getMessagesData(); + this.dataPromise.then( + self._onLoadData.bind(self) + ) + } + + getMessagesData() { + const self = this; + return Promise.resolve( + $.ajax({ + url: '/api/documents', + type: 'GET', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: { + 'order': self.orderId, + 'is_delete': false, + 'is_send': true, + }, + dataType: 'json', + // success: function (json) { + // + // }, + error: function (e) { + console.log(e); + } + })); + } + + addDocument(json) { + + } + + _onLoadData(json) { + const self = this; + // console.log('mesages json = ', json); + // console.log('$inbox = ', this.$inbox); + // console.log("messages render start"); + this.$container.html(""); + $.each(json.results, function (i, v) { + let document = $(self.messageTemplate( + { + href: `/chat/download/' + ${v.file}`, + text: v.file, + document_id: v.id + })); + self.$container.append(document); + }); + // console.log("messages render complete"); + // self.$inbox.scrollTop(self.$inbox.prop("scrollHeight")); + } +} + +export {DocumentsController} \ No newline at end of file diff --git a/assets/js/src/chat/MessagesControllers.js b/assets/js/src/chat/MessagesControllers.js new file mode 100644 index 0000000..8bb1d10 --- /dev/null +++ b/assets/js/src/chat/MessagesControllers.js @@ -0,0 +1,61 @@ +import {getCookie} from '../utils' +import {loadTemplate} from './loaders' + +class MessagesController { + constructor(orderId) { + console.log('Create MessagesController'); + const self = this; + this.orderId = orderId; + this.$inbox = $('#message-chat-order-space'); + this.$inbox.html(""); + this.messageTemplate = loadTemplate('message_tmpl'); + this.dataPromise = this.getMessagesData(); + this.dataPromise.then( + self._onLoadData.bind(self) + ) + } + + getMessagesData() { + const self = this; + return Promise.resolve($.ajax({ + url: '/api/message', + type: 'GET', + data: {'order': self.orderId, 'team__isnull': 'true'}, + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + dataType: 'json', + success: function (json) { + console.log('Success Messages') + } + })); + } + + _onLoadData(json) { + const self = this; + // console.log('mesages json = ', json); + // console.log('$inbox = ', this.$inbox); + // console.log("messages render start"); + self.$inbox.html(""); + $.each(json.results, function (i, v) { + var senderName = 'Вы'; + var className = 'youChat'; + + if (v.sender.id !== userId) { + senderName = v.sender.username; + className = ''; + } + if (v.is_system) { + senderName = 'Системное'; + className = 'systemChat' + } + let message = $(self.messageTemplate({className: className, senderName: senderName, message: v})); + self.$inbox.append(message); + + }); + // console.log("messages render complete"); + self.$inbox.scrollTop(self.$inbox.prop("scrollHeight")); + } +} + +export {MessagesController} \ No newline at end of file diff --git a/assets/js/src/chat/Stages.js b/assets/js/src/chat/Stages.js new file mode 100644 index 0000000..feb09f9 --- /dev/null +++ b/assets/js/src/chat/Stages.js @@ -0,0 +1,340 @@ +import {loadTemplate} from './loaders' +// new-stages-form +// update-stages-form +// remove-stages-form + +class StageForm { + constructor($container, {orderId, stage_num, stage_status, type = 'new', formNamePostfix = '-stages-form', template_name, data = {}}, + kwargs = { + stage_num: stage_num, + stage_status: stage_status, + form_name: (type + formNamePostfix), + orderId: orderId, + stage: data + },) + // kwargs - auto generate from name_attributes + { + // console.log('Stage form template_name = ', template_name); + this.orderId = orderId; + this._type = type; + this.$container = $container; + this.self_tmpl = loadTemplate(template_name); + this.data = data; + this.$form = undefined; + this.stageId = (type != 'new') ? data.id : undefined; + this.create(kwargs); + } + + create(kwargs) { + /** + * Добавление шаблона-формы Этапа на страницу + */ + let el = $(this.self_tmpl(kwargs)); + this.$container.append(el); + this.$form = el.find('form'); + // console.log("form --> ", this.$form); + if (this.$form.length) this.$form.find('input[name=cost]').mask('000000000'); + } + + remove() { + /** + * Удаление, при уменьшении кол-ва этапов + * return true - удаляем из [] stages + */ + if (this.type == 'new') { + this.$form.parent().remove(); + return true; + } + this.type = 'remove'; + // this.$form.removeClass('update-stages-form').addClass('remove-stages-form'); + return false + } + + restore() { + /** + * Восстановление, при увеличении кол-ва этапов + */ + if (this.type == 'new') throw new Error("Попытка восстановить элемент с type='new'"); + this.type = 'update'; + // this.$form.removeClass('remove-stages-form').addClass('update-stages-form'); + } + + set type(newType) { + this.$form.removeClass(`${this._type}-stages-form`).addClass(`${newType}-stages-form`); + if (newType == 'remove') this.hide(); + if (newType == 'update') this.show(); + this._type = newType + } + + get type() { + return this._type + } + + disable() { + this.$form.find('input').attr('readonly', true); + } + + enable() { + this.$form.find('input').attr('readonly', false); + } + + hide() { + this.$form.parent().hide(); + } + + show() { + this.$form.parent().show() + } + + is_valid() { + let self = this; + let mesage = 'Это поле обязательно'; + let valid = true; + //Очищаем старые ошибки + this.$form.find('.error').html(""); + // Отображаем новые + this.$form.find(":input:not([type=hidden])").each(function (i, v) { + if (!$(v).val()) { + self.$form.find(`.error-${$(v).attr("name")}`).html(mesage).css('color', 'red'); + valid = false + } + }); + return valid + } + + sendAjax_approve() { + /** + * Отправка Этапа "на согласование" + */ + let self = this; + // console.log("Send AJAX Approve"); + if (this.type == 'new') { + // console.log('new stages approve'); + return Promise.resolve($.ajax({ + // async: false, + url: '/api/stages/', + type: 'POST', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: this.$form.serialize(), + dataType: 'json', + }) + .done(function (json) { + self.type = 'update'; + self.disable(); + self.$form.find('.error').html(""); + // console.log("json -->", json); + self.stageId = json.id; + // console.log(json); + }) + .fail(function (xhr, errorMsg, error) { + console.log("ERROR, xhr", xhr); + $.each(xhr.responseJSON, function (i, v) { + self.$form.find('.error-' + i).html(v).css('color', 'red'); + // console.log(self.$form); + // console.log(v); + // console.log(i); + }); + })); + } else if (this.type == 'update') { + this.$form.find('input[name=status]').val('send_approve'); + return Promise.resolve($.ajax({ + url: `/api/stages/${this.stageId}/`, + type: 'PUT', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: this.$form.serialize(), + dataType: 'json', + }) + .done(function (json) { + self.$form.find('.error').html(""); + self.disable(); + }) + .fail(function (xhr, errorMsg, error) { + $.each(xhr.responseJSON, function (i, v) { + self.$form.find('.error-' + i).html(v).css('color', 'red'); + console.log(v); + console.log(i); + }); + })); + } else if (this.type == 'remove') { + return Promise.resolve($.ajax({ + url: `/api/stages/${this.stageId}/`, + type: 'DELETE', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + dataType: 'json', + }) + .done(function (json) { + }) + .fail(function (xhr, errorMsg, error) { + console.log("delete fail, json -->", xhr); + })); + } + } + + sendAjax_accept(secureOrder) { + /** + * "Согласовать" Этапы (Исполнителем) + */ + // console.log("secureOrder = ", secureOrder); + // console.log("set new status =", secureOrder ? 'agreed': 'in_process'); + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PATCH', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + //TODO: слать только изменения + data: { + status: secureOrder ? 'agreed': 'in_process', + }, + dataType: 'json', + })) + } + + sendAjax_change() { + /** + * Отправка Этапа "Внести изменения" + */ + let self = this; + // this.$form.find('input[name=status]').val('not_agreed'); + // console.log("ajax Change form -->", this.$form); + return Promise.resolve($.ajax({ + url: '/api/stages/' + this.stageId + '/', + type: 'PATCH', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + //TODO: слать только изменения + data: {status: 'not_agreed'}, + dataType: 'json', + }) + .done(function (json) { + // enableStageFields(json.id); + // $form.find('.error').html(""); + self.enable(); + }) + .fail(function (xhr) { + console.log("Ошибка, которой не должно быть json -->", xhr.responseJSON); + })); + } + +} + +class StageReserved { + constructor($container, {template_name = 'reserved_tmpl', data}, + kwargs = { + reserved_cls: '', + reserved_name: '', + stage: data + },) { + // Вывод текста резервирования в зависимости от статуса этапа + let reserved_names = { + agreed: 'Не зарезервирована', + in_process: 'Зарезервирована', + completed: 'Зарезервирована', + closed: 'Переведена исполнителю', + }; + // Вывод текста резервирования в зависимости от статуса этапа + let reserved_classes = { + agreed: 'unreserved', + in_process: 'reserved', + completed: 'reserved', + closed: 'closed', + }; + kwargs.reserved_cls = reserved_classes[data.status]; + kwargs.reserved_name = reserved_names[data.status]; + this.data = data; + this.self_tmpl = loadTemplate(template_name); + this.$container = $container; + this.create(kwargs); + } + + create(kwargs) { + /** + * Добавление шаблона "Резервирование" Этапа на страницу + */ + this.$self = $(this.self_tmpl(kwargs)); + this.$container.append(this.$self); + // console.log("form --> ", this.$form); + // this.$form.find('input[name=cost]').mask('000000000'); + } +} + +class StageInWork { + constructor($container, {template_name = 'work_in_process_tmpl', note_text = '', data}, + kwargs = {stage: data, note_text: note_text}) { + this.stageId = data.id; + this.data = data; + this.self_tmpl = loadTemplate(template_name); + this.$container = $container; + this.create(kwargs); + } + + create(kwargs) { + /** + * Добавление шаблона "Выполнение работы" Этапа на страницу + */ + this.$self = $(this.self_tmpl(kwargs)); + this.$container.append(this.$self); + } + + hide() { + this.$self.hide(); + } + + sendAjax_complete() { + /** + * Отправка Этапа "Закрыть этап" + */ + let self = this; + return Promise.resolve($.ajax({ + url: `/api/stages/${this.stageId}/`, + type: 'PATCH', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: {status: 'completed'}, + dataType: 'json', + }) + .done(function (json) { + // enableStageFields(json.id); + // $form.find('.error').html(""); + // self.enable(); + }) + .fail(function (xhr) { + console.log("Ошибка, которой не должно быть json -->", xhr.responseJSON); + })); + } + + sendAjax_close() { + /** + * Отправка Этапа "Закрыть этап" + */ + let self = this; + return Promise.resolve($.ajax({ + url: `/api/stages/${this.stageId}/`, + type: 'PATCH', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + //TODO: слать только изменения + data: {status: 'closed'}, + dataType: 'json', + }) + .done(function (json) { + // enableStageFields(json.id); + // $form.find('.error').html(""); + // self.enable(); + }) + .fail(function (xhr) { + console.log("Ошибка, которой не должно быть json -->", xhr.responseJSON); + })); + } +} + +export {StageForm, StageReserved, StageInWork} \ No newline at end of file diff --git a/assets/js/src/chat/StagesContractorController.js b/assets/js/src/chat/StagesContractorController.js new file mode 100644 index 0000000..bb947d8 --- /dev/null +++ b/assets/js/src/chat/StagesContractorController.js @@ -0,0 +1,446 @@ +import {getCookie} from '../utils' +import {loadTemplate} from './loaders' +import {StageForm, StageReserved, StageInWork} from './Stages' + +let message_format = { + "format_type": "approve_stages", + "data": { + "sender_id": "", + "recipent_id": "", + "order_id": "", + "msg": "", + "is_system": true + } +}; + +const STATUSES = { + 'not_agreed': 'не согласован', + 'send_approve': 'на согласовании', + 'agreed': 'согласовано', + 'cancel_approve': 'исполнитель отказался', + 'in_process': 'в процессе', + 'completed': 'завершен', + 'closed': 'закрыт', + +}; + +//Contractor +class StagesController { + constructor(orderId, projectId, recipentId, orderName, secureOrder) { + const self = this; + this.orderId = orderId; + this.projectId = projectId; + this.recipentId = recipentId; + this.orderName = orderName; + this.secureOrder = secureOrder; + // console.log("ids -->", orderId, projectId, recipentId); + this.data = {}; //JSON + this.stages = []; + this.stages_reserved = []; + this.stages_work = []; + this.STAGE_STATUSES = { + 'not_agreed': this.buildStartStage.bind(self), + 'send_approve': this.buildSendApproveStage.bind(self), + 'agreed': this.buildAgreedStage.bind(self), + 'in_process': this.buildProcessStage.bind(self), + 'completed': this.buildProcessStage.bind(self), + 'closed': this.buildProcessStage.bind(self), + }; + this.btnCompleteTmpl = loadTemplate('bntCompleteStage_tmpl'); + this.btnSendReviewTmpl = loadTemplate('btnSendReview_tmpl'); + this.$orderStagesContainer = $('#order-stages'); + this.$orderStagesContainer.html(''); + this.buttons = { + btnApprove: $('#btnApprove'), // "Согласовать" + btnChange: $('#btnChange'), // "Отправить на внесение изменений" + btnsToArchive: $('.js-btnToArchive'), // "Отказаться от заказа" + btnsArbitration: $('.js-btnArbitration'),// "Обратиться в арбитраж" + btnSendReview: $('#order-review-add') // "Оставить отзыв" + }; + this.stages_elements = { + $approve: $('#conditions-approve'), //1. Согласование условия + $reserve: $('#reserveSpace'), //2. Резервирование (Отобразить) + $works: $('#completeWork') //3. Выполненная работа + }; + this.init(); + } + + init() { + const self = this; + + this.dataPromise = this.getOrderData({orderId: this.orderId}); + this.dataPromise + .then( + self._onLoadData.bind(self) + ) + .catch( + self._onLoadDataError.bind(self) + ); + } + + getOrderData({orderId}) { + const self = this; + return Promise.resolve($.ajax({ + url: `/api/orders/${orderId}/`, + dataType: 'json', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + })) + } + + redraw() { + /** + * Полностью перерисовываем страницу Заказа + */ + console.log("Redraw contractor stages"); + // $("#orderBlock" + this.orderId).trigger('click'); + this.init(); + } + + + buildStartStage() { + /** + * Стадия: "Проект Предложен"(нет этапов) + */ + // Выделить цифру 1. красным + // $('#conditions-approve').find('.select') + this.stages_elements.$approve.show(); + this.stages_elements.$reserve.show(); + this.stages_elements.$works.show(); + this.$orderStagesContainer.parent().hide(); + this.buttons.btnsToArchive.first().hide(); + this.$orderStagesContainer.show(); + this.buttons.btnApprove.hide(); + this.buttons.btnChange.hide(); + this.buttons.btnsArbitration.hide(); + this.stages_elements.$approve.find('.js-help-text').show(); + this.stages_elements.$reserve.find('.stages-paid').html(""); + this.stages_elements.$works.find('.js-help-text').show(); + this.stages_elements.$works.find('#stagesWork').html(""); + if (this.secureOrder){ + this.stages_elements.$reserve.find('.js-help-text').show(); + } else { + this.stages_elements.$reserve.find('.js-help-text').hide(); + // this.stages_elements.$reserve.find('.js-help-text').html('Резервирование не предусмотрено, безопасная сделака не активна'); + } + + } // Нет Этапов / "Не согласован" + + // buildNotAgreedStage() { + // console.log("Stage: not_agreed"); + // // this._renderStage('stage_tmpl'); + // this.buttons.btnApprove.hide(); + // this.buttons.btnChange.hide(); + // this.buttons.btnToArchive.hide(); + // this.buttons.btnArbitration.hide(); + // } // Статус "Не согласован" + + buildSendApproveStage() { + console.log("Stage: send_approve"); + this._renderStage('stage_approved_tmpl', true); + this.$orderStagesContainer.parent().show(); + this.buttons.btnApprove.show(); + this.buttons.btnChange.show(); + this.buttons.btnsToArchive.first().show(); + this.stages_elements.$reserve.hide(); + this.stages_elements.$works.hide(); + } // Статус "На согласовании" + + buildAgreedStage() { + console.log('Stage: agreed'); + this.$orderStagesContainer.parent().show(); + this.buttons.btnApprove.hide(); + this.buttons.btnChange.hide(); + this.buttons.btnsToArchive.hide(); + this.buttons.btnsArbitration.first().hide(); + this.buttons.btnsArbitration.last().show(); + this._renderStage('stage_approved_tmpl', true); + this.stages_elements.$approve.find('.js-help-text').hide(); + this.stages_elements.$reserve.show(); + if (this.secureOrder){ + this._renderStageReserved('reserved_tmpl'); + this.stages_elements.$reserve.find('.js-help-text').show(); + }else{ + this.stages_elements.$reserve.find('.stages-paid').html(""); + this.stages_elements.$reserve.find('.js-help-text').hide(); + } + } // Статус "Согласован" + + buildProcessStage() { + console.log('Stage: in_process'); + this.buildAgreedStage(); + this.stages_elements.$reserve.find('.js-help-text').hide(); + this.stages_elements.$works.show(); + if (this.secureOrder) { + this._renderStageInWork('work_in_process_tmpl'); + } else { + this.stages_elements.$reserve.find('.stages-paid').html(""); + } + } // Статус "В процессе"/"Завершен"/"Закрыт" + + _buildPage() { + // console.log("Build PAge"); + this.stages_elements.$reserve.hide(); + this.stages_elements.$works.hide(); + if (this.data.stages.length == 0) { + this.buildStartStage() + } else { + let stageStatus = this.data.stages[0].status; + // console.log('stageStatus = ', stageStatus); + this.STAGE_STATUSES[stageStatus](); + } + this._bindEvents(); + } + + _renderStage(template_name, disable = false) { + let i = 0; + // console.log("this.data.stages = ", this.data.stages); + this.$orderStagesContainer.html(""); + for (let stage_data of this.data.stages) { + i++; + // console.log('stage_data = ', stage_data); + let stage = new StageForm(this.$orderStagesContainer, + { + orderId: this.orderId, stage_num: i, stage_status: STATUSES[stage_data.status], + type: 'update', template_name: template_name, data: stage_data + }); + if (disable) stage.disable(); + this.stages.push(stage); + + } + } + + _renderStageReserved(template_name) { + /** + * Отрисовываем блок "Резервирование" + */ + // console.log("_renderStageReserved"); + let $container = this.stages_elements.$reserve.find('.stages-paid'); + $container.html(""); + this.stages_reserved = []; + // console.log("this.data.stages = ", this.data.stages); + // Нет незарезервированных Этапов + // let has_not_reserved_stages = false; + for (let stage_data of this.data.stages) { + // if (stage_data.status == 'agreed') has_not_reserved_stages = true; + let stage = new StageReserved($container, + { + template_name, data: stage_data + }); + this.stages_reserved.push(stage); + } + // if (!has_not_reserved_stages) { + // this.buttons.btnReserve.hide(); + // this.stages_elements.$reserve.find('.js-help-text').hide(); + // } + } + + _renderStageInWork(template_name) { + /** + * Отрисовываем блок "Выволнение работы", включая "Выполненныа работа" и "Оставить отзыв" + */ + let $container = this.stages_elements.$works.find('#stagesWork'); + $container.html(""); + let all_closed = this.data.stages.every((el)=>el.status == 'closed'); + if (all_closed) { + this.stages_elements.$works.find('.titleStepss').html('3. Выполненная работа'); + this.stages_elements.$works.find('.js-btnArbitration').hide(); + this.stages_elements.$works.find('.js-help-text').hide(); + for (let stage_data of this.data.stages) { + let stage = new StageInWork($container, + { + template_name, data: stage_data + }); + this.stages_work.push(stage); + } + // console.log("has_user_review = ", this.data.has_user_review); + if (!this.data.has_user_review) { + let btnReviewOpenModel = $(this.btnSendReviewTmpl()); + btnReviewOpenModel.unbind().on('click', this._onBtnReviewOpenModal.bind(this)); + // Если кнопка "Оставить отзыв" еще не добавлена - добавляем + if (!this.stages_elements.$works.find('#send-review').length) this.stages_elements.$works.append(btnReviewOpenModel); + } else { + if (this.stages_elements.$works.find('#send-review').length) this.stages_elements.$works.find('#send-review').remove() + } + + } else { + for (let stage_data of this.data.stages) { + if (stage_data.status == 'closed' || stage_data.status == 'agreed') continue; + let note_text = (stage_data.status == 'completed') ? '...НА УТВЕРЖДЕНИИ У ЗАКАЗЧИКА' : ''; + let stage = new StageInWork($container, + { + template_name, data: stage_data, note_text: note_text + }); + if (stage_data.status == 'in_process') { + let $btn = $(this.btnCompleteTmpl({stage: stage_data, text: 'Завершить этап'})); + $container.html(); + $container.append($btn); + $btn.on('click', this._onBtnComplete.bind(this, stage)) + } + this.stages_work.push(stage); + } + } + + } + + _onLoadData(json) { + this.data = json; + this._buildPage(); + } + + _bindEvents() { + const self = this; + this.buttons.btnApprove.unbind().on("click", this._onBtnAccept.bind(self)); + this.buttons.btnChange.unbind().on("click", this._onBtnChange.bind(self)); + this.buttons.btnsToArchive.unbind().on("click", this._onBtnAToArchive.bind(self)); + this.buttons.btnsArbitration.unbind().on("click", this._onBtnArbitration.bind(self)); + this.buttons.btnSendReview.unbind().on("click", this._onBtnSendReview.bind(self)); + $("#reserve-stage-modal").find('#stage-num').unbind().on('change', function (event) { + // console.log("select stage cost = ", self.stages[this.value - 1].data.cost); + $("#reserve-stage-modal").find('#stage-cost').html(self.stages[this.value - 1].data.cost); + }); + } + + // BINDS + + _onBtnAccept(event) { + event.preventDefault(); + const self = this; + Promise.all(this.stages.map((el)=>el.sendAjax_accept(self.secureOrder))).then(()=> { + console.log('Этапы согласованы'); + self.redraw(); + + let message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = `Условия заказа ${self.orderName} приняты`; + console.log("Send-WS Условия приняты"); + socket.send_stages_approve(message); + //TODO: раскомментировать дурацкое окно + // $('#popupOk').modal('show'); + // }) + }); + } // "Согласовать" + + _onBtnChange(event) { + event.preventDefault(); + const self = this; + Promise.all(this.stages.map((el)=>el.sendAjax_change())).then(()=> { + self.redraw(); + let message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = `Заказ ${self.orderName} отправлен для внесения изменений`; + console.log("Send-WS Внести изменения"); + socket.send_stages_approve(message); + }); + + } // "Отправить на внесение изменений" + + // TODO: test it + _onBtnAToArchive(event) { + event.preventDefault(); + console.error("Отказаться от заказа. Не протестировано!!"); + // TODO: Не только удалять заказ, но и делать его копию со статусом "Открыто" + $.ajax({ + // async: false, + url: `/api/orders/${this.orderId}/`, + type: 'DELETE', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + dataType: 'json', + }) + .done(function (json) { + console.log('delete complete'); + window.location.href = window.location.href.replace(getHash(), ""); + }) + .fail(function (xhr, errorMsg, error) { + console.log("delete fail, json -->", xhr); + }); + + } // "Отказаться от заказа" + + _onBtnComplete(stage, event) { + event.preventDefault(); + const self = this; + // let stageId = $(event.target).data('stage-id'); + // console.log('Complete stage id = ', stage.data.id); + stage.sendAjax_complete() + .then(function (json) { + self.redraw(); + let message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = `Этап ${json.name} закрыт`; + console.log("Send-WS Закрытие этапа"); + socket.send_stages_approve(message); + }) + .catch(function (xhr) { + console.log("При закрытии этапа произошла ошибка -->", xhr); + }) + + } // "Закрыть этап" + + _onBtnReviewOpenModal(event) { + event.preventDefault(); + $('#review-add').modal('show'); + } // Открыть модальное окно "Оставить отзыв" + + _onBtnSendReview(event) { + event.preventDefault(); + const self = this; + $('#projectReviewId').val(this.projectId); + $('#targetCustomerId').val(this.recipentId); + // $('#fromContractorId').val('....current user'); + var formData = $("#review-adds-form").serialize(); + // console.log('Оставить отзыв formdata -->', formData); + $.ajax({ + url: '/api/reviews/', + type: 'POST', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: formData, + dataType: 'json', + success: function (json) { + // console.log('Отзыв успешно отправлен, json -->', json); + // $('#review-add').modal('hide'); + // self.stages_elements.$works.find('.js-btnSendReview').hide(); + $('#review-add').modal('hide'); + self.redraw(); + + let message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = `Отзыв на заказ ${self.orderName} оставлен`; + console.log("Send-WS Оставить отзыв"); + socket.send_stages_approve(message); + // $("a[href='#tab2']").trigger('click'); + window.location = '/chat/#order'; + location.reload(); + }, + error: function (e) { + console.log('error'); + console.log(e); + } + }); + } // "Оставить отзыв" + + + _onBtnArbitration(event) { + event.preventDefault(); + $("#arbitration-add").modal('show'); + } // "Обратиться в арбитраж" + + _onLoadDataError(error) { + console.log("Error loading data -->", error); + } +} + +export {StagesController} \ No newline at end of file diff --git a/assets/js/src/chat/StagesCustomerController.js b/assets/js/src/chat/StagesCustomerController.js new file mode 100644 index 0000000..5541d05 --- /dev/null +++ b/assets/js/src/chat/StagesCustomerController.js @@ -0,0 +1,545 @@ +import {getCookie} from '../utils' +import {loadTemplate} from './loaders' +import {StageForm, StageReserved, StageInWork} from './Stages' + +let message_format = { + "format_type": "approve_stages", + "data": { + "sender_id": "", + "recipent_id": "", + "order_id": "", + "msg": "", + "is_system": true + } +}; + +const STATUSES = { + 'not_agreed': 'не согласован', + 'send_approve': 'на согласовании', + 'agreed': 'согласовано', + 'cancel_approve': 'исполнитель отказался', + 'in_process': 'в процессе', + 'completed': 'завершен', + 'closed': 'закрыт', + +}; + + +class StagesController { + constructor(orderId, projectId, recipentId, orderName, secureOrder) { + const self = this; + this.orderId = orderId; + this.orderName = orderName; + this.projectId = projectId; + this.recipentId = recipentId; + this.secureOrder = secureOrder; + this.data = {}; //JSON + this.stages = []; + this.stages_reserved = []; + this.stages_work = []; + this.STAGE_STATUSES = { + 'not_agreed': this.buildNotAgreedStage.bind(self), + 'send_approve': this.buildSendApproveStage.bind(self), + 'agreed': this.buildAgreedStage.bind(self), + 'in_process': this.buildProcessStage.bind(self), + 'completed': this.buildProcessStage.bind(self), + 'closed': this.buildProcessStage.bind(self), + }; + this.btnCompleteTmpl = loadTemplate('bntCompleteStage_tmpl'); + this.btnSendReviewTmpl = loadTemplate('btnSendReview_tmpl'); + this.$orderStagesContainer = $('#order-stages'); + this.$orderStagesContainer.html(''); + this.$stagesCount = $('#countStage'); + this.$stagesCount.unbind().on("change", this._changeNumStages.bind(self)); + this.$stagesCount.parent().show(); + this.buttons = { + btnApprove: $('#btnApprove'), + btnChange: $('#btnChange'), + btnToArchive: $('#btnToArchive'), + btnReserve: $('#btnReserve'), + btnsArbitration: $('.js-btnArbitration'), + btnSendReview: $('#order-review-add') + }; + this.stages_elements = { + $approve: $('#conditions-approve'), //1. Согласование условия + $reserve: $('#reserveSpace'), //2. Резервирование + $works: $('#completeWork') //3. Выполненная работа + }; + this.init(); + } + + init() { + const self = this; + + this.dataPromise = this.getOrderData({orderId: this.orderId}); + this.dataPromise + .then( + self._onLoadData.bind(self) + ) + .catch( + self._onLoadDataError.bind(self) + ); + } + + getOrderData({orderId}) { + const self = this; + return Promise.resolve($.ajax({ + url: `/api/orders/${orderId}/`, + dataType: 'json', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + })) + } + + redraw() { + /** + * Полностью перерисовываем страницу Заказа + */ + console.log("Redraw customer stages"); + // $("#orderBlock" + this.orderId).trigger('click'); + this.init(); + } + + buildStartStage() { + /** + * Стадия: "Проект Предложен"(нет этапов) + */ + // Выделить цифру 1. красным + // $('#conditions-approve').find('.select') + this.$orderStagesContainer.show(); + this.buttons.btnApprove.show(); + this.buttons.btnChange.hide(); + this.buttons.btnToArchive.hide(); + this.$stagesCount.removeAttr('disabled'); + this.$stagesCount.val(1); + this.$stagesCount.trigger('change'); + // this.stages_elements.$approve.find('.js-help-text').show(); + // this.stages_elements.$reserve.find('.js-help-text').show(); + // this.stages_elements.$reserve.find('.stages-paid').hide(); + // this.stages_elements.$works.find('.js-help-text').show(); + // this.stages_elements.$works.find('#stagesWork').show(); + + } // Нет Этапов + + buildNotAgreedStage() { + console.log("Stage: not_agreed"); + this._renderStage('stage_tmpl'); + this.buttons.btnApprove.show(); + this.buttons.btnChange.hide(); + this.buttons.btnToArchive.hide(); + } // Статус "Не согласован" + + buildSendApproveStage() { + console.log("Stage: send_approve"); + this._renderStage('stage_tmpl', true); + this.$stagesCount.attr('disabled', true); + this.stages_elements.$reserve.hide(); + this.stages_elements.$works.hide(); + this.buttons.btnApprove.hide(); + this.buttons.btnChange.show(); + this.buttons.btnToArchive.show(); + } // Статус "На согласовании" + + buildAgreedStage() { + console.log('Stage: agreed'); + this.buttons.btnApprove.hide(); + this.buttons.btnChange.hide(); + this.buttons.btnToArchive.hide(); + this.$stagesCount.parent().hide(); + this._renderStage('stage_approved_tmpl', true); + this.stages_elements.$approve.find('.js-help-text').hide(); + this.stages_elements.$reserve.find('.js-help-text').show(); + this.stages_elements.$reserve.show(); + this.buttons.btnReserve.show(); + this.buttons.btnsArbitration.show(); + this._renderStageReserved('reserved_tmpl') + + } // Статус "Согласован" + + buildProcessStage() { + console.log('Stage: in_process'); + this.buildAgreedStage(); + this.stages_elements.$reserve.find('.js-btnArbitration').hide(); + this.stages_elements.$works.show(); + this._renderStageInWork('work_in_process_tmpl'); + } // Статус "В процессе"/"Завершен"/"Закрыт" + + _buildPage() { + // console.log("Build PAge"); + this.stages_elements.$reserve.hide(); + this.stages_elements.$works.hide(); + if (this.data.stages.length == 0) { + this.buildStartStage() + } else { + let stageStatus = this.data.stages[0].status; + // console.log('stageStatus = ', stageStatus); + this.STAGE_STATUSES[stageStatus](); + } + this._bindEvents(); + } + + _renderStage(template_name, disable = false) { + let i = 0; + this.$orderStagesContainer.html(""); + for (let stage_data of this.data.stages) { + i++; + let stage = new StageForm(this.$orderStagesContainer, + { + orderId: this.orderId, stage_num: i, stage_status: STATUSES[stage_data.status], + type: 'update', template_name: template_name, data: stage_data + }); + if (disable) stage.disable(); + this.stages.push(stage); + + } + this.$stagesCount.val(i); + } + + _renderStageReserved(template_name) { + let $container = this.stages_elements.$reserve.find('.stages-paid'); + $container.html(""); + this.stages_reserved = []; + // Нет незарезервированных Этапов + let has_not_reserved_stages = false; + for (let stage_data of this.data.stages) { + if (stage_data.status == 'agreed') has_not_reserved_stages = true; + let stage = new StageReserved($container, + { + template_name, data: stage_data + }); + this.stages_reserved.push(stage); + } + if (!has_not_reserved_stages) { + this.buttons.btnReserve.hide(); + this.stages_elements.$reserve.find('.js-help-text').hide(); + } + } + + _renderStageInWork(template_name) { + /** + * Отрисовываем блок "Выволнение работы", включая "Выполненныа работа" и "Оставить отзыв" + */ + let $container = this.stages_elements.$works.find('#stagesWork'); + $container.html(""); + let all_closed = this.data.stages.every((el)=>el.status == 'closed'); + if (all_closed) { + this.stages_elements.$works.find('.titleStepss').html('3. Выполненная работа'); + this.stages_elements.$works.find('.js-btnArbitration').hide(); + this.stages_elements.$works.find('.js-help-text').hide(); + for (let stage_data of this.data.stages) { + let stage = new StageInWork($container, + { + template_name, + data: stage_data, + note_text: 'Закройте этап или подробно опишите замечания в чате' + }); + this.stages_work.push(stage); + } + if (!this.data.has_user_review) { + let btnReviewOpenModel = $(this.btnSendReviewTmpl()); + btnReviewOpenModel.unbind().on('click', this._onBtnReviewOpenModal.bind(this)); + // Если кнопка "Оставить отзыв" еще не добавлена - добавляем + if (!this.stages_elements.$works.find('#send-review').length) this.stages_elements.$works.append(btnReviewOpenModel); + } else { + if (this.stages_elements.$works.find('#send-review').length) this.stages_elements.$works.find('#send-review').remove() + } + + } else { + for (let stage_data of this.data.stages) { + if (stage_data.status == 'closed') continue; + let stage = new StageInWork($container, + { + template_name, data: stage_data + }); + if (stage_data.status == 'completed') { + let $btn = $(this.btnCompleteTmpl({stage: stage_data, text: 'Закрыть этап'})); + $container.html(); + $container.append($btn); + $btn.on('click', this._onBtnClose.bind(this, stage)) + } + this.stages_work.push(stage); + } + } + + } + + _onLoadData(json) { + this.data = json; + this._buildPage(); + } + + _changeNumStages(event) { + /** + * Изменяет кол-во этапов(stages) + */ + let newNumStages = parseInt($(event.target).val()); + if (newNumStages < 1 || isNaN(newNumStages)) { + newNumStages = 1; + this.$stagesCount.val(newNumStages) + } + let currentNumStages = $('.js-stage-form:not(.remove-stages-form)').length; + if (currentNumStages == newNumStages) return; + if (currentNumStages > newNumStages) { + for (let stage of this.stages.slice().reverse()) { + if (stage.remove()) { + let index = this.stages.indexOf(stage); + if (index >= 0) { + this.stages.splice(index, 1); + } + } + currentNumStages--; + if (currentNumStages == newNumStages) break; + } + } else { + for (let stage of this.stages.slice()) { + if (stage.type == 'remove') { + stage.restore(); + } else continue; + currentNumStages++; + if (currentNumStages == newNumStages) break; + } + while (currentNumStages < newNumStages) { + currentNumStages++; + let stage = new StageForm(this.$orderStagesContainer, + {orderId: this.orderId, stage_num: currentNumStages, type: 'new', template_name: 'stage_tmpl'}); + this.stages.push(stage); + } + } + } //При изменении кол-ва этапов + + _bindEvents() { + const self = this; + this.buttons.btnApprove.unbind().on("click", this._onBtnApprove.bind(self)); + this.buttons.btnChange.unbind().on("click", this._onBtnChange.bind(self)); + this.buttons.btnToArchive.unbind().on("click", this._onBtnAToArchive.bind(self)); + this.buttons.btnReserve.unbind().on("click", this._onBtnReserve.bind(self)); + this.buttons.btnsArbitration.unbind().on("click", this._onBtnArbitration.bind(self)); + this.buttons.btnSendReview.unbind().on("click", this._onBtnSendReview.bind(self)); + $('#paymentfromSite').unbind().on('click', this._onBtnPaymentFromSite.bind(self)); + $("#reserve-stage-modal").find('#stage-num').unbind().on('change', function (event) { + // console.log("select stage cost = ", self.stages[this.value - 1].data.cost); + $("#reserve-stage-modal").find('#stage-cost').html(self.stages[this.value - 1].data.cost); + }); + } + + // BINDS + + _onBtnApprove(event) { + event.preventDefault(); + const self = this; + if (!this.stages.every((el)=>el.is_valid())) { + console.error('Не все поля форм валидны'); + return + } + // При выполнении всех ajax запросов + Promise.all(this.stages.map((el)=>el.sendAjax_approve())).then(()=> { + this.buttons.btnApprove.hide(); + this.buttons.btnChange.show(); + this.buttons.btnToArchive.show(); + this.$stagesCount.attr('disabled', true); + // var currentRecipentId = $(self).data('id'); + // var secureOrder = true; + // + let message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = `Условия заказа ${self.orderName} отправлены на согласование`; + console.log("Send-WS Отправить на согласование"); + socket.send_stages_approve(message); + //TODO: раскомментировать дурацкое окно + // $('#popupOk').modal('show'); + // }) + }); + } // "Отправить на согласование" + + _onBtnChange(event) { + event.preventDefault(); + const self = this; + Promise.all(this.stages.map((el)=>el.sendAjax_change())).then(()=> { + this.buttons.btnApprove.show(); + this.buttons.btnChange.hide(); + this.buttons.btnToArchive.hide(); + this.$stagesCount.attr('disabled', false); + let message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = `Заказ ${self.orderName} отозван для внесения изменений`; + console.log("Send-WS Внести изменения"); + socket.send_stages_approve(message); + }); + + } // "Внести изменения" + + // TODO: test it + _onBtnAToArchive(event) { + event.preventDefault(); + const self = this; + $.ajax({ + // async: false, + url: `/api/orders/${this.orderId}/`, + type: 'DELETE', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + dataType: 'json', + }) + .done(function (json) { + console.log('delete complete'); + window.location.href = window.location.href.replace(getHash(), ""); + let message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = `Заказа ${self.orderName} отправлен в архив`; + console.log("Send-WS Отправить в архив"); + socket.send_stages_approve(message); + }) + .fail(function (xhr, errorMsg, error) { + console.log("delete fail, json -->", xhr); + }); + + } // "Отказаться и отправить в архив" + + _onBtnReserve(event) { + const self = this; + event.preventDefault(); + // Set modal-window params + let $modal = $("#reserve-stage-modal"); + let total_cost = this.stages.map((el)=>parseInt(el.data.cost)).reduce((a, b) => a + b, 0); + // console.log('total cost = ', total_cost); + $modal.find('#total-cost').html(total_cost); + + let $select_stageNum = $modal.find('#stage-num'); + $select_stageNum + .find('option') + .remove() + .end(); + for (let stage of this.stages) { + if (stage.data.is_paid) continue; + $select_stageNum.append(``); + } + // let $stage_cost = $modal.find('#stage-cost'); + // $stage_cost.html(self.stages[this.value - 1].data.cost); + $modal.find('#stage-num').trigger('change'); + + $modal.modal('show'); + } // "Зарезервировать" --> Открывает модальное окно для резервирования + + _onBtnPaymentFromSite(event) { + const self = this; + event.preventDefault(); + let $modal = $("#reserve-stage-modal"); + let sum, stages_id; + if ($modal.find('input[name=choice_way]:checked').val() == 'all_stages') { + sum = $modal.find('#total-cost').html(); + stages_id = this.stages.map((el)=>el.data.id); + } else { + sum = $modal.find('#stage-cost').html(); + let num_stage = $modal.find('#stage-num').val() - 1; + stages_id = [this.stages[num_stage].data.id]; + } + $.ajax({ + url: '/wallets/payfromscore/', + type: 'POST', + beforeSend: function (xhr) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + data: { + sum: sum, + stages_id: stages_id.join(';'), + }, + dataType: 'json', + success: function (json) { + // console.log('success pay stage, json ', json); + $("#reserve-stage-modal").modal('toggle'); + let message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = `Заказчик зарезервировал сумму для этапов`; + console.log("Send-WS Оплата Этапа/Этапов"); + socket.send_stages_approve(message); + self.redraw(); + }, + error: function (xhr) { + console.log('error pay stage, json', xhr.responseJSON); + $.jGrowl(xhr.responseJSON.message_error); + } + }); + } // Оплата с сайта(Счет на Proekton) + + _onBtnClose(stage, event) { + event.preventDefault(); + const self = this; + stage.sendAjax_close() + .then(function (json) { + console.log("Этап закрыт успешно"); + let message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = `Заказчик закрыл этап ${json.name}`; + console.log("Send-WS Оплата Этапа/Этапов"); + socket.send_stages_approve(message); + self.redraw(); + }) + .catch(function (xhr) { + console.log("При закрытии этапа произошла ошибка -->", xhr); + }) + + } // "Закрыть этап" + + _onBtnReviewOpenModal(event) { + event.preventDefault(); + $('#review-add').modal('show'); + } // Открыть модальное окно "Оставить отзыв" + + _onBtnSendReview(event) { + event.preventDefault(); + const self = this; + $('#projectReviewId').val(this.projectId); + $('#targetContractorId').val(this.recipentId); + 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) { + $('#review-add').modal('hide'); + let message = message_format; + message.data.sender_id = userId; + message.data.recipent_id = self.recipentId; + message.data.order_id = self.orderId; + message.data.msg = `Отзыв на заказ ${self.orderName} оставлен`; + console.log("Send-WS Оставить отзыв"); + socket.send_stages_approve(message); + window.location = '/chat/#order'; + location.reload(); + // $("a[href='#tab2']").trigger('click'); + }, + error: function (e) { + console.log('error'); + console.log(e); + } + }); + } // "Оставить отзыв" + + + _onBtnArbitration(event) { + event.preventDefault(); + $("#arbitration-add").modal('show'); + } // "Обратиться в арбитраж" + + _onLoadDataError(error) { + console.log("Error loading data -->", error); + } +} + +export {StagesController} \ No newline at end of file diff --git a/assets/js/src/chat/archiveProjects.js b/assets/js/src/chat/archiveProjects.js new file mode 100644 index 0000000..aabd223 --- /dev/null +++ b/assets/js/src/chat/archiveProjects.js @@ -0,0 +1,84 @@ +import {getCookie} from '../utils' + + +function bindArchiveProjects() { + // Нажимаем на кнопку архивные сообщения + $("#trashed-button").on('click', function (e) { + e.preventDefault(); + var state = $(this).attr('data-show'); + var trashedOrderHtml = ""; + + if (state == 'true') { + $(this).attr('data-show', 'false'); + $(this).text("Скрыть архивные заказы"); + + $("#archive-space").show(); + $("#show-archive-label").show(); + + } else { + $(this).attr('data-show', 'true'); + $(this).text("Показать архивные заказы"); + $("#archive-space").hide(); + $("#show-archive-label").hide(); + } + + + }); + + // Нажимаем на заказ в архмвных заказах + $(".messageBlock").on('click', '.trashedOrderBlock', function () { + let $this = $(this); + $("#chat-order-add").css("display", "none"); + $('.order-block, .trashedOrderBlock').each(function () { + $(this).removeClass('orAct'); + }); + $this.addClass('orAct'); + // var inbox = document.getElementById('message-chat-order-space'); + // var docList = document.getElementById('documentOrderSpace'); + // inbox.innerHTML = ''; + // docList.innerHTML = ''; + + + let orderId = $this.data('id'); + // let projectId = $this.data('project-id'); + // let recipentId = $this.data('recipent-id'); + // let orderName = $this.data('order-name'); + location.hash = '#order' + orderId; + // console.log(orderId); + window.chatController.create(orderId); + // $.ajax({ + // url: '/api/message', + // type: 'GET', + // beforeSend: function (xhr) { + // xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + // }, + // data: {'order': orderId, 'team__isnull': 'true'}, + // dataType: 'json', + // success: function (json) { + // $.each(json.results, function (i, v) { + // var senderName = 'Вы'; + // var className = 'youChat'; + // + // if (v.sender.id !== userId) { + // senderName = v.sender.username; + // className = ''; + // } + // + // inbox.innerHTML += '
    ' + + // '

    ' + senderName + '

    ' + v.created + '
    ' + + // '

    ' + v.text + '

    '; + // + // }); + // var height = inbox.scrollHeight; + // inbox.scrollTop = height; + // } + // }); + + // $("#order-stages").html(""); + // $("#completeWork").hide(); + // $("#add-form-order-note").hide(); + // $("#reserveSpace").hide(); + }); +} + +export {bindArchiveProjects} \ No newline at end of file diff --git a/assets/js/src/chat/chats.js b/assets/js/src/chat/chats.js new file mode 100644 index 0000000..4b15a62 --- /dev/null +++ b/assets/js/src/chat/chats.js @@ -0,0 +1,145 @@ +function chatContactsInit() { + /** + * Bind на кнопку "Отправить" в Закладке "Личные контакты" + */ + $('#contact-chat-add-message').on('click', function (e) { + e.preventDefault(); + var chatMessage = $("#chat").val(); + var recipentId = $("#recipentContactId").val(); + var senderId = $("#senderContactId").val(); + var sendLinks = $("#document-send-contact a"); + + if (chatMessage || sendLinks.length > 0) { + $("#contact-chat-form .errorEmptyMessage").hide(); + + 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 = ", 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(); + } + + }); +} + +function chatOrdersInit() { + /** + * Bind на кнопку "Отправить" в Закладке "Исполнители/Заказчики" + */ + $('#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(); + var sendLinks = $("#document-send-order a"); + if (chatMessage || sendLinks.length > 0) { + 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(); + } + + }); +} + +function chatTeamsInit() { + $("#add-team-chat-message").on('click', function (e) { + e.preventDefault(); + var chatMessage = $("#team-chat-form #chatText").val(); + // var recipentId = $("#team-chat-form #recipentTeamId").val(); + var senderId = $("#team-chat-form #senderTeamId").val(); + var teamId = $("#team-chat-form #teamId").val(); + // var orderId = $("#team-chat-form #orderTeamId").val(); + var documentSendIds = $("#documentSendIds").val(); + var teamIds = $("#team-chat-form #teamIds").val(); + var sendLinks = $("#document-send a"); + if (chatMessage || sendLinks.length > 0) { + 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_team", + "data": { + "sender_id": senderId, + // "recipent_id": recipentId, + "chat_message": chatMessage, + "team_id": teamId, + "team_ids": teamIds, + // "order_id": orderId, + "document_send_links": sendLinkIds, + "document_data": { + "document_links": documentLinks, + "document_attach_files": documentAttachFiles, + } + } + }); + + $("#team-chat-form #chatText").val(""); + $("#document-send").html(""); + $("#documentSendIds").val(""); + } else { + $("#team-chat-form .errorEmptyMessage").show(); + } + }); +} + + +export {chatContactsInit, chatOrdersInit, chatTeamsInit} \ No newline at end of file diff --git a/assets/js/src/chat/documents.js b/assets/js/src/chat/documents.js new file mode 100644 index 0000000..5045aec --- /dev/null +++ b/assets/js/src/chat/documents.js @@ -0,0 +1,157 @@ +import {getCookie} from '../utils' + +function uploadDocumentsContactInit() { + $("#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("Upload form data -->", this.formData); + $('#progress .progress-bar').css( + 'width', + '0%' + ); + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + dataType: 'json', + done: function (e, data) { + $.each(data.result.files, function (index, file) { + var htmlImg = ''; + 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'); +} + +function uploadDocumentsOrderInit() { + $("#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%' + ); + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')) + }, + dataType: 'json', + done: function (e, data) { + $.each(data.result.files, function (index, file) { + var htmlImg = ''; + 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'); +} + +function uploadDocumentsTeamInit() { + $("#upload-document-team").bind('fileuploadsubmit', function (e, data) { + data.formData = { + sender: $("#team-chat-form #senderTeamId").val(), + recipent: $("#team-chat-form #recipentTeamId").val(), + order: $("#team-chat-form #orderTeamId").val(), + team: $("#team-chat-form #teamId").val(), + }; + // console.log(data.formData); + }); + + $('#upload-document-team').fileupload({ + url: '/chat/create/', + crossDomain: false, + beforeSend: function (xhr, settings) { + $('#progress .progress-bar').css( + 'width', + '0%' + ); + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + }, + dataType: 'json', + done: function (e, data) { + $.each(data.result.files, function (index, file) { + var currentValue = $("#documentSendIds").val(); + currentValue += file.id + ';'; + $("#documentSendIds").val(currentValue); + var htmlImg = ''; + var document_send = $(htmlImg).appendTo("#document-send"); + }); + }, + 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'); +} + +function bindRemoveDocuments() { + $('.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); + } + }); + }); +} + +export {uploadDocumentsContactInit, uploadDocumentsOrderInit, uploadDocumentsTeamInit, bindRemoveDocuments} \ No newline at end of file diff --git a/assets/js/src/chat/formats/receive_message_formats.py b/assets/js/src/chat/formats/receive_message_formats.py new file mode 100644 index 0000000..e8d7798 --- /dev/null +++ b/assets/js/src/chat/formats/receive_message_formats.py @@ -0,0 +1,9 @@ +write_message = {'msg': "", + 'msg_time': ".strftime('%Y-%m-%d %H:%M:%S')", + 'order_id': "", + 'recipent_id': "", + 'sender_id': "", + 'sender_name': "", + 'answer_type': "", + 'docs_attach': "", + } diff --git a/assets/js/src/chat/formats/send_message_formats.js b/assets/js/src/chat/formats/send_message_formats.js new file mode 100644 index 0000000..72bfd0f --- /dev/null +++ b/assets/js/src/chat/formats/send_message_formats.js @@ -0,0 +1,36 @@ +//1-approve_stages +var approve_stages = { + "format_type": "approve_stages", + "data": { + "sender_id": "", + "recipent_id": "", + "order_id": "", + "msg": "Заказчик зарезервировал сумму для этапов " + json.stages, + } +}; + +//2-add_message_order +var add_message_order = { + "format_type": "add_message_order", + "data": { + "sender_id": "", + "recipent_id": "", + "chat_message": "", + "order_id": "", + "document_send_links": "id;id;id", + "document_data": { + "document_links": 'links/document_link_tmpl.html(...copy)', + "document_attach_files": 'links/document_attach_file_tmpl.html(...copy)', + } + } + +}; + +//3-add_message_contact +var add_message_contact = add_message_order; + +//4-add_message_team +var add_message_team = add_message_order; +add_message_team["team_id"] = ""; +add_message_team["team_ids"] = "id;id;id"; + diff --git a/assets/js/src/chat/loaders.js b/assets/js/src/chat/loaders.js new file mode 100644 index 0000000..7b76cb6 --- /dev/null +++ b/assets/js/src/chat/loaders.js @@ -0,0 +1,28 @@ +import stage_tmpl from './templates/stage_tmpl.html' +import stage_approved_tmpl from './templates/stage_approved_tmpl.html' +import reserved_tmpl from './templates/reserved_tmpl.html' +import message_tmpl from './templates/message_tmpl.html' +import work_in_process_tmpl from './templates/work_in_process_tmpl.html' +import bntCompleteStage_tmpl from './templates/buttons/bntCompleteStage_tmpl.html' +import btnSendReview_tmpl from './templates/buttons/btnSendReview_tmpl.html' +import document_attach_file_tmpl from './templates/links/document_attach_file_tmpl.html' +import note_tmpl from './templates/note_tmpl.html' + +function loadTemplate(template_name) { + let templates = { + stage_tmpl: stage_tmpl, + stage_approved_tmpl: stage_approved_tmpl, + reserved_tmpl: reserved_tmpl, + message_tmpl: message_tmpl, + work_in_process_tmpl: work_in_process_tmpl, + bntCompleteStage_tmpl: bntCompleteStage_tmpl, + btnSendReview_tmpl: btnSendReview_tmpl, + document_attach_file_tmpl: document_attach_file_tmpl, + note_tmpl: note_tmpl, + }; + + if (!templates[template_name]) throw new Error(`Template ${template_name} does not exist`); + return templates[template_name] +} + +export {loadTemplate} \ No newline at end of file diff --git a/assets/js/src/chat/messageCounters.js b/assets/js/src/chat/messageCounters.js new file mode 100644 index 0000000..b4169de --- /dev/null +++ b/assets/js/src/chat/messageCounters.js @@ -0,0 +1,43 @@ +function recalculateTabsCounter() { + // let tabs = [$('#count-tab-contact'), $('#count-tab-order'), $('#count-tab-team')] + let tabs = [$('#tab1'), $('#tab2'), $('#tab3')]; + let total_messages_count = 0; + for (let tab of tabs){ + let count_sum = Array.from((tab.find('.js-count').map((i, el)=>parseInt($(el).html())))).reduce((a, b) => a + b, 0); + let $tab_counter = $(`a[href="#${tab.attr('id')}"]`).find('.count-tab'); + $tab_counter.html(count_sum); + total_messages_count += count_sum; + // console.log($tab_counter, 'new value -->', count_sum); + } + let $header_counter = $('.js-all-messages'); + $header_counter.html(total_messages_count); +} + +function countPlus(message, place) { + /** + * Увеличиваем счетчик соответствующий сообщению(message) + */ + // console.log("MESSAGE = ", message); + let $container; + if (message.answer_type == "add_message_contact"){ + $container = $(`.contact-count-${message.sender_id}`); + } else if (message.answer_type == "add_message_order"){ + $container = $(`#count-order-${message.order_id}`); + } else if (message.answer_type == "add_message_team") { + $container = $(`#count-team-${message.team_id}`); + } + // console.log("container = ", $container); + $container.html(parseInt($container.html()) + 1); + recalculateTabsCounter(); +} + +function onClickCardWithCount($card){ + /** + * При нажатии на карточку со счетчиком новых сообщений + */ + // console.log('Обнулем счетчик ', $card); + $card.find('.js-count').html(0); + recalculateTabsCounter(); +} + +export {countPlus, onClickCardWithCount} \ No newline at end of file diff --git a/assets/js/src/chat/notes.js b/assets/js/src/chat/notes.js new file mode 100644 index 0000000..1ec480b --- /dev/null +++ b/assets/js/src/chat/notes.js @@ -0,0 +1,77 @@ +import {loadTemplate} from './loaders' +var note_tmpl = loadTemplate('note_tmpl'); + +function bindContractorNotes() { + $('#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(""); + let li = note_tmpl({text: json.text}); + $(li).appendTo(".contractor-notes-block"); + }, + error: function (e) { + console.log('error'); + console.log(e); + } + }); + }); +} + +function bindOrderNotes() { + $('#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"); + let li = note_tmpl({text: json.text}); + $(li).appendTo(".order-notes-block"); + $("#add-form-order-note #chat2").val(""); + }, + error: function (e) { + console.log('error'); + console.log(e); + } + }); +}); +} + +function bindTeamNotes() { + $('#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); + } + }); +}); +} + +export {bindContractorNotes, bindOrderNotes, bindTeamNotes} \ No newline at end of file diff --git a/assets/js/src/chat/parts.js b/assets/js/src/chat/parts.js new file mode 100644 index 0000000..0d06e61 --- /dev/null +++ b/assets/js/src/chat/parts.js @@ -0,0 +1,27 @@ +import {getCookie} from '../utils' + +function restoreTabFromHash() { + var currentHash = URI(location.href).hash(); + if (currentHash.indexOf("#order") == 0) { + $("a[href='#tab2']").trigger('click'); + // console.log("click on ", "#orderBlock" + currentHash.replace("#order", "")); + let obj_id = currentHash.replace("#order", ""); + // console.log("obj_id = ", obj_id); + if (obj_id) { + $("#orderBlock" + currentHash.replace("#order", "")).trigger('click'); + } else { + $('.order-block').first().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'); + } +} + + + +export {restoreTabFromHash} \ No newline at end of file diff --git a/assets/js/src/chat/templates/buttons/bntCompleteStage_tmpl.html b/assets/js/src/chat/templates/buttons/bntCompleteStage_tmpl.html new file mode 100644 index 0000000..90a0edb --- /dev/null +++ b/assets/js/src/chat/templates/buttons/bntCompleteStage_tmpl.html @@ -0,0 +1,8 @@ + + \ No newline at end of file diff --git a/assets/js/src/chat/templates/buttons/btnSendReview_tmpl.html b/assets/js/src/chat/templates/buttons/btnSendReview_tmpl.html new file mode 100644 index 0000000..df81dfc --- /dev/null +++ b/assets/js/src/chat/templates/buttons/btnSendReview_tmpl.html @@ -0,0 +1,6 @@ + \ No newline at end of file diff --git a/assets/js/src/chat/templates/links/document_attach_file_tmpl.html b/assets/js/src/chat/templates/links/document_attach_file_tmpl.html new file mode 100644 index 0000000..73fd89e --- /dev/null +++ b/assets/js/src/chat/templates/links/document_attach_file_tmpl.html @@ -0,0 +1,12 @@ + +
  • + ${this.text} +
    +
  • + + \ No newline at end of file diff --git a/assets/js/src/chat/templates/links/document_link_tmpl.html b/assets/js/src/chat/templates/links/document_link_tmpl.html new file mode 100644 index 0000000..f82849b --- /dev/null +++ b/assets/js/src/chat/templates/links/document_link_tmpl.html @@ -0,0 +1,7 @@ + +
    + Приложенный файл. скачать:
    + + $(this.text) + +
    \ No newline at end of file diff --git a/assets/js/src/chat/templates/message_tmpl.html b/assets/js/src/chat/templates/message_tmpl.html new file mode 100644 index 0000000..c7197e1 --- /dev/null +++ b/assets/js/src/chat/templates/message_tmpl.html @@ -0,0 +1,7 @@ + +
    +
    +

    ${this.senderName}

    ${this.message.created} +
    +

    ${this.message.text}

    +
    \ No newline at end of file diff --git a/assets/js/src/chat/templates/note_tmpl.html b/assets/js/src/chat/templates/note_tmpl.html new file mode 100644 index 0000000..e13300f --- /dev/null +++ b/assets/js/src/chat/templates/note_tmpl.html @@ -0,0 +1,6 @@ +
    +
  • + ${this.text} +
  • +
    +
    diff --git a/assets/js/src/chat/templates/reserved_tmpl.html b/assets/js/src/chat/templates/reserved_tmpl.html new file mode 100644 index 0000000..411014b --- /dev/null +++ b/assets/js/src/chat/templates/reserved_tmpl.html @@ -0,0 +1,5 @@ + + +
  • Сумма за этап ${this.stage.pos} +
    ${this.reserved_name}
    +
  • \ No newline at end of file diff --git a/assets/js/src/chat/templates/stage_approved_tmpl.html b/assets/js/src/chat/templates/stage_approved_tmpl.html new file mode 100644 index 0000000..31f12be --- /dev/null +++ b/assets/js/src/chat/templates/stage_approved_tmpl.html @@ -0,0 +1,29 @@ + +
    +
    +
    + ЭТАП ${this.stage_num} +
    +
    + ${this.stage_status} +
    +
    +
    + +
    + ${this.stage.name} +
    + Результат этапа +
    + ${this.stage.result} +
    + Цена +
    + ${this.stage.cost} ₽ +
    + Срок +
    + до ${this.stage.term} +
    + +
    \ No newline at end of file diff --git a/assets/js/src/chat/templates/stage_tmpl.html b/assets/js/src/chat/templates/stage_tmpl.html new file mode 100644 index 0000000..ac21205 --- /dev/null +++ b/assets/js/src/chat/templates/stage_tmpl.html @@ -0,0 +1,29 @@ + +
    +

    ЭТАП ${this.stage_num}

    +
    + + +

    + + +

    + +

    + + + + +

    + + +

    +
    +
    \ No newline at end of file diff --git a/assets/js/src/chat/templates/work_in_process_tmpl.html b/assets/js/src/chat/templates/work_in_process_tmpl.html new file mode 100644 index 0000000..f14d97c --- /dev/null +++ b/assets/js/src/chat/templates/work_in_process_tmpl.html @@ -0,0 +1,10 @@ + +
    + В работе: ${this.stage.name}
    + Результат этапа: ${this.stage.result}
    + Срок сдачи: ${this.stage.term}
    + ${this.stage.cost} р +
    + ${this.note_text} +
    +
    \ No newline at end of file diff --git a/assets/js/src/chat/utils_debug.js b/assets/js/src/chat/utils_debug.js new file mode 100644 index 0000000..7ca565b --- /dev/null +++ b/assets/js/src/chat/utils_debug.js @@ -0,0 +1,6 @@ +function ws_print(...messages) { + let message = messages.join(' '); + console.log(`%c WS: ${message}`, 'background: white; color: blue'); +} + +export {ws_print} \ No newline at end of file diff --git a/assets/js/src/chat/wsChatConnect.js b/assets/js/src/chat/wsChatConnect.js new file mode 100644 index 0000000..5b8db0b --- /dev/null +++ b/assets/js/src/chat/wsChatConnect.js @@ -0,0 +1,114 @@ +import {loadTemplate} from './loaders' +import {countPlus} from './messageCounters' + +function getUserPlace() { + /** + * Определяем в какой закладке Чата пользователь + */ + let hash = location.hash; + let tab, id; + + for (let str of ["user", "order", "myteam"]) { + if (hash.indexOf(`#${str}`) != -1) { + tab = str; + id = hash.replace(`#${str}`, ''); + } + } + return {tab, id} +} + +function checkMessageInPlace(message, place) { + /** + * Проверяем, направлено ли входящее сообщение на текущую вкладку пользователя + */ + // message.answer_type=place.tab + let eq = ['add_message_contact=user', 'add_message_order=order', 'add_message_team=myteam', 'approve_stages=order']; + // console.log([message.answer_type, place.tab].join('=')); + // console.log(message.order_id, '==', place.id, message.order_id == place.id); + if ((eq.indexOf([message.answer_type, place.tab].join('=')) != -1) && + ((message.order_id == place.id) || (message.recipent_id == place.id) || (message.sender_id == place.id) || (message.team_id == place.id))) { + + return true + } + return false +} + +function connect() { + wsConnect.then(function (_socket) { + socket = _socket; + // Onmessage in Chat page + socket.addEventListener("message", function (event) { + var data = JSON.parse(event.data); + print.ws_print("new message on Chat page"); + console.log(", message =", data); + + let user_place = getUserPlace(); + // console.log("User place ", place.tab, place.id); + + if (checkMessageInPlace(data, user_place)) { + console.log("Сообщение принято открытым чатом"); + let chat_container_selectors = { + "user": "#message-chat-space", + "order": "#message-chat-order-space", + "myteam": "#message-chat-team-space", + }; + let documents_container_seletors = { + "user": "#documentSpace", + "order": "#documentOrderSpace", + "myteam": "#documentTeamSpace", + }; + let $chat_container = $(chat_container_selectors[user_place.tab]); + let $documents_container = $(documents_container_seletors[user_place.tab]); + var classMessage = 'youChat'; + var senderName = 'Вы'; + if (data.sender_id != userId) { + senderName = data.sender_name; + classMessage = ''; + } + if (data.is_system){ + senderName = 'Системное'; + classMessage = 'systemChat' + } + + let chat_message = loadTemplate('message_tmpl')({ + className: classMessage, + senderName: senderName, + message: {created: data.msg_time, text: data.msg} + }); + $chat_container.append(chat_message); + $chat_container.scrollTop($chat_container.prop("scrollHeight")); + + $documents_container.append(data.docs_attach); + + if (data.answer_type == 'approve_stages') { + window.chatController.statesController.redraw(); + } + + } else { + console.log("Сообщение учтено счетчиком"); + countPlus(data, user_place) + } + + }); + + socket.addEventListener("close", function () { + console.error("Connection Lost"); + connect(); + }); + + socket.send_message = function (messageData) { + console.log('send message -->', messageData); + socket.send(JSON.stringify(messageData)); + }; + + socket.send_stages_approve = function (messageData) { + // TODO: Пометить сообщения как "системные" + socket.send(JSON.stringify(messageData)); + }; + }); + wsConnect.catch(function (reason) { + console.error("Server is not available", reason) + }) +} + +export {connect} \ No newline at end of file diff --git a/assets/js/src/chat_contractor_oop.js b/assets/js/src/chat_contractor_oop.js new file mode 100644 index 0000000..4bb146d --- /dev/null +++ b/assets/js/src/chat_contractor_oop.js @@ -0,0 +1,63 @@ +import {ChatPageController} from './chat/ChatContractorPageController' +import { + bindOrders, + bindArbitrationSend, + bindOnTabs, + bindUserContacts, + bindGetUserMessages, + bindTeams, + bindDeleteContact +} from './chat/BINDS' + +import { + uploadDocumentsContactInit, + uploadDocumentsOrderInit, + uploadDocumentsTeamInit, + bindRemoveDocuments +} from './chat/documents' + +import {bindContractorNotes, bindOrderNotes, bindTeamNotes} from './chat/notes' + +import {restoreTabFromHash} from './chat/parts' + +import {bindArchiveProjects} from './chat/archiveProjects' + +import {chatContactsInit, chatOrdersInit, chatTeamsInit} from './chat/chats' +import {connect} from './chat/wsChatConnect' + +window.connect = connect; +window.socket = undefined; + +$(function () { + bindArbitrationSend(); + window.onhashchange = function (e) { + $('a[data-toggle="tab"][href="#' + location.hash.slice(1) + '"]').trigger("click"); + }; + window.chatController = new ChatPageController(); + bindOrders(); + bindTeams(); + bindOnTabs(); + bindUserContacts(); + bindGetUserMessages(); + bindArchiveProjects(); + bindDeleteContact(); + + // Chats + chatContactsInit(); + chatOrdersInit(); + chatTeamsInit(); + + //Documents + uploadDocumentsContactInit(); + uploadDocumentsOrderInit(); + uploadDocumentsTeamInit(); + bindRemoveDocuments(); + + //Notes + bindContractorNotes(); + bindOrderNotes(); + bindTeamNotes(); + + //restore + restoreTabFromHash(); +}); \ No newline at end of file diff --git a/assets/js/src/chat_customer_oop.js b/assets/js/src/chat_customer_oop.js new file mode 100644 index 0000000..293589b --- /dev/null +++ b/assets/js/src/chat_customer_oop.js @@ -0,0 +1,47 @@ +import {ChatPageController} from './chat/ChatCustomerPageController' +import { + bindOrders, + bindArbitrationSend, + bindOnTabs, + bindUserContacts, + bindGetUserMessages, + bindDeleteContact +} from './chat/BINDS' + +import {restoreTabFromHash} from './chat/parts' + +import {chatContactsInit, chatOrdersInit} from './chat/chats' +import {connect} from './chat/wsChatConnect' + +import {bindArchiveProjects} from './chat/archiveProjects' + +window.connect = connect; +window.socket = undefined; + +$(function () { + $('body').on('focus', ".term-picker", function () { + $(this).datepicker({ + minDate: 0, + }); + }); + + bindArbitrationSend(); + window.onhashchange = function (e) { + // console.log("Change Hash!!! ", 'a[data-toggle="tab"][href="#' + location.hash.slice(1) + '"]'); + $('a[data-toggle="tab"][href="#' + location.hash.slice(1) + '"]').trigger("click"); + }; + + window.chatController = new ChatPageController(); + bindOrders(); + bindOnTabs(); + restoreTabFromHash(); + bindUserContacts(); + bindGetUserMessages(); + bindArchiveProjects(); + bindDeleteContact(); + + //Chats + chatContactsInit(); + chatOrdersInit(); + +}); \ No newline at end of file diff --git a/assets/js/src/debugUtilsInit.js b/assets/js/src/debugUtilsInit.js new file mode 100644 index 0000000..7f91be3 --- /dev/null +++ b/assets/js/src/debugUtilsInit.js @@ -0,0 +1,5 @@ +import {ws_print} from './chat/utils_debug' + +// DEBUG +window.print = {}; +window.print.ws_print = ws_print; \ No newline at end of file diff --git a/assets/js/src/init_customer_project_create.js b/assets/js/src/init_customer_project_create.js index aff853c..9ab0c0d 100644 --- a/assets/js/src/init_customer_project_create.js +++ b/assets/js/src/init_customer_project_create.js @@ -115,8 +115,10 @@ $(function () { }else{ //Если перешли со страницы профиля по кнопке "Добавить заказ" let id = window.location.hash.replace("#", ""); - if (id) sb_realty_top.setElementById(id); - select_realty.add(id); + if (id) { + sb_realty_top.setElementById(id); + select_realty.add(id); + } } }); select_realty.on("add", (args)=> { diff --git a/assets/js/src/seeds/read_more.js b/assets/js/src/seeds/read_more.js index a6b12e0..36d6320 100644 --- a/assets/js/src/seeds/read_more.js +++ b/assets/js/src/seeds/read_more.js @@ -5,12 +5,6 @@ function readMoreInit() { $target.siblings(".complete").toggle(); $target.toggleClass("less"); }); - - // $(".more").toggle(function () { - // $(this).text("less..").siblings(".complete").show(); - // }, function () { - // $(this).text("more..").siblings(".complete").hide(); - // }); } export {readMoreInit} \ No newline at end of file diff --git a/assets/js/chat.js b/assets/js/trash/chat.js similarity index 88% rename from assets/js/chat.js rename to assets/js/trash/chat.js index 10ead9f..c852baa 100644 --- a/assets/js/chat.js +++ b/assets/js/trash/chat.js @@ -40,9 +40,9 @@ var SocketHandler = function () { var intervalId; sock.onopen = function () { console.log("Start connect"); - intervalId = setInterval(function () { - sock.send('{"dummy": 1}'); - }, 15000); + // intervalId = setInterval(function () { + // sock.send('{"dummy": 1}'); + // }, 15000); }; sock.onmessage = function (event) { @@ -140,68 +140,68 @@ $(function () { } var currentHash = URI(location.href).hash(); - $('a[data-toggle="tab"]').on('show.bs.tab', function (e) { - console.log("TAB!"); - 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': - console.log("tab2"); - updateCounts(); - 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'); - } + // $('a[data-toggle="tab"]').on('show.bs.tab', function (e) { + // console.log("TAB!"); + // 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': + // console.log("tab2"); + // updateCounts(); + // 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'); + // } // Информация о заказе $(".messageBlock").on('click','.full-order-info', function (e) { @@ -276,6 +276,7 @@ $(function () { }); }); + // "Оплата с сайта" (copy) $("#paymentfromSite").on('click', function () { var sum = $("#stageSumPay").val(); var stages = $("#stagesIds").val(); @@ -315,7 +316,7 @@ $(function () { }) }); - //Удаление документа + //Удаление документа(copy) $('.tab-content').on('click', '.remove-document', function (e) { e.preventDefault(); var dataId = $(this).attr('data-id'); @@ -338,7 +339,7 @@ $(function () { }); }); - // Вытащить сообщения для конактов + // Вытащить сообщения для конактов(copy) $('.user-block').on('click', function () { var newCount = parseInt($("#count-tab-contact").text()); var contactId = $(this).attr('data-id'); @@ -437,6 +438,7 @@ $(function () { }); + // Удалить контакт из "Личные" (copy) $('.deleteMess').on('click', function (e) { e.preventDefault(); e.stopPropagation(); @@ -512,6 +514,7 @@ $(function () { }); + // Добавление заметок Исполнителем (copy) $('#add-note-contractor').on('click', function (e) { e.preventDefault(); $.ajax({ @@ -534,7 +537,7 @@ $(function () { }); }); - //Добавить заметку. + //Добавить заметку Заказ (copy) $('#add-note-button').on('click', function (e) { e.preventDefault(); $.ajax({ @@ -556,7 +559,7 @@ $(function () { }); }); - //Добавить заметку. + //Добавить заметку Группа (copy) $('#add-team-note-button').on('click', function (e) { e.preventDefault(); $.ajax({ @@ -578,7 +581,7 @@ $(function () { }); }); - // Добавление сообщения для заказа. + // Добавление сообщения для заказа(copy) $('#order-chat-add-message').on('click', function (e) { e.preventDefault(); var chatMessage = $("#chat-order-add #chat").val(); @@ -620,7 +623,7 @@ $(function () { }); - // Добавление сообщения для контакта + // Добавление сообщения для контакта(copy) $('#contact-chat-add-message').on('click', function (e) { e.preventDefault(); var chatMessage = $("#chat").val(); @@ -664,7 +667,7 @@ $(function () { }); - // Добавление сообщения в арбитраж + // Добавление сообщения в арбитраж (copy) $('#order-arbitration-add').on('click', function (e) { e.preventDefault(); e.stopPropagation(); @@ -691,6 +694,7 @@ $(function () { }); }); + //Загрузка документов Order(copy) $("#upload-document-order").bind('fileuploadsubmit', function (e, data) { data.formData = { sender: $("#chat-order-add #senderId").val(), @@ -700,7 +704,7 @@ $(function () { console.log(data.formData); }); - //Загрузка документов + // + Загрузка документов Order(copy) $('#upload-document-order').fileupload({ url: '/chat/create/', crossDomain: false, @@ -734,6 +738,7 @@ $(function () { }).prop('disabled', !$.support.fileInput) .parent().addClass($.support.fileInput ? undefined : 'disabled'); //Загрузка документов + // + Загрузка документов Contact(copy) $("#upload-document-contact").bind('fileuploadsubmit', function (e, data) { data.formData = { sender: $("#contact-chat-form #senderContactId").val(), @@ -742,6 +747,7 @@ $(function () { }); + //Загрузка документов Contact(copy!) $('#upload-document-contact').fileupload({ url: '/chat/create/', crossDomain: false, @@ -783,7 +789,7 @@ $(function () { $("#text-new").val(""); }); - // Добавление отзыва + // Добавление отзыва(complete) $('#order-review-add').on('click', function (e) { e.preventDefault(); e.stopPropagation(); @@ -820,7 +826,7 @@ $(function () { }); }); - // Нажимаем на кнопку архивные сообщения + // Нажимаем на кнопку архивные сообщения(complete) $("#trashed-button").on('click',function(e){ e.preventDefault(); var state = $(this).attr('data-show'); @@ -833,31 +839,6 @@ $(function () { $("#archive-space").show(); $("#show-archive-label").show(); - //$.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 + '

    ' + - // 'Исполнитель:'+ v.contractor_name +'

    ' + - // '' + - // 'Полное описание заказа
    '; - // - // trashedOrderHtml += temp; - // }); - // $("#trashed-orders").html(trashedOrderHtml); - // - // }, - // error: function (e, jqxhr) { - // console.log(e); - // } - //}); - }else { $(this).attr('data-show','true'); $(this).text("Показать архивные заказы"); @@ -868,7 +849,7 @@ $(function () { }); - // Нажимаем на заказ в архмвных заказах + // Нажимаем на заказ в архмвных заказах(complete) $(".messageBlock").on('click','.trashedOrderBlock',function(){ $("#chat-order-add").css("display", "none"); $('.order-block, .trashedOrderBlock').each(function () { diff --git a/assets/js/chat_contractor.js b/assets/js/trash/chat_contractor.js similarity index 85% rename from assets/js/chat_contractor.js rename to assets/js/trash/chat_contractor.js index 871a2af..e666cb7 100644 --- a/assets/js/chat_contractor.js +++ b/assets/js/trash/chat_contractor.js @@ -1,3 +1,51 @@ +/***TEMPLATES***/ +var wrapper_btn_tmpl = (btn_tmpl) => + ` +
    ${btn_tmpl}
    +`; + +var btn_tmpl_approve = (args = {}) => + ` + +`; + +var btn_tmpl_change = (args = {}) => + ` + +`; + +var btn_tmpl_refuse = (args = {}) => + ` + +`; + +function replaceButtons($container, buttons_html = []) { + console.log("replace Buttons"); + $container.html(""); + for (var button_html of buttons_html) { + $container.append(button_html); + } +} + + $(function () { function dialog(message, yesCallback, notCallback) { @@ -19,6 +67,7 @@ $(function () { var url = '/chat/create/'; + // + Загрузка документов Team (complete) $("#upload-document-team").bind('fileuploadsubmit', function (e, data) { data.formData = { sender: $("#team-chat-form #senderTeamId").val(), @@ -29,7 +78,7 @@ $(function () { console.log(data.formData); }); - //Загрузка документов + //Загрузка документов Team (complete) $('#upload-document-team').fileupload({ url: url, crossDomain: false, @@ -49,7 +98,7 @@ $(function () { currentValue += file.id + ';'; $("#documentSendIds").val(currentValue); var htmlImg = ''; + '
    '; var document_send = $(htmlImg).appendTo("#document-send"); }); }, @@ -66,17 +115,17 @@ $(function () { }).prop('disabled', !$.support.fileInput) .parent().addClass($.support.fileInput ? undefined : 'disabled'); - // Согласование этапов + // "Согласовать" (complete) $("#order-stages").on('click', "#approve-stages", function (e) { e.preventDefault(); - var orderId = $(this).attr('data-order-id'); - var senderId = $(this).attr('data-sender-id'); - var recipentId = $(this).attr('data-recipent-id'); + var orderId = $(this).data('order-id'); + var senderId = $(this).data('sender-id'); + var recipentId = $(this).data('recipent-id'); var caption = "Вы действительно хотите согласовать этапы?"; confirm(caption, function () { $(".stage-block-approve").each(function () { - var stageId = $(this).attr('data-id'); + var stageId = $(this).data('id'); $.ajax({ //async: false, url: '/api/stages/' + stageId + '/', @@ -124,16 +173,17 @@ $(function () { }); - // Отказаться от этапов + // "Отправить на внесение изменений" (complete) $("#order-stages").on('click', "#cancel-stages", function (e) { + console.log("Отправить на внесение изменений"); e.preventDefault(); var senderId = $(this).attr('data-sender-id'); var recipentId = $(this).attr('data-recipent-id'); var orderId = $(this).attr('data-order-id'); var caption = "Вы действительно хотите отказаться от этапов?"; - confirm(caption,function() { + confirm(caption, function () { $(".stage-block-approve").each(function () { - var stageId = $(this).attr('data-id'); + var stageId = $(this).data('id'); $.ajax({ url: '/api/stages/' + stageId + '/', type: 'PATCH', @@ -165,7 +215,7 @@ $(function () { "msg": "Исполнитель отказался от текущих этапов " + orderId, } }); - }.bind(),caption); + }.bind(), caption); }); @@ -271,6 +321,7 @@ $(function () { }); + // Отображаем сообщения "Группы"(copy) $('.team-block').on('click', function () { $('.team-order-block, .team-block').each(function () { @@ -365,17 +416,19 @@ $(function () { }); - // Вытащить сообщения для чата заказа + // Заполняем страницу Заказа(complete) $('.order-block').on('click', function () { + console.log("Заполняем страницу Заказа"); $('.order-block').each(function () { $(this).removeClass('orAct'); }); $(this).addClass('orAct'); - var orderId = $(this).attr('data-id'); + var orderId = $(this).data('id'); location.hash = '#order' + orderId; - var recipentId = $(this).attr('data-recipent-id'); - var projectId = $(this).attr('data-project-id'); - var teamCurrentId = parseInt($(this).attr('data-team-id')); + var senderId = ''; + var recipentId = $(this).data('recipent-id'); + var projectId = $(this).data('project-id'); + var teamCurrentId = parseInt($(this).data('team-id')); var newCount = parseInt($("#count-tab-order").text()); var currNewCount = parseInt($(".order-count-" + orderId).text()); @@ -383,11 +436,11 @@ $(function () { $("#count-tab-order").text(resCount); $(".order-count-" + orderId).text(0); - if (teamCurrentId>0){ + if (teamCurrentId > 0) { $("#fromTeamId").val(teamCurrentId); $("#fromContractorId").val(""); - }else { - $("#fromTeamId").val("") + } else { + $("#fromTeamId").val(""); $("#fromContractorId").val(userId); } @@ -537,12 +590,36 @@ $(function () { if (statusNotAgreed) { - htmlInbox += ''; + // htmlInbox += wrapper_btn_tmpl( + // btn_tmpl_approve() + btn_tmpl_change() + btn_tmpl_refuse() + // ); + if (stagesResults[0] && stagesResults[0].status == 'send_approve') { + htmlInbox += + wrapper_btn_tmpl(btn_tmpl_approve({ + senderId: senderId, + recipentId: recipentId, + orderId: orderId + }) + + btn_tmpl_change({ + senderId: senderId, + recipentId: recipentId, + orderId: orderId + }) + + btn_tmpl_refuse({ + senderId: senderId, + recipentId: recipentId, + orderId: orderId + }) + ); + } else { + htmlInbox += wrapper_btn_tmpl(btn_tmpl_refuse({ + senderId: senderId, + recipentId: recipentId, + orderId: orderId + }) + ); + + } } } @@ -582,7 +659,7 @@ $(function () { } else { $("#leaveReview").hide(); } - }else{ + } else { $("#leaveReview").hide(); } }); @@ -590,6 +667,7 @@ $(function () { }); + // Закрыть этап (complete) $('#tab2').on('click', '.closeStage', function (e) { e.preventDefault(); var stageId = $(this).attr('data-stage-id'); @@ -623,7 +701,7 @@ $(function () { }); }); - //Добавить сообщение для исполнителей в группе + //Добавить сообщение для исполнителей в группе(copy) $("#add-team-chat-message").on('click', function (e) { e.preventDefault(); var chatMessage = $("#team-chat-form #chatText").val(); diff --git a/assets/js/chat_customer.js b/assets/js/trash/chat_customer.js similarity index 99% rename from assets/js/chat_customer.js rename to assets/js/trash/chat_customer.js index 7615ce7..5d50d28 100644 --- a/assets/js/chat_customer.js +++ b/assets/js/trash/chat_customer.js @@ -209,6 +209,7 @@ $(function () { htmlInbox = htmlInboxStage + htmlInbox; $("#order-stages").html(htmlInbox); $("#completeWork").hide(); + $("#completeWork").hide(); if (stagesInWork.length > 0) { $("#completeWork").show(); @@ -280,7 +281,7 @@ $(function () { }); }); - // Добавление этапов + // Добавление этапов(complete) $("#order-stages").on('click', "#addStagesForm", function (e) { e.preventDefault(); var currentOrderId = $(this).attr('data-order-id'); @@ -391,7 +392,7 @@ $(function () { }); -//Изменение счетчика + //Изменение счетчика(complete) $('#order-stages-tab').on('change', '#countStage', function () { var countStage = parseInt($(this).val()); var currentCountStage = $("#order-stages .numberStepp").length; @@ -431,7 +432,7 @@ $(function () { }); -// Для заказов все вытащить + // Для заказов все вытащить(complete) $('.order-block').on('click', function () { var newCount = parseInt($("#count-tab-order").text()); $("#chat-order-add").css("display", "block"); diff --git a/chat/chat.py b/chat/chat.py index 94cc6ff..8ee4175 100644 --- a/chat/chat.py +++ b/chat/chat.py @@ -22,8 +22,10 @@ class ChatHandler(websocket.WebSocketHandler): waiters = set() def open(self, *args, **kwargs): + print("open") self.user_id = kwargs.get('user_id', 1) self.waiters.add((self.user_id, self)) + print("num connection = ", len(self.waiters)) # @gen.coroutine def on_message(self, message): @@ -63,6 +65,7 @@ class ChatHandler(websocket.WebSocketHandler): team_ids_raw = message_data['data'].get('team_ids', None) message = message_data['data'].get('chat_message', None) docs_send_links = message_data['data'].get('document_send_links', None) + is_system = message_data['data'].get('is_system', False) if 'document_data' in message_data['data']: docs_links = message_data['data']['document_data'].get('document_links', ""); docs_attach = message_data['data']['document_data'].get('document_attach_files', "") @@ -88,16 +91,17 @@ class ChatHandler(websocket.WebSocketHandler): order_value = "NULL" if order_id is None or not order_id else order_id insert_sql = "INSERT INTO chat_message (id,text,created, sender_id,recipent_id," \ - " private_type,team_id, order_id,is_delete,is_new) " \ - "VALUES (DEFAULT,'{0}',NOW(),{1},{2},{3},{4},{5},{6},{7}) RETURNING id". \ - format(message, sender_id, recipent_id, private_type, team_value, order_value, is_delete, is_new) + " private_type,team_id, order_id,is_delete,is_new,is_system) " \ + "VALUES (DEFAULT,'{0}',NOW(),{1},{2},{3},{4},{5},{6},{7},{8}) RETURNING id". \ + format(message, sender_id, recipent_id, private_type, team_value, order_value, is_delete, is_new, is_system) cursor_list = yield dict(cursor=self.db.execute(insert_sql)) cursor = cursor_list.get('cursor') result = cursor.fetchone() message_id = result[0] + team_ids = [] if team_ids_raw: - team_ids = [t for t in team_ids_raw.rstrip(';').split(';')] + team_ids = [int(t) for t in team_ids_raw.rstrip(';').split(';')] values_str = ''; for t in team_ids: values_str += '(DEFAULT,{0},{1}),'.format(message_id, t) @@ -128,21 +132,31 @@ class ChatHandler(websocket.WebSocketHandler): if docs_links: message += '

    ' + docs_links - if message_type: - waiters = tuple(w for c, w in self.waiters if c == recipent_id) - else: - waiters = tuple(w for c, w in self.waiters if c == recipent_id or c == sender_id) - - for waiter in waiters: - waiter.write_message({'msg': message, - 'msg_time': msg_time, - 'order_id': order_id, - 'recipent_id': recipent_id, - 'sender_id': sender_id, - 'sender_name': sender_name, - 'answer_type': answer_type, - 'docs_attach': docs_attach, - }) + # if message_type: + # waiters = tuple(w for c, w in self.waiters if c == recipent_id) + # else: + # waiters = tuple(w for c, w in self.waiters if c == recipent_id or c == sender_id) + + # if answer_type == 'add_message_contact': order_id = recipent_id + # if answer_type == 'add_message_team': order_id = team_id + + for user_id, waiter in self.waiters: + # print(recipent_id, '==', waiter.user_id) + # print(sender_id, '==', waiter.user_id) + # print('types -->', type(recipent_id), type(sender_id), type(user_id)) + if int(recipent_id) == int(user_id) or int(sender_id) == int(user_id) or int(user_id) in team_ids: + # print("waiter.user_id = ", waiter.user_id) + waiter.write_message({'msg': message, + 'msg_time': msg_time, + 'order_id': order_id, + 'team_id': team_id, + 'recipent_id': recipent_id, + 'sender_id': sender_id, + 'sender_name': sender_name, + 'answer_type': answer_type, + 'is_system': is_system, + 'docs_attach': docs_attach, + }) def check_origin(self, origin): return True diff --git a/chat/migrations/0015_message_is_system.py b/chat/migrations/0015_message_is_system.py new file mode 100644 index 0000000..3249a88 --- /dev/null +++ b/chat/migrations/0015_message_is_system.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.7 on 2017-01-31 13:09 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('chat', '0014_newmessage'), + ] + + operations = [ + migrations.AddField( + model_name='message', + name='is_system', + field=models.BooleanField(default=False), + ), + ] diff --git a/chat/models.py b/chat/models.py index bbe164a..47728fa 100644 --- a/chat/models.py +++ b/chat/models.py @@ -10,11 +10,14 @@ class Message(models.Model): created = models.DateTimeField(default=timezone.now) order = models.ForeignKey(Order, related_name='messages', null=True, blank=True) sender = models.ForeignKey(User, related_name='sender_messages') + # TODO: recipent --> recipient recipent = models.ForeignKey(User, related_name='recipent_messages') private_type = models.BooleanField(default=False) team = models.ForeignKey(Team, related_name='messages', null=True, blank=True) is_delete = models.BooleanField(default=False) is_new = models.BooleanField(default=True) + # Системное + is_system = models.BooleanField(default=False) def __str__(self): return self.text diff --git a/chat/serializers.py b/chat/serializers.py index 0ef0750..e74fa59 100644 --- a/chat/serializers.py +++ b/chat/serializers.py @@ -56,6 +56,7 @@ class MessageSerializer(ModelSerializer): 'private_type', 'team', 'documents', + 'is_system' ) def get_text(self, obj): diff --git a/chat/static/sass/chat_add.sass b/chat/static/sass/chat_add.sass new file mode 100644 index 0000000..00ef1d4 --- /dev/null +++ b/chat/static/sass/chat_add.sass @@ -0,0 +1,325 @@ +@import "base/variavles" +@import "modules/mods" +@import "base/colors" + +%icons + margin-left: 0px + display: inline-flex + align-items: center + &:before + content: '' + display: inline-block + width: 20px + height: 20px + background-size: cover + position: relative + left: -5px + +.contractor-notes-block, .team-notes-block, .order-notes-block + text-align: left + padding-left: 45px + font-family: Arial, Verdana, Helvetica, sans-serif + +ol + li + display: list-item + list-style: decimal inside + white-space: nowrap + overflow: hidden + text-overflow: ellipsis + max-width: 180px + +.note-wrapper + position: relative + +.modal-header + text-align: center + +// Системное сообщение +.systemChat + background-color: #ffe9ed + +.review-type + .alignleft + float: left + //width: 33% + text-align: left + + .aligncenter + float: left + //width: 33% + text-align: center + + .alignright + float: right + //width: 33% + text-align: right + +.chat-button + transition: all 0.3s + width: 100% + background-color: #f1f1f1 + text-transform: uppercase + color: #373737 + //display: inline-block + font-family: "pfdintextcomppro-regular", sans-serif + font-size: 18px + letter-spacing: 1px + margin-bottom: 5px + &:visited, &:link + color: #373737 + &:hover + box-shadow: 0 0 15px rgba(0, 0, 0, 0.8) + transform: scale(1.04) + //color: #7e7e7e + padding: 25px 30px + &.icon-hand + @extend %icons + &:before + width: 25px + height: 25px + background: + image: url("#{$static}/img/icons/icon_hands_gray.png") + size: 24px 24px + repeat: no-repeat + &.icon-books + @extend %icons + &:before + width: 30px + height: 25px + background: + image: url("#{$static}/img/icons/icon_books.png") + size: 30px 25px + repeat: no-repeat + &.icon-print + @extend %icons + &:before + width: 30px + height: 25px + background: + image: url("#{$static}/img/icons/icon_print.png") + size: 30px 25px + repeat: no-repeat + &.icon-change + @extend %icons + &:before + width: 20px + height: 24px + background: + image: url("#{$static}/img/icons/icon_edit.png") + size: 20px 24px + repeat: no-repeat + &.icon-credit_card + @extend %icons + &:before + width: 25px + height: 28px + background: + image: url("#{$static}/img/icons/icon_credit_card_gray.png") + size: 25px 28px + repeat: no-repeat + &.icon-arbitration + @extend %icons + &:before + width: 25px + height: 28px + background: + image: url("#{$static}/img/icons/icon_arbitration.png") + size: 25px 28px + repeat: no-repeat + + &.icon-complete_stage + @extend %icons + &:before + width: 25px + height: 28px + background: + image: url("#{$static}/img/icons/icon_complete_stage.png") + size: 25px 28px + repeat: no-repeat + &.icon-check + @extend %icons + &:before + width: 25px + height: 25px + background: + image: url("#{$static}/img/icons/icon_check.png") + size: 25px 25px + repeat: no-repeat + +a.btn.btn-send + transition: all 0.3s + padding: 5px 25px !important + background-color: white + border: 1px solid #BEBEBE + border-radius: 40px + &:hover + transform: scale(1.04) + box-shadow: 0 0 15px rgba(0, 0, 0, 0.2) + &.icon-send + @extend %icons + &:before + width: 25px + height: 25px + background: + image: url("#{$static}/img/icons/icon_arrow_gray.png") + size: 24px 24px + repeat: no-repeat + +.icon-protect + display: inline-block + @extend %icons + &:before + width: 18px + height: 20px + left: 0 + background: + image: url("#{$static}/img/icons/icon_protect.png") + size: 18px 20px + repeat: no-repeat + +.icon-note + display: inline-block + @extend %icons + &:before + width: 30px + height: 20px + left: 0 + background: + image: url("#{$static}/img/icons/icon_pen_black.png") + size: 20px 20px + repeat: no-repeat + +.stage-data + padding-left: 3px + background-color: #f1f1f1 + color: #8c8c8c + font-size: 12px + +.stage-status + font-style: italic + color: #5e5e5e + +.stages-paid + li + padding-left: 25px + margin-top: 15px + .text + padding-left: 10px + .reserved + //display: inline-block + @extend %icons + &:before + width: 25px + height: 25px + background: + image: url("#{$static}/img/icons/icon_coins_green.png") + size: 25px 25px + repeat: no-repeat + + .unreserved + //display: inline-block + color: #FD010E + @extend %icons + &:before + width: 25px + height: 25px + background: + image: url("#{$static}/img/icons/icon_coins_red.png") + size: 25px 25px + repeat: no-repeat + .closed + //display: inline-block + @extend %icons + &:before + width: 25px + height: 25px + background: + image: url("#{$static}/img/icons/icon_coins_gray.png") + size: 25px 25px + repeat: no-repeat + +.border + border-top: 1px solid #CFCFCF + position: relative + height: 20px + margin-top: 10px + .bird + position: absolute + border: 30px solid transparent + border-top: 12px solid #CFCFCF + top: 0 + left: 50% + margin-left: -30px + &:before + content: '' + display: block + position: absolute + border: 30px solid transparent + border-top: 12px solid white + top: -13px + left: 50% + margin-left: -30px + +.select + color: #FD010E + +.note + color: #FD010E + padding-top: 10px + font-size: 12px + +//Team +.team-block + .team-user-list + overflow-y: auto + display: -webkit-box + line-height: 16px + max-height: 64px + hyphens: none + + .max-rows + overflow-y: hidden + display: -webkit-box + line-height: 16px + max-height: 32px + + .icon-hand + @extend %icons + &:before + width: 25px + height: 25px + background: + image: url("#{$static}/img/icons/icon_hands_gray.png") + size: 24px 24px + repeat: no-repeat + + a + cursor: crosshair + &:visited + color: #333333 + &:hover + color: black + +a.docs + &-more, &-less + color: #{map_get($component_colors, select)} + cursor: pointer + &:hover + color: darken(#FD010E, 25%) + box-shadow: none + + &-more:before + content: '...Развернуть' + &-less:before + content: '...Cвернуть' + +.remove-note + position: absolute + width: 11px + height: 11px + background: url('../img/delDoc.png') no-repeat center + background-size: cover + right: -20px !important + top: 2px + cursor: pointer \ No newline at end of file diff --git a/chat/templates/chat_contractor.html b/chat/templates/chat_contractor.html index 85860e3..b12ad3f 100644 --- a/chat/templates/chat_contractor.html +++ b/chat/templates/chat_contractor.html @@ -2,6 +2,11 @@ {% load staticfiles %} {% load thumbnail %} {% load user_tags %} +{% load sass_tags %} +{% block head_css %} + + +{% endblock %} {% block content %} {% include 'partials/header.html' %}
    @@ -27,8 +32,8 @@
  • - Исполнители,Группы{{ teams_ms_count }} + Группы{{ teams_ms_count }}
  • @@ -39,107 +44,116 @@
    -
    -
    -

    Контакты

    - {% for contact in contacts_users %} - {% include 'inc-contact-card.html' %} - {% endfor %} - -
    -
    - -
    -
    -
    - - - - - -
    -
    - -

    Прикрепить файл

    +
    +
    +
    +
    +
    + + Контакты + +
    +
    -
    - отправить -
    - -
    + {% for contact in contacts_users %} + {% include 'inc-contact-card.html' %} + {% endfor %} -
    -
    -

    Прикрепленные документы

    -
      -
    - - Распечатать с помощью ресурса - +
    -
    -
      -
    -
    -

    Для заметок

    - - - - - сохранить +
    +
    + + + + + + +
    + +
    +

    прикрепить файл

    +
    + отправить +
    +
    +
    +
    +
    + {% include 'partials/inc-attach-documents.html' with class='documentSpace' %} + {#

    Прикрепленные документы

    #} + {#
      #} + {#
    #} + {# #} +
    +
    +
      +
      +
      Для заметок
      + + + + + {# сохранить#} + сохранить +
      +
      - - {% include 'contact-info.html' %} - + + {% include 'contact-info.html' %} + +
      -
      -
      -

      Заказы

      - {% for order in orders %} -
      - -

      {{ order }}

      -
      -

      - - Исполнитель: {{ request.user.get_full_name }}

      - - - - Полное описание заказа - - +
      +
      +
      +
      +
      + + Заказы + +
      - {% endfor %} + {% for order in orders %} + {% include 'partials/inc-order-card.html' %} + {% endfor %} - {% if archive_orders %} - - - +
      +
      + +
      + + + + + +
      + +
      +

      прикрепить файл

      +
      + отправить +
      +
      +
      +
      -
      -
      -
      - -
      - - - - - -
      -
      - -

      Прикрепить файл

      +
      +
      +
      +
      + + Порядок работы + +
      +
      +
      + {# 1.Согласование условий #} +
      +

      + 1. Согласование условий

      +

      + Обсуджение задания и условий выполнения работы. Подтверждение заказа исполнителем. +

      +
      +
      -
      +
      + + - -
      -
      -

      Этапы работы

      -
      -

      1 / Согласование условий

      -

      - Обсуждение задания и условий выполнения работы. - Подтверждение заказа исполнителем. -

      -
      -
      - - + -
      -

      3 / Выполнение работы

      -

      - Процесс выполнения задания в заказе до получения - заказчиком итогового результата работы. -

      -
      + + -
      - @@ -263,137 +339,86 @@
      -
      -
      -

      Заказы

      - {% for torder in team_orders %} -
      - -

      - {{ torder }} -

      -
      -

      - - - Исполнитель: {{ torder.team.name }} -

      -
        - {% for tuser in torder.team.users.all %} -
      • {{ tuser }}
      • - {% endfor %} -
      -

      - Чаты: - {% if request.user.pk != torder.team.owner.pk %} - {{ torder.team.owner.username }} - {% endif %} - {% for tuser in torder.team.contractors.all %} - {% if request.user.pk != tuser.pk %} - {{ tuser.username }} - {% endif %} - {% endfor %} -

      - - - Полное описание заказа - +
      +
      +
      +
      +
      + + Группы + +
      - {% endfor %} - - {% for yteam in your_teams %} -
      - -

      - {{ yteam }} -

      -
      -

      - - Владелец группы: {{ yteam.owner }} -

      -
        - {% for tuser in yteam.contractors.all %} -
      • {{ tuser }}
      • - {% endfor %} -
      -

      - Чаты: - {% if request.user.pk != torder.team.owner.pk %} - {{ yteam.owner.username }} - {% endif %} - {% for tuser in yteam.contractors.all %} - {% if request.user.pk != tuser.pk %} - {{ tuser.username }} - {% endif %} - {% endfor %} -

      + {# {% for torder in team_orders %}#} + {# {% include 'partials/inc-order-card.html' with order=torder %}#} + {# {% endfor %}#} -
      -
      + {% for yteam in your_teams %} + {% include 'partials/inc-team-card.html' %} - {% endfor %} + {% endfor %} +
      -
      -
      -
      -
      - - - - - - - - -
      -
      - -

      Прикрепить файл

      -
      -
      -
      +
      +
      + + + + + + + + + +
      + +
      +

      прикрепить файл

      +
      + + отправить +
      +
      - -
      - отправить -
      - -
      -
      - -
      -

      Прикрепленные документы

      -
        - - Распечатать с помощью ресурса - +
        +
        + +
        + {% include 'partials/inc-attach-documents.html' with class='documentTeamSpace' %} + {#

        Прикрепленные документы

        #} + {#
          #} + {# #} +
          -
          -
            -
          -

          Для заметок

          -
          - - - - - - сохранить -
          +
          +
            + +
            +
            Для заметок
            + + + + + + {# сохранить#} + сохранить +
            +
            @@ -402,7 +427,9 @@ {% include 'order_info.html' %}
            - {% include 'partials/footer.html' %} +
            @@ -415,6 +442,7 @@ var port = '{{ request.META.SERVER_PORT }}'; - - + {# #} + {# #} + {% endblock %} diff --git a/chat/templates/chat_customer.html b/chat/templates/chat_customer.html index 0f65f65..ae52c63 100644 --- a/chat/templates/chat_customer.html +++ b/chat/templates/chat_customer.html @@ -1,13 +1,32 @@ {% extends 'partials/base.html' %} -{% load staticfiles %} +{% load static %} {% load thumbnail %} -{% load user_tags %} +{% load sass_tags %} +{% block head_css %} + + +{% endblock %} {% block content %} {% include 'partials/header.html' %} +
            -

            Чат

            +

            Переговорная

            @@ -31,61 +50,88 @@
            -
            -
            -

            Контакты

            - {% for contact in contacts_users %} - {% include 'inc-contact-card.html' %} - {% endfor %} +
            + +
            +
            +
            +
            + + Контакты + +
            +
            -
            -
            -
            -
            -
            - - - - - -
            -
            - -

            Прикрепить файл

            -
            - отправить + {% for contact in contacts_users %} + {% include 'inc-contact-card.html' %} + {% endfor %} +
            +
            + +
            +
            + + + + + - + {#
            #} + {#
            #} + {# #} + {#

            Прикрепить файл

            #} + {#
            #} + {#
            #} + {# отправить#} + {#
            #} + {# EDIT#} +
            + +
            +

            прикрепить файл

            +
            +
            + отправить +
            + + -
            -
            -
            -

            Прикрепленные документы

            -
              -
            - - Распечатать с помощью ресурса -
            + +
            +
            + {% include 'partials/inc-attach-documents.html' with class='documentSpace' %} + {#

            Прикрепленные документы

            #} + {#
              #} + {#
            #} + {# #} + {# Распечатать с помощью ресурса#} + {# #} +
            -
            -

            Заметки

            -
              -
            -
            -

            Для заметок

            - - - - сохранить -
            +
            +
              +
              +
              Для заметок
              + + + + + {# сохранить#} + сохранить +
              +
              - {% include 'contact-info.html' %} @@ -94,61 +140,43 @@
              -
              -
              -

              Заказы

              - {% for order in orders %} -
              - -

              {{ order }}

              -
              -

              - - Исполнитель: - {% if order.order.contractor %} - {{ order.order.contractor.get_full_name }} - {% else %} - {{ order.order.team.name }} - {% endif %} -

              - - - Полное описание заказа - - {# #} - {# Удалить заказ#} - {# #} +
              + +
              +
              +
              +
              + + Заказы + +
              - {% endfor %} + {% for order in orders %} + {% include 'partials/inc-order-card.html' %} + {% endfor %} - {% if archive_projects %} - - - -
              -
              -