create procedure dbo.%PROC% @sid varchar(30) = null as .BEGIN('N') .CHECK_USER .CHECK_UPDATE .TRANSACTION_SAVE create table #dog_for_calc ( asset_place_id numeric null, dog_date datetime null ) create table #sum2inv ( contract_id numeric null, portfolio_id numeric null, portfolio_sub_id numeric null, contragent_id numeric null, list_sum money null, asset_place_id numeric null, dogovor_id numeric null, money_acc_id numeric null ) declare @org_id numeric, @plan_money_id numeric, @plan_securs_id numeric, @out_method_id numeric, @is_realiz int, @is_p2l int, @is_com_in int, @is_allow_short4stocks int, @is_allow_short4money int, @asset4pereoc_type_id int, @purpose_code int, @dep_acc_id numeric, /*Счет депозита на плане ДС*/ @mess_res varchar(255), @subc_str varchar(255), @curs_id numeric, @curs_date datetime, @cur_plan_id numeric, @cur_com_sum money, @contragent_id numeric, @plan2partner_id numeric, @acc2proc2depozit_id numeric, @subc_str2proc varchar(255), @money_acc_id numeric, @date_bb datetime .GET_PROPS .BACK_GET_ORG_PARMS(@owner_id,@org_id,@plan_money_id,@plan_securs_id,@out_method_id,@is_realiz,@is_p2l,@is_com_in,@is_allow_short4stocks,@is_allow_short4money,@asset4pereoc_type_id) select @cur_plan_id=.CUR2PLAN(@plan_money_id) select @plan2partner_id=.PLAN2PARTNER_ID(@owner_id,@plan_money_id) .ACCID_FROM_OBJ2PLAN(@acc2proc2depozit_id,@purpose_id,@plan_money_id,1,1,'Счет начисленных процентов по депозиту',@mess_res) .ACCID_FROM_CONST2PLAN(@dep_acc_id,'BACK_ACC_DEPOZIT',@plan_money_id,1,1,'Счет депозита',@mess_res) select @subc_str='' .SUBC_STR_ADD(@subc_str,'INVESTORS',null,Y) .SUBC_STR_ADD(@subc_str,'ASSET_PLACES',null,Y) ---.SUBC_STR_ADD(@subc_str,'BANK_ACCOUNT',null,Y) .SUBC_STR_ADD(@subc_str,'INVESTOR2PORTFOLIO',null,Y) .SUBC_STR_ADD(@subc_str,'PORTFOLIO',null,Y) select @date_bb=dateadd(yy,-10,@date_b) .TOTALS_QUERY(@owner_id,@plan_money_id,@date_bb,@date_b,@dep_acc_id,@subc_str,L,N,Y,D,D) select @purpose_code=.PURPOSE_CODE(@purpose_id) -- начисление % по договорам депозита if @purpose_code=120 begin if @is_dogovor=1 insert #dog_for_calc select b.id, d.dogexec_begin_date from tb_contracts d, tb_broker2exchange b where d.id=@contract_id and b.ext_broker_deal=d.id and .ITEMS_EXISTS_BY_TYPE(b.id,'BROKER2EXCHANGE') else insert #dog_for_calc select b.id, d.dogexec_begin_date from tb_contracts d, tb_broker2exchange b where d.dogexec_begin_date <= @date_b and d.dogexec_end_date >= @date_b and d.dog_type_id = 8 and b.ext_broker_deal = d.id and .ITEMS_EXISTS_BY_TYPE(b.id,'BROKER2EXCHANGE') and .ITEMS_EXISTS_BY_TYPE_STATE(d.id,'ORGANIZATION_CONTRACTS','SIGN') declare @inv_sum money, @com_sum money, @inv_id numeric, @asset_id numeric, @contr_date datetime, @dogovor_id numeric, @portf_id numeric, @portf_sub_id numeric, @oper_date datetime, @qty_day_yy int, @qty_day int, @proc_sum money, @p_q money, @p_a_s money select @subc_str2proc='' declare cur2calc cursor for select s1_id, s2_id, s3_id, s4_id, saldo_de, op_date from #tmp_osv for read only open cur2calc fetch cur2calc into @inv_id, @portf_id, @portf_sub_id, @asset_id, @inv_sum, @oper_date while .CURSOR_STATE=0 begin select @dogovor_id = (select ext_broker_deal from tb_broker2exchange where id=@asset_id) select @money_acc_id = (select money_acc_id from tb_contracts where id = @dogovor_id) select @qty_day_yy = qty_day_yy, @oper_date = dogexec_begin_date, @contragent_id = client_id from tb_contracts where id=@dogovor_id select @qty_day = DATEDIFF(day, @oper_date, @date_b) if exists(select 1 from #dog_for_calc where asset_place_id = @asset_id) begin select @contr_date=(select dog_date from #dog_for_calc where asset_place_id=@asset_id) .CALC_COMIS(@inv_sum,@dogovor_id,@date_b,@cur_plan_id,@com_sum,@id,@cur_com_sum,@cur_plan_id,@plan_money_id) declare @com_sum_calc decimal(18,8) select @com_sum_calc = @com_sum select @com_sum=round((convert(float,1.0) * @com_sum / @qty_day_yy),2) * @qty_day .SUBC_STR_ADD(@subc_str2proc,'INVESTOR2PORTFOLIO',@portf_sub_id,Y) .SUBC_STR_ADD(@subc_str2proc,'INVESTORS',@inv_id,Y) .SUBC_STR_ADD(@subc_str2proc,'PORTFOLIO',@portf_id,Y) .SUBC_STR_ADD(@subc_str2proc,'BANK_ACCOUNT',@money_acc_id,Y) .SUBC_STR_ADD(@subc_str2proc,'CONTRAGENTS',@contragent_id,Y) .SUBC_STR_ADD(@subc_str2proc,'ASSET_PLACES',@asset_id,Y) select @proc_sum = 0 .SALDO(@owner_id, @plan_money_id, @date_b, @acc2proc2depozit_id, @subc_str2proc, N, D, @proc_sum, @p_q, @p_a_s) select @com_sum = @com_sum - @proc_sum select @com_sum = isnull(@com_sum,0) --/* !!! -- пока закомментарено, т.к. неправильно работает в этом курсоре -- нужен курсор по корректному набор остатков, в разрезе р.счетов -- надо либо .TOTALS_QUERY с другими параметрами, либо честный селект по проводкам -------------------------------- -- ************** -- alexy 12/08/06 ----------------------------------------------------- -- альтернативный метод расчета (как в спецдепе) -- в интерфейсе ничего не менялось, в т.ч. и возможность выбора вариантов не делался -- поэтому дату начала периода, за который рассчитываем, понимаем как дату последней проводки по начислению % ----------------------------------------------------- declare @last_date datetime select @last_date = ( select .DATE_NORM((max(o.op_date)),B) from t_operations o, t_oper_list ol, t_plans2partner pp where ol.acc_id = @acc2proc2depozit_id and ol.deb_or_cred = 1 and ol.head_id = o.id and .DATE_NORM((o.op_date),B) <= @date_b and o.partner2plan_id = pp.id and pp.plan_id = @plan_money_id and pp.partner_id = @owner_id and exists(select 1 from t_oper_subconto where id = ol.id and item_id = @portf_sub_id) and exists(select 1 from t_oper_subconto where id = ol.id and item_id = @inv_id) and exists(select 1 from t_oper_subconto where id = ol.id and item_id = @portf_id) and exists(select 1 from t_oper_subconto where id = ol.id and item_id = @money_acc_id) and exists(select 1 from t_oper_subconto where id = ol.id and item_id = @contragent_id) and exists(select 1 from t_oper_subconto where id = ol.id and item_id = @asset_id) ) -- стандартный код, его можно убрать в шаблон или отдельную процедуру ------------------ -- параметры на входе declare @calc_sum money -- сумма, от которой считаем , @check_date datetime -- дата расчета (дата окончания периода, за который рассчитываем) , @begin_date datetime -- дата начала депозита , @prev_date datetime -- предыдущая дата от расчетной , @days money -- кол-во дней, за которые считаем , @rate_proc money select @calc_sum = @inv_sum , @check_date = @date_b , @begin_date = @oper_date , @days = datediff(dd, @last_date, @date_b) , @rate_proc = @comission_percent_ac -- эта переменная содержит ставку %, определяется и заполняется в .CALC_COMIS -- расчет declare @div money -- число дней в году , @proc_calc_sum money -- сумма начисляемого % , @start int -- кол-во дней, прошедших от начала депозита до начала периода, за который рассчитываем , @end int -- кол-во дней от начала депозита до даты расчета select @div = datediff(dd,convert(datetime,'01/01/' + convert(varchar,datepart(yy,@check_date))), convert(datetime,'01/01/' + convert(varchar,datepart(yy,@check_date)+1))) , @start = datediff(dd,@begin_date,dateadd(dd,(-1) * @days,@check_date)) , @end = datediff(dd,@begin_date,@check_date) if isnull(@end,0) <= 0 select @end = 0 if isnull(@start,0) <= 0 or @end=0 select @start = 0 -- select @proc_calc_sum = round(((@calc_sum * @rate_proc * @end) * (convert(float,1.0)) / (@div * 100.0)),2) -- - round(((@calc_sum * @rate_proc * @start) * (convert(float,1.0))/(@div * 100.0)),2) .CALC_EXT_DATE(@begin_date, -1, @prev_date) SELECT @end = DATEDIFF(DAY, @begin_date, @prev_date) SELECT @proc_calc_sum = ROUND(@calc_sum * @rate_proc * @end / (@div * 100), 2) --SELECT @proc_calc_sum AS proc_calc_sum, @calc_sum AS calc_sum, @rate_proc AS rate_proc, -- @end AS end1, @start AS start if isnull(@proc_calc_sum,0) <= 0 select @proc_calc_sum = 0 -- стандартный код закончился ------------------------------------------------------------- -- эту строчку необходимо закомментарить, чтобы работало по-старому: select @com_sum = @proc_calc_sum -- /alexy 12/08/06 -- ************** -------------------------------- --*/ insert #sum2inv select @inv_id, @portf_id, @portf_sub_id, @contragent_id, @com_sum, @asset_id, @dogovor_id, @money_acc_id end fetch cur2calc into @inv_id,@portf_id,@portf_sub_id,@asset_id,@inv_sum,@oper_date end close cur2calc .DEALLOCATE cur2calc end -- начисление % -- переоценка валютных счетов if @purpose_code=122 begin .ID_VAR(@plan2partner_money_id) .ID_VAR(@cur_rur_id) -- получение ID типов аналитики .ID_VAR(@st_investors_id) -- Инвестор .ID_VAR(@st_investor2portfolio_id) -- Раздел учета .ID_VAR(@st_portfolio_id) -- Портфель менеджера .ID_VAR(@st_asset_places_id) -- Место нахождения актива .ID_VAR(@st_bank_acc_id) -- расч.счет SELECT @plan2partner_money_id = .PLAN2PARTNER_ID(@owner_id, @plan_money_id) select @cur_rur_id = .CUR('RUR') SELECT @st_investors_id = .SUBCTYPE_FROM_CODE('INVESTORS') SELECT @st_investor2portfolio_id = .SUBCTYPE_FROM_CODE('INVESTOR2PORTFOLIO') SELECT @st_portfolio_id = .SUBCTYPE_FROM_CODE('PORTFOLIO') SELECT @st_asset_places_id = .SUBCTYPE_FROM_CODE('ASSET_PLACES') SELECT @st_bank_acc_id = .SUBCTYPE_FROM_CODE('BANK_ACCOUNT') insert #sum2inv ( contract_id, portfolio_id, portfolio_sub_id, list_sum, asset_place_id, money_acc_id ) select -- Инвестор s1.item_id, -- Портфель менеджера s3.item_id, -- Раздел учета s2.item_id, -- остаток sum(o.saldo_accur * o.deb_or_cred), -- Место нахождения актива s4.item_id, -- расч.счет s5.item_id from t_account_now o, t_bank_accounts b, t_accnow_subconto s1, t_accnow_subconto s2, t_accnow_subconto s3, t_accnow_subconto s4, t_accnow_subconto s5 where o.plan2partner_id = @plan2partner_money_id and o.acc_id in (select id from t_accounts where plan_id = @plan_money_id and is_last = 1 and (type4cur_id = 3 or (type4cur_id = 2 and cur_id <> @cur_rur_id and cur_id is not null)) and acc_num_eff like '2.0.%') and o.id = s1.id and s1.subconto_type_id = @st_investors_id and o.id = s2.id and s2.subconto_type_id = @st_investor2portfolio_id and o.id = s3.id and s3.subconto_type_id = @st_portfolio_id and o.id = s4.id and s4.subconto_type_id = @st_asset_places_id and o.id = s5.id and s5.subconto_type_id = @st_bank_acc_id and (s5.item_id = @bank_acc_id or @bank_acc_id is null) and s5.item_id = b.id and isnull(b.bank_acc_cur_id,@cur_rur_id) <> @cur_rur_id and o.acc_cur_id = b.bank_acc_cur_id group by s1.item_id, s4.item_id, s2.item_id, s3.item_id, s5.item_id having abs(sum(o.saldo_accur * o.deb_or_cred)) > 0 end ----------------------------------- -- формирование записей по остаткам begin tran .UPDATE_STATE .ACTION_HISTORY select @inv_id=null, @portf_id=null, @portf_sub_id=null, @asset_id=null, @inv_sum=null, @contragent_id=null declare cur3calc cursor for select contract_id, portfolio_id, portfolio_sub_id, asset_place_id, sum(list_sum), contragent_id, dogovor_id, money_acc_id from #sum2inv group by contract_id,portfolio_id,portfolio_sub_id,asset_place_id,contragent_id, dogovor_id, money_acc_id for read only open cur3calc fetch cur3calc into @inv_id,@portf_id,@portf_sub_id,@asset_id,@inv_sum,@contragent_id, @dogovor_id, @money_acc_id while .CURSOR_STATE=0 begin .TYPE_INIT('LIST_FOR_MONEY_REDEMPTION',1,N) .TYPE_ASSIGN(contract_id,@inv_id) .TYPE_ASSIGN(item_id,@id) .TYPE_ASSIGN(portfolio_id,@portf_id) .TYPE_ASSIGN(portfolio_sub_id,@portf_sub_id) .TYPE_ASSIGN(contragent_id,@contragent_id) .TYPE_ASSIGN(list_sum,@inv_sum) .TYPE_ASSIGN(asset_place_id,@asset_id) .TYPE_ASSIGN(dog_id,@dogovor_id) .TYPE_ASSIGN(bank_account_id,@money_acc_id) .TYPE_ASSIGN(cur_id,((select bank_acc_cur_id from t_bank_accounts where id = @money_acc_id))) .TYPE_INSERT('LIST_FOR_MONEY_REDEMPTION','CRT',1,N) fetch cur3calc into @inv_id,@portf_id,@portf_sub_id,@asset_id,@inv_sum,@contragent_id, @dogovor_id, @money_acc_id end close cur3calc .DEALLOCATE cur3calc commit tran drop table #sum2inv drop table #dog_for_calc .TRANSACTION_RESTORE .END