create procedure dbo.%PROC% @moment varchar(30) = null, -- Дата сделки @contract varchar(30) = null, -- Номер сделки @deal_time varchar(30) = null, -- Время сделки @direct_no varchar(20) = null, -- НЕ ИСП. - Номер поручения (внутрибиржевого) @emi_code varchar(50) = null, -- Код бумаги на ММВБ @deal_code varchar(30) = null, -- Покупка/Продажа -> B/S @deal_account varchar(50) = null, -- НЕ ИСП. - Код торгового счета @price decimal(18,8) = null, -- Цена бумаги @qty money = null, -- Количество ЦБ (лотов!) @deal_sum decimal(18,8) = null, -- Сумма сделки @comis decimal(18,8) = null, -- Комиссия биржи @com_settle decimal(18,8) = null, -- НЕ ИСП. - Комиссия клиринговой компании @com_its decimal(18,8) = null, -- НЕ ИСП. - Комиссия ИТС @brok_code varchar(50) = null, -- НЕ ИСП. - Шифр брокера @company_code varchar(50) = null, -- НЕ ИСП. - Шифр клиенского договора? @client_code varchar(50) = null, -- Код инвестора (клиента)/комментарий(код раздела учета/поручение) - ИСП. только Код инвестора (клиента) - код ФОНДА @nkd decimal(18,4) = null, -- НКД @is_repo_rps varchar(255) = null, -- НЕ ИСП. - Сделка обычная, Неполные лоты, РПС или РЕПО @exec_code varchar(50) = null, -- НЕ ИСП. - Код исполнения сделки (R14 - РЕПО 14 дней) @repo_percent decimal(18,4) = null, -- НЕ ИСП. - Ставка РЕПО @repo_price decimal(18,8) = null, -- НЕ ИСП. - Цена второй части РЕПО @contragent varchar(50) = null, -- НЕ ИСП. - Код контрагента ------------------Параметры из "фильтра"--------------------------- @external_broker_id_s varchar(30) = null -- Отчет брокера as declare @sid varchar(30) .BEGIN('N') begin tran declare @comm_brok money, @comm_depo money, @comm_ts money, @coupon_account_sum money, @cur_id numeric, @foundation_id numeric, @initiator_id numeric, @is_coupon_in_sum int, @organisation_id numeric, @owner_id numeric, @pay_cur_id numeric, @stock_id numeric, @stock_price decimal(18,6), @stock_qty money, @sum_in_paycur money, @summ_doc_total money, @transaction_date datetime, @transaction_no varchar(80), @transaction_time datetime, @in_date datetime, @in_no varchar(50), @depo_doc_type integer declare @rate_value decimal(18,8), @rate_date datetime, @new_id numeric, @classvalue_id numeric, @stock_classvalue_id numeric, @acc_code_id numeric, @place_code_id numeric, @mess varchar(255), @doc_type_code varchar(255), @stock_out_sum_method_id numeric, @stock_out_method_id numeric, @acc_code varchar(50), @broker_acc_id numeric, @brok_dog_id numeric declare @rep_initiator_id numeric, @rep_organisation_id numeric, @rep_owner_id numeric, @rep_oper_type integer --Площадка ММВБ!!! declare @mmvb_code varchar(50) select @mmvb_code='MICEX' select @place_code_id = (select max(td_rate_places.id) from td_rate_places where upper(td_rate_places.place_code) = @mmvb_code and .ITEMS_EXISTS(td_rate_places.id)) if @place_code_id is null select @mess='Не найдена площадка ММВБ!' -- Поиск и проверки select @deal_code=upper(ltrim(rtrim(@deal_code))) select @emi_code=ltrim(rtrim(@emi_code)) select @client_code=ltrim(rtrim(@client_code)) select @mess=null if @deal_code not in ('B','S') select @mess='В данных импорта не указан тип сделки' if isnull(@emi_code,'')='' select @mess='В данных импорта не указан код ЦБ' if charindex('/',@client_code,1)>0 select @acc_code=substring(@client_code,1,charindex('/',@client_code,1)-1) else select @acc_code=@client_code if isnull(@acc_code,'')='' select @mess='В данных импорта не указан код клиента' if @mess is not null .EXIT_MESSAGE(@mess) select @classvalue_id=v.id from t_classes c, t_classvalues v where c.code='FUND_IMPORT_CODE' and v.code='MMVB_DEALS_CODE' and v.class_id=c.id if @classvalue_id is null .EXIT_MESSAGE('Не найден тип классификатора FUND_IMPORT_CODE со значением MMVB_DEALS_CODE для импорта сделок') if (select count(*) from t_item2class i where i.code=@acc_code and .ITEMS_EXISTS(i.item_id) and i.value_id=@classvalue_id) > 1 select @mess='Существуют несколько клиентов с указанным кодом: '+@acc_code if @mess is not null .EXIT_MESSAGE(@mess) select @stock_classvalue_id = (select classvalue_rate_id from td_rate_places where id = @place_code_id) if @stock_classvalue_id is null .EXIT_MESSAGE('У площадки не указано значение классификатора кодов ЦБ') if (select count(*) from t_item2class, td_stock_emis where t_item2class.value_id = @stock_classvalue_id and t_item2class.code is not null and t_item2class.code = @emi_code and t_item2class.item_id = td_stock_emis.id and .ITEMS_EXISTS_BY_TYPE(t_item2class.id, 'item2classvalues') and .ITEMS_EXISTS_BY_TYPE(td_stock_emis.id, 'td_stock_emis')) > 1 begin select @mess='Существуют несколько ЦБ с указанным кодом ММВБ: '+@emi_code .EXIT_MESSAGE(@mess) end select @stock_id=td_stock_emis.id from t_item2class, td_stock_emis where t_item2class.value_id = @stock_classvalue_id and t_item2class.code is not null and t_item2class.code = @emi_code and t_item2class.item_id = td_stock_emis.id and .ITEMS_EXISTS_BY_TYPE(t_item2class.id, 'ITEM2CLASSVALUES') and .ITEMS_EXISTS_BY_TYPE(td_stock_emis.id, 'TD_STOCK_EMIS') if @stock_id is null select @mess='Не найдена ЦБ с кодом ММВБ = '+@emi_code select @acc_code_id=i.item_id from t_item2class i where i.code=@acc_code and .ITEMS_EXISTS(i.item_id) and i.value_id=@classvalue_id -- Отчет брокера if @external_broker_id_s='' select @external_broker_id_s=null select @foundation_id = convert(numeric,@external_broker_id_s) if @foundation_id is not null --задан отчет брокера! begin if .ITEM_STATE_CODE(@foundation_id)<>'SET' .EXIT_MESSAGE('Указанный отчет брокера должен быть принят') select @rep_initiator_id=uk_id, @rep_organisation_id=brok_id, @rep_owner_id=fund_id, @rep_oper_type=rep_oper_type from t_sd_brok_rep where id=@foundation_id end -- Валюта select @cur_id=td_rate_places.cur_id from td_rate_places where id=@place_code_id --if @cur_id is null select @cur_id=.CUR('RUR') if @cur_id is null select @mess='В Площадке не указана валюта!' -- Фонд if upper(.ITEM_TYPE_CODE(@acc_code_id)) in ('PIF_FUND','NPF_FUND') select @owner_id=@acc_code_id if upper(.ITEM_TYPE_CODE(@acc_code_id)) = 'FUND_CONTRACTS' -- это НПФ через УК begin select @owner_id=d.owner_id, @initiator_id=b.client_id from td_depo_docs d, tb_contracts b where d.id=@acc_code_id and d.id=b.id and b.dog_type_id=3 if @initiator_id is null select @owner_id=null end if @owner_id is null select @mess='Не найден клиент с кодом: '+@acc_code if @foundation_id is not null and @rep_owner_id is not null and @owner_id<>@rep_owner_id select @mess='Фонд не соответствует указанному в выбранном отчете брокера' -- УК НПФ if @foundation_id is not null and @rep_owner_id is not null and isnull(@initiator_id,0)<>isnull(@rep_initiator_id,0) select @mess='УК НПФ не соответствует указанному в выбранном отчете брокера' -- Брокер if @foundation_id is not null --задан Отчет брокера begin select @organisation_id=@rep_organisation_id --id Брокера select @brok_dog_id=brok_dog_id from t_sd_brok_rep where id=@foundation_id --id Брокерского договора end else -- брокер по умолчанию select @organisation_id=s.id from t_partners s where s.partner_code=.GET_CONST('DEFAULT_BROKER') and .ITEMS_EXISTS_BY_TYPE(s.id, 'PARTNERS_JUR') if @organisation_id is null select @mess='Не найден Брокер' --Расчетный счет брокера declare @cnt int /* select @cnt=(select count(*) from t_bank_accounts where t_bank_accounts.partner_id=@organisation_id and t_bank_accounts.acc_type_id = 10 -- Расчетный счет and t_bank_accounts.acc_purpose_id = 1 --собственный and .ITEMS_EXISTS_BY_TYPE_STATE(t_bank_accounts.id,'BANK_ACCOUNTS','CRT')) */ select @cnt=(select count(*) from t_bank_accounts where t_bank_accounts.partner_id=@organisation_id and t_bank_accounts.acc_type_id = 10 -- Расчетный счет and t_bank_accounts.acc_purpose_id = 3 --Целевой Для ПИФ and t_bank_accounts.fund_id=@owner_id -- фонд and .ITEMS_EXISTS_BY_TYPE_STATE(t_bank_accounts.id,'BANK_ACCOUNTS','CRT')) if @cnt=1 select @broker_acc_id=(select t_bank_accounts.id from t_bank_accounts where t_bank_accounts.partner_id=@organisation_id and t_bank_accounts.acc_type_id = 10 -- Расчетный счет and t_bank_accounts.acc_purpose_id = 3 --Целевой Для ПИФ and t_bank_accounts.fund_id=@owner_id -- фонд and .ITEMS_EXISTS_BY_TYPE_STATE(t_bank_accounts.id,'BANK_ACCOUNTS','CRT')) if isnull(@cnt,0)=0 select @mess='Не найден расчетный счет Брокера' if @cnt>1 begin select @broker_acc_id=(select t_bank_accounts.id from t_bank_accounts where t_bank_accounts.partner_id=@organisation_id and t_bank_accounts.acc_type_id = 10 -- Расчетный счет and t_bank_accounts.acc_purpose_id = 3 --Целевой Для ПИФ and t_bank_accounts.fund_id=@owner_id -- фонд and t_bank_accounts.default_account=1 and .ITEMS_EXISTS_BY_TYPE_STATE(t_bank_accounts.id,'BANK_ACCOUNTS','CRT')) if @broker_acc_id is null select @broker_acc_id=(select max(t_bank_accounts.id) from t_bank_accounts where t_bank_accounts.partner_id=@organisation_id and t_bank_accounts.acc_type_id = 10 -- Расчетный счет and t_bank_accounts.acc_purpose_id = 3 --Целевой Для ПИФ and t_bank_accounts.fund_id=@owner_id -- фонд and .ITEMS_EXISTS_BY_TYPE_STATE(t_bank_accounts.id,'BANK_ACCOUNTS','CRT')) end --end of Расчетный счет брокера -- По умолчанию select @is_coupon_in_sum = 0, @pay_cur_id = .CUR('RUR'), @depo_doc_type=1 -- Напрямую if @moment='' select @moment=null if @deal_time='' select @deal_time=null select @transaction_date = convert(datetime,@moment,3), @transaction_no = ltrim(rtrim(@contract)), @transaction_time = convert(datetime,@deal_time,8), @comm_ts = convert(money,@comis), @summ_doc_total = abs(convert(money,@deal_sum)), @coupon_account_sum = convert(money,@nkd), @stock_price = convert(decimal(18,6),@price), @stock_qty = abs(@qty) ---------- /* У облигации цена - в процентах от номинала, количество - в штуках Вычисляем Цены облигаций */ declare @stock_class_type_id numeric,@price_file decimal(18,8) select @stock_class_type_id=(select t_stock_types.stock_type_id from t_stock_types,td_stock_emis where td_stock_emis.id=@stock_id and t_stock_types.id=td_stock_emis.stock_type_id) select @is_coupon_in_sum=convert(int,(.GET_CONST('ENTRY_CD'))) if @stock_class_type_id=2 --базовый тип ЦБ -облигация begin select @stock_price=@deal_sum/@qty select @price_file=@stock_price -- Если вычисленная цена незначительно отличается от цены в файле, то в сделку импортируем цену из файла (в т.ч. и цену второй части РЕПО) if abs(@stock_price-@price_file)<1 select @stock_price=@price_file if @is_coupon_in_sum<>0 and @is_coupon_in_sum<>1 .EXIT_MESSAGE('Неверное значение константы ENTRY_CD (Купонный доход входит (1) или не входит (0) в сумму сделки). Значение должно быть 1 или 0.') if @is_coupon_in_sum is null .EXIT_MESSAGE('Не найдена константа ENTRY_CD (Купонный доход входит (1) или не входит (0) в сумму сделки). Создайте константу.') end -------- --Проверка кол-ва - в лотах или в штуках if isnull(@stock_price,0)=0 .EXIT_MESSAGE('Цена бумаги не задана') if round(@summ_doc_total/@stock_price,0)!=round(@stock_qty,0) --кол-во не в штуках, а в лотах select @stock_qty=round(@summ_doc_total/@stock_price,0) -- округляем до целых! ---- select @in_date=@transaction_date if @mess is not null .EXIT_MESSAGE(@mess) -- Существующая сделка if @deal_code='B' select @doc_type_code='SD_BROK_BUY' if @deal_code='S' select @doc_type_code='SD_BROK_SALE' if exists(select 1 from tb_baysale_docitems b, td_depo_docs d where b.id=d.id and .ITEMS_EXISTS(b.id) and .ITEM_TYPE_CODE(b.id)=@doc_type_code and b.transaction_no=@transaction_no and b.transaction_date=@transaction_date and b.sale_place_id=@place_code_id and d.owner_id=@owner_id and isnull(d.initiator_id,0)=isnull(@initiator_id,0)) begin select @mess='Сделка уже существует: № '+@transaction_no+' от '+@moment+', площадка: '+'ММВБ'+', клиент: '+@acc_code .EXIT_MESSAGE(@mess) end -- Формирование .FUND_GEN_NO(@in_no,@depo_doc_type,@in_date) if @cur_id<>@pay_cur_id begin .CONVERT_SUM_DEC(@cur_id, @pay_cur_id, @transaction_date, 0, @summ_doc_total, @sum_in_paycur, @rate_value, @rate_date) select @sum_in_paycur=round(@sum_in_paycur,2) end else select @sum_in_paycur=@summ_doc_total if @sum_in_paycur is null select @mess='Не задана сумма сделки' if @stock_qty is null select @mess='Не задано количество ЦБ' if @transaction_date is null select @mess='Не задана дата сделки' if @transaction_no is null select @mess='Не задан номер сделки' --Брокерский договор и комиссии -- расчет комиссии брокера if @brok_dog_id is not null and isnull(@comm_brok,0)=0 begin .CALC_AGENT_COMIS(@sum_in_paycur,@comm_brok,@brok_dog_id,(.CUR_CODE(@pay_cur_id)),@transaction_date,@owner_id,4) select @comm_brok = round(@comm_brok,2) end -- расчет комиссии депо if @brok_dog_id is not null and isnull(@comm_depo,0)=0 begin .CALC_AGENT_COMIS(@sum_in_paycur,@comm_depo,@brok_dog_id,(.CUR_CODE(@pay_cur_id)),@transaction_date,@owner_id,6) select @comm_depo = round(@comm_depo,2) end if @brok_dog_id is null select @comm_brok=0, @comm_depo=0 --end of Брокерский договор и комиссии if @mess is not null .EXIT_MESSAGE(@mess) --Если сделка не найдена -> вставка сделки -- Вставка if @deal_code='B' begin .TYPE_INIT('SD_BROK_BUY',1) .TYPE_ASSIGN(comm_brok,@comm_brok,1) .TYPE_ASSIGN(comm_depo,@comm_depo,1) .TYPE_ASSIGN(comm_ts,@comm_ts,1) .TYPE_ASSIGN(is_comm_in_sum,0,1) -- комиссии не входят в покупку .TYPE_ASSIGN(coupon_account_sum,@coupon_account_sum,1) .TYPE_ASSIGN(cur_id,@cur_id,1) .TYPE_ASSIGN(foundation_id,@foundation_id,1) .TYPE_ASSIGN(initiator_id,@initiator_id,1) .TYPE_ASSIGN(is_coupon_in_sum,@is_coupon_in_sum,1) .TYPE_ASSIGN(organisation_id,@organisation_id,1) .TYPE_ASSIGN(owner_id,@owner_id,1) .TYPE_ASSIGN(pay_cur_id,@pay_cur_id,1) .TYPE_ASSIGN(sale_place_id,@place_code_id,1) .TYPE_ASSIGN(stock_id,@stock_id,1) .TYPE_ASSIGN(stock_price,@stock_price,1) .TYPE_ASSIGN(stock_qty,@stock_qty,1) .TYPE_ASSIGN(sum_in_paycur,@sum_in_paycur,1) .TYPE_ASSIGN(summ_doc_total,@summ_doc_total,1) .TYPE_ASSIGN(transaction_date,@transaction_date,1) .TYPE_ASSIGN(transaction_no,@transaction_no,1) .TYPE_ASSIGN(transaction_time,@transaction_time,1) .TYPE_ASSIGN(in_date,@in_date,1) .TYPE_ASSIGN(in_no,@in_no,1) .TYPE_ASSIGN(depo_doc_type,@depo_doc_type,1) .TYPE_ASSIGN(broker_acc_id,@broker_acc_id,1) .TYPE_ASSIGN(direction_id,@brok_dog_id,1) .TYPE_INSERT('SD_BROK_BUY','EDIT',1) select @new_id=.TYPE_FIELD(id,1) end if @deal_code='S' begin select @stock_out_sum_method_id = out_sum_method_id, @stock_out_method_id = out_method_id from td_pay_fond where id=@owner_id .TYPE_INIT('SD_BROK_SALE',2) .TYPE_ASSIGN(comm_brok,@comm_brok,2) .TYPE_ASSIGN(comm_depo,@comm_depo,2) .TYPE_ASSIGN(comm_ts,@comm_ts,2) .TYPE_ASSIGN(is_comm_in_sum,0,2) -- комиссии не входят в продажу .TYPE_ASSIGN(coupon_account_sum,@coupon_account_sum,2) .TYPE_ASSIGN(cur_id,@cur_id,2) .TYPE_ASSIGN(foundation_id,@foundation_id,2) .TYPE_ASSIGN(initiator_id,@initiator_id,2) .TYPE_ASSIGN(is_coupon_in_sum,@is_coupon_in_sum,2) .TYPE_ASSIGN(organisation_id,@organisation_id,2) .TYPE_ASSIGN(owner_id,@owner_id,2) .TYPE_ASSIGN(pay_cur_id,@pay_cur_id,2) .TYPE_ASSIGN(sale_place_id,@place_code_id,2) .TYPE_ASSIGN(stock_id,@stock_id,2) .TYPE_ASSIGN(stock_price,@stock_price,2) .TYPE_ASSIGN(stock_qty,@stock_qty,2) .TYPE_ASSIGN(sum_in_paycur,@sum_in_paycur,2) .TYPE_ASSIGN(summ_doc_total,@summ_doc_total,2) .TYPE_ASSIGN(transaction_date,@transaction_date,2) .TYPE_ASSIGN(transaction_no,@transaction_no,2) .TYPE_ASSIGN(transaction_time,@transaction_time,2) .TYPE_ASSIGN(in_date,@in_date,2) .TYPE_ASSIGN(in_no,@in_no,2) .TYPE_ASSIGN(depo_doc_type,@depo_doc_type,2) .TYPE_ASSIGN(stock_out_sum_method_id,@stock_out_sum_method_id,2) .TYPE_ASSIGN(stock_out_method_id,@stock_out_method_id,2) .TYPE_ASSIGN(broker_acc_id,@broker_acc_id,2) .TYPE_ASSIGN(direction_id,@brok_dog_id,2) .TYPE_INSERT('SD_BROK_SALE','EDIT',2) select @new_id=.TYPE_FIELD(id,2) end -- Информация для операции if @foundation_id is not null and @rep_oper_type=0 insert t_sd_info4oper (id,op_date,op_time,assent_date,is_fixed,reg_date,is_assent) select @new_id,@transaction_date,op_time,null,is_fixed,reg_date,is_assent from t_sd_info4oper where id=@foundation_id else insert t_sd_info4oper (id,op_date,op_time,assent_date,is_fixed,reg_date,is_assent) values (@new_id,@transaction_date,@transaction_time,null,1,@transaction_date,1) -- Дата согласия = Дата сделки, Время согласия = Время сделки - 1 час declare @date_time4assent datetime select @date_time4assent=.DATE_NORM(@transaction_date,B) + .TIME_FROM_DATE((dateadd(hh,-1,@transaction_time))) update t_sd_info4oper set is_assent=1, assent_date=@date_time4assent where id=@new_id end select @sid = convert(varchar, @new_id) commit tran