Your comments

На данный момент скидки для группы номенклатуры не учитываются. Данный режим сейчас является архитектурным базисом для возможности назначения скидок по группам в будущем.
Откройте SQL Managment Studio, подключитесь к вашему SQL серверу, слева сверху в выпадающем списке выберете вашу базу данных. Нажмите кнопку "New Query" (Создать запрос). В открывшееся окно вставьте код ниже, нажмите F5. Все должно заработать.

ALTER TRIGGER [dbo].[AXI_Attr147_ImportBK] ON [dbo].[Attr147]
--with execute as owner
AFTER INSERT
AS
BEGIN
set nocount on;
IF OBJECT_ID (N'tempdb..#TABLE_AXI_Attr147_ImportBK', N'U') IS not NULL return
delete from ImportTable
declare @TN varchar(256)
,@FP varchar(256)
, @ObjectID int


set @TN = 'ImportTable'


if (select COUNT(*) from inserted i inner join dbo.attr24 a24 on a24.ObjectID = i.ObjectID and a24.ObjectClassID = 147
where Left(p117,11) = 'База данных')>0
begin
raiserror('Не сохраняйте файлы в базе данных!', 16, 1)
rollback
return
end
create table #TABLE_AXI_Attr147_ImportBK(ObjectID int)




DECLARE cursfile cursor local fast_forward for


select i.ObjectID, p117+
P115+
p116 from inserted i inner join dbo.attr24 a24 on a24.ObjectID = i.ObjectID and a24.ObjectClassID = 147
where Left(p117,11) <> 'База данных'
OPEN cursfile
FETCH NEXT FROM cursfile into @ObjectID, @FP
WHILE @@FETCH_STATUS=0
BEGIN






--IF OBJECT_ID (N''+@TN, N'U') IS not NULL exec('drop table '+@TN)


exec spImportClientBank @TableName=@TN,@FilePath=@FP




declare @Table table
(KAID int
,JurID int
,KLID int
,INN varchar(255)
,KPP varchar(255)
)


insert into @Table
(KAID
,JurID
,KLID
,INN
,KPP
)
select
a5.ObjectID as KAID
,a126.ObjectID as JurID
,a98.ObjectID as KLID
,coalesce(a126.p575, a98.p745) as INN
,a126.p576 as KPP
from dbo.Attr5 a5
left outer join dbo.Attr126 a126 on a126.p582 = a5.ObjectID and isnull(a5.p554,0) = 0
left outer join dbo.Attr6 a98 on a98.P357 = a5.ObjectID and ISNULL(a5.p554,0) = 1
--where coalesce(a126.p575, a98.p745) in (select PolINN from ImportTable union select PayerINN from ImportTable)
where a126.p575 in (select PolINN from ImportTable union select PayerINN from ImportTable)
or a98.p745 in (select PolINN from ImportTable union select PayerINN from ImportTable)


declare @TablePR table
(PRID int
,KAID int
,JurID int
,BID int
,rs varchar(255)
,bik varchar(255)
,ks varchar(255)
)
insert into @TablePR
(PRID
,KAID
,JurID
,BID
,rs
,bik
,ks
)
select
a128.ObjectID
,a128.p599 as KAID
,a128.p600 as JurID
,a127.ObjectID as BID
,a128.p593 as rs
,a127.p586 as bik
,a127.p587 as ks
from dbo.Attr128 a128
inner join dbo.attr127 a127 on a127.ObjectID = a128.p594
inner join @Table b0 on b0.KAID = a128.p599




INSERT INTO [dbo].[Attr148]
([ObjectClassID]
,[P770]--номер
,[p1879]--дата
,[P1880]--сумма
,[P1881]--назначение платежа
,[P1882]--плательщик
,[P1883]--плательщик ИНН
,[P1884]--плательщик счет
,[P1885]--плательщик КПП
,[P1886]--плательщик контрагент (ссылка)
,[P1887]--плательщик юр.лицо (ссылка)
,[P1888]--плательщик - контактное лицо (ссылка)
,[P1889]--плательщик-платежные реквизиты (ссылка)
,[P1890]--Получатель КПП
,[P1891]--показатель КБК
,[P1892]--ОКАТО
,[P1893]--Показатель основания
,[P1894]--показатель периода
,[P1895]--показатель номера
,[P1896]--показатель даты
,[P1921]--показатель типа
,[P1897]--плательщик банк
,[P1898]--плательщик-банк (ссылка)
,[P1899]--Плательщик корсчет
,[P1900]--получатель
,[P1901]--получатель инн
,[P1902]--получатель счет
,[P1903]--получатель-контрагент (ссылка)
,[P1904]--получатель - юр.лицо (ссылка)
,[P1905]--получатель - Контактное лицо (ссылка)
,[P1906]--получатель - платежные реквизиты (ссылка)
,[P1907]--вид оплаты
,[P1908]--срок платежа
,[P1909]--вид платежа
,[P1910]--дата поступило
,[P1911]--получатель банк
,[P1912]--получатель бик
,[P1913]--получатель корсчет
,[P1914]--получатель банк (ссылка)
,[P1916]--касса-счет
,[P1915]--направление платежа
,p3429--файл
,P3422 --касса-счет получатель (для переносов)
)
SELECT
148
,Number--номер
,cast(
dateadd(yyyy, cast(right([Date],4) as int)-1900,
dateadd(mm, cast(left(right([Date], LEN([Date])-3),2) as int)-1 ,
dateadd(d, cast(left([Date],2) as int) , cast(-1 as datetime))))
as datetime)--дата
,cast([SUM] as decimal(15,2))--сумма
,PaymentFunction--назначение платежа
,Payer1--плательщик
,PayerINN--плательщик ИНН
,PayerAccount--плательщик счет
,PayerKPP--плательщик КПП
,Plat.KAID--плательщик контрагент (ссылка)
,Plat.JurID--плательщик юр.лицо (ссылка)
,Plat.KLID--плательщик - контактное лицо (ссылка)
,PlatPR.PRID--плательщик-платежные реквизиты (ссылка)
,RecipientKPP--Получатель КПП
,KBK--показатель КБК
,OKATO--ОКАТО
,PokazOsn--Показатель основания
,PokazPeriod--показатель периода
,PokazNumber--показатель номера
,PokazDate--показатель даты
,PokazType--показатель типа
,PlatBank1--плательщик банк
,PlatPR.BID--плательщик-банк (ссылка)
,PlanCorr--Плательщик корсчет
,Pol1--получатель
,PolINN--получатель инн
,PolAcc--получатель счет
,Pol.KAID--получатель-контрагент (ссылка)
,Pol.JurID--получатель - юр.лицо (ссылка)
,Pol.KLID--получатель - Контактное лицо (ссылка)
,PolPR.PRID--получатель - платежные реквизиты (ссылка)
,VidOplaty--вид оплаты
,cast(
dateadd(yyyy, cast(right(SrokPlatezha,4) as int)-1900,
dateadd(mm, cast(left(right(SrokPlatezha, LEN(SrokPlatezha)-3),2) as int)-1 ,
dateadd(d, cast(left(SrokPlatezha,2) as int) , cast(-1 as datetime))))
as datetime)--срок платежа
,VidPlatezha--вид платежа
,cast(
dateadd(yyyy, cast(right(DataPostupilo,4) as int)-1900,
dateadd(mm, cast(left(right(DataPostupilo, LEN(DataPostupilo)-3),2) as int)-1 ,
dateadd(d, cast(left(DataPostupilo,2) as int) , cast(-1 as datetime))))
as datetime)--дата поступило
,PolBank1--получатель банк
,PolBIK--получатель бик
,PolCorr--получатель корсчет
,PolPR.BID--получатель банк (ссылка)
--касса-счет
,case
when a5plat.ObjectClassID = 29 then (Select a186.ObjectID from dbo.attr186 a186 where a186.p1160 = PlatPR.PRID)
when a5pol.ObjectClassID = 29 then (Select a186.ObjectID from dbo.attr186 a186 where a186.p1160 = PolPR.PRID)
end
,case when a5plat.ObjectClassID = 29 and a5pol.ObjectClassID = 29 then 'Перенос'
when a5plat.ObjectClassID = 29 then 'Расход'
else 'Приход'
end

,@ObjectID

, case
when a5plat.ObjectClassID = 29 and a5pol.ObjectClassID = 29 then (Select a186.ObjectID from dbo.attr186 a186 where a186.p1160 = PolPR.PRID)
end


from ImportTable it
left outer join (@Table Plat
left outer join dbo.Attr5 a5plat on a5plat.ObjectID = Plat.KAID)

on Plat.INN = it.PayerINN

and isnull(Plat.KPP,'') = case

a5plat.ObjectClassID

when 29 then isnull(nullif(it.PayerKPP,0),'')

else isnull(nullif(Plat.KPP,0),'')

end
left outer join (@Table Pol
left outer join dbo.Attr5 a5pol on a5pol.ObjectID = Pol.KAID)

on Pol.INN = it.PolINN

and isnull(Pol.KPP,'') = case

a5pol.ObjectClassID

when 29 then isnull(nullif(it.RecipientKPP,0),'')

else isnull(nullif(Pol.KPP,0),'')

end
left outer join @TablePR PlatPR on PlatPR.rs = it.PayerAccount and Plat.KAID = PlatPR.KAID
left outer join @TablePR PolPR on PolPR.rs = it.PolAcc and Pol.KAID = PolPR.KAID


delete from ImportTable
FETCH NEXT FROM cursfile into @ObjectID, @FP
END


CLOSE cursfile
DEALLOCATE cursfile


drop table #TABLE_AXI_Attr147_ImportBK
END
попробуйте сохранить куда-нибудь весь скрипт с карточки и полностью заменить его этим





public BaseCurrency


dim konst_vip


Sub ZnachKonst_vip (sender)


' значение константы 41. 03. VBS действия кнопка "Выполнить""
datknVip = this("datknVip")


if not isObject(datknVip) then
datknVip = this.create("TX2Query", this, "datknVip")
end if


with datknVip
.ClassName = "Константы"
.Connector = this ("X2Connector1")
.SelectString = "p343 AS [конст41]"
.WhereString = "ObjectID = " + CStr(41)
.Refresh
konst_vip = .ValueByFieldName("конст41")
.Free
end with


if isnull(konst_vip) then
konst_vip = 1
end if


End Sub




sub CanSave(act)
'''''''''''ВСЕ ЧТО ПРОИСХОДИТ ПОСЛЕ СОХРАНЕНИЯ КАРТОЧКИ ВНОСИТЬ СЮДА
dim err
err = 0
'дальше идут проверки, если по проверке не проходит, ставим err = 1
dim NewCard
NewCard = 0


if err = 0 then


if isnull(this("BookQuery").ValueByFieldName("ID_")) then
NewCard = 1
end if
this("SaveAction").Execute
VisibleButton
foto
if not IsObject(this("datCountTask")) then
datCountTask = this.create("TX2Query", this, "datCountTask")
end if
with this("datCountTask")
.ClassName ="Задачи"
.Connector = this ("X2Connector1")
.SelectString = "count(*) as [Количество] "
.WhereString = "p846 = "+cstr(this("BookQuery").ValueByFieldName("ID_"))
end with


this ("datCountTask").refresh
dim kolZ
kolZ = this("datCountTask").ValueByFieldName("Количество")
this("datCountTask").free
if isnull(kolZ) then
kolZ = 0
end if
'Вопрос о создании задачи
if not IsObject(this("datSistKonst")) then
datSistKonst = this.create("TX2Query", this, "datSistKonst")
end if
with this("datSistKonst")
.ClassName ="Константы"
.Connector = this ("X2Connector1")
.SelectString = "p343 as [Значение] "
.WhereString = "ObjectID= 2"
end with


this ("datSistKonst").refresh
dim konst
konst = this("datSistKonst").ValueByFieldName("Значение")
this("datSistKonst").free
if not isnull(this("BookQuery").ValueByFieldName("ID_Место работы")) then
if kolZ = 0 and konst = 1 then
' kontMes = msgbox("Создать задачу по контактному лицу?", vbYesNo)
' if kontMes = 6 then 'да
kontMes = MsgDialog ("Создать задачу по контактному лицу?","C","YesNo")
if kontMes = vbYes then


CreateTask
end if
end if
if konst = 2 then
if not IsObject(this("datCountProd")) then
datCountProd = this.create("TX2Query", this, "datCountProd")
end if
with this("datCountProd")
.ClassName ="Продажи"
.Connector = this ("X2Connector1")
.SelectString = "count(*) as [Количество] "
.WhereString = "p868 = "+cstr(this("BookQuery").ValueByFieldName("ID_"))
end with


this("datCountProd").refresh
dim kolProd
kolProd = this("datCountProd").ValueByFieldName("Количество")
this("datCountProd").free
if isnull(kolProd) then
kolProd = 0
end if
if kolProd = 0 then
' kontMes = msgbox("Создать продажу по контактному лицу?", vbYesNo)
' if kontMes = 6 then 'да
kontMes = MsgDialog ("Создать продажу по контактному лицу?","C","YesNo")
if kontMes = vbYes then


CreateProdazha
end if
end if
end if
end if
VisibleButton
if act = "SaveClose" then
this("OkAction").Execute
end if
end if
end sub






sub VisibleButton()
if isnull(this("BookQuery").ValueByFieldName("ID_")) then
' this("keyPanel").enabled = false
this("keyPanelBottom").enabled = false
else
' this("keyPanel").enabled = true
this("keyPanelBottom").enabled = true
end if
this("KeyButtonVip").Enabled =this("KeyButtonVip").Parent.Enabled
this("Ref").Enabled =this("Ref").Parent.Enabled
' this("KeyButtonNapom").Enabled =this("KeyButtonNapom").Parent.Enabled
' this("keybuttonTask").Enabled =this("keybuttonTask").Parent.Enabled






end sub


public function GetCurrUserRef()
If not IsObject(this("datCurrUser")) Then
datCurrUser = this.create ("TX2Query",this,"datCurrUser")
end if


with this("datCurrUser")
.ClassName ="Сотрудники"
.Connector = this ("X2Connector1")
.SelectString = "top 1 dbo.F_GetCurrUserRef() as [ТП]"


end with


this ("datCurrUser").refresh
GetCurrUserRef =this ("datCurrUser").ValueByFieldName("ТП")
this ("datCurrUser").free


end function


sub FOTO()
if isnull(this("BookQuery").ValueByFieldName("ID_Фото")) then


' создаем надпись ФОТО нет
If not IsObject(this("Label3")) Then
Label3 = this.Create("TcxLabel", this, "Label3")


With Label3
.Parent = this("pagecontrol1TS1016") ' this("TabSheet0")
.Caption = "Фото НЕТ"
With .style
' .TextStyle = "fsbold" ' жирный
' .Textcolor = RGB (0,128,225)'(66,66,225)
' .font.size = 10
End With
.top = 163
.left = 5
.visible = true
.transparent = true
End With
end if


If IsObject(this("Label32")) Then
this ("Label32").visible = false
end if


If IsObject(this("Label3")) Then
this ("Label3").visible = true
end if


else
' создаем надпись ЕСТЬ фото
If not IsObject(this("Label32")) Then
Label32 = this.Create("TcxLabel", this, "Label32")


With Label32
.Parent = this("pagecontrol1TS1016") ' this("TabSheet0")
.Caption = "ЕСТЬ фото"
With .style
.TextStyle = "fsbold" ' жирный
.Textcolor = RGB (0,128,225)'(66,66,225)
' .font.size = 10
End With
.top = 163
.left = 5
.visible = false
.transparent = true
End With
end if


If IsObject(this("Label3")) Then
this ("Label3").visible = false
end if


If IsObject(this("Label32")) Then
this ("Label32").visible = true
end if


end if
end sub


sub GetKAtel ()
if not isnull (this("BookQuery").ValueByFieldName ("ID_Место работы")) then
if not isObject(this("datKA")) then
datKA = this.create("TX2Query", this, "datKA")
end if
with this("datKA")
.ClassName = "Контрагенты"
.Connector = this ("X2Connector1")
.SelectString = "coalesce(p26, p666) AS [номер]"
.WhereString = "ObjectID="+CStr(this ("BookQuery").ValueByFieldName("ID_Место работы"))
end with


this ("datKA").refresh
call this("BookQuery").ValueByFieldName ("Рабочий телефон", this ("datKA").ValueByFieldName("номер"))
this ("datKA").free
end if


end sub


sub GetVosn()
dim v
if not isnull (this("BookQuery").ValueByFieldName ("ID_Место работы")) then
v=this("BookQuery").ValueByFieldName ("ID_Место работы")
id = this("BookQuery").ValueByFieldName("ID_")
if isnull(ID) then id = 0
if not isObject(this("datCountKL")) then
datCountKL = this.create("TX2Query", this, "datCountKL")
end if
'при создании карточки подставляет телефон из контрагента, если у контрагента телефон не указан, поставит пустую строку
with this("datCountKL")
.ClassName = "Контактные лица"
.Connector = this ("X2Connector1")
.SelectString = "COUNT(*) AS [Колво]"
.WhereString = "p357 = " + CStr(v) +" and ObjectID <> "+cstr(id)
.refresh
kol =.ValueByFieldName("Колво")
.free
end with


if kol = 0 then
call this("BookQuery").ValueByFieldName ("Основной контакт", 1)
else
if isnull(id) then
call this("BookQuery").ValueByFieldName ("Основной контакт", 0)
end if
end if


end if


end sub




public function GetSystParam(ObjID)
if not isnull(ObjID) then
If not IsObject(this("datSist")) Then
datSist = this.create ("TX2Query",this,"datSist")
end if


with this("datSist")
.ClassName ="Константы"
.Connector = this ("X2Connector1")
.SelectString = " cast(p343 as int) as [Значение]"
.WhereString = " ObjectID = "+cstr(ObjID)
end with


this ("datSist").refresh
GetSystParam = this("datSist").ValueByFieldName("Значение")
this ("datSist").free
end if
end function




public function GetBaseCurrency()
if not isObject(this("datBaseCurr")) then
datBaseCurr = this.create("TX2Query", this, "datBaseCurr")
end if
with this("datBaseCurr")
.ClassName = "Валюты"
.Connector = this("X2Connector1")
.SelectString = "ObjectID as [ID_]"
.WhereString = "p526 = 1"
end with


this("datBaseCurr").refresh
GetBaseCurrency =this("datBaseCurr").ValueByFieldName("ID_")
this("datBaseCurr").free


end function








sub FillFLnameRP(Sender)
call this("BookQuery").ValueByFieldName("Должность в род.п.",this("BookQuery").ValueByFieldName("Должность"))
call this("BookQuery").ValueByFieldName("Действует на основании", "Устава")
if isnull(this("BookQuery").ValueByFieldName("ID_Пол")) then
' Msgbox("Не заполнен пол физического лица!")
MsgDialog "Не заполнен пол физического лица!", "I"
end if
if not isnull(this("BookQuery").ValueByFieldName("ID_Пол")) then




dim Tp ' пол 1 - м, 2 - ж
dim Typ ' падеж Родительный Р или 2
dim Dlm ' разделитель " "


dim f
dim n
dim s
f= this ("BookQuery").ValueByFieldName ("Фамилия")
n= this ("BookQuery").ValueByFieldName ("Имя")
s= this ("BookQuery").ValueByFieldName ("Отчество")
if isnull(f) then
f=""
end if
if isnull(n) then
n=""
end if
if isnull(s) then
s=""
end if


dim fam
dim name
dim otch
' для мужчин
if this("BookQuery").ValueByFieldName ("ID_Пол") = 1 then


' фамилии
select case right(f,2)
case "ин"
fam = f +"a"
case "ын"
fam = f +"a"
case "як"
fam = f +"a"
case "ев"
fam = f +"a"
case "ов"
fam = f +"a"
case "ич"
fam = f +"a"
case "ий"
fam = left(f,(len(f)-2)) + "ого"
case else
fam = f
end select


call this("BookQuery").ValueByFieldName ("Фамилия в род.п.", fam )


' имена
select case right(n,1)
case "й"
name = left(n,(len(n)-1)) + "я"
case "р"
name =n + "а"
case "н"
name =n + "а"
case "с"
name =n + "а"
case "л"
name =n + "а"
case "и"
name =n + "а"
case "в"
name =n + "а"
case "д"
name =n + "а"
case "г"
name =n + "а"
case "я"
name = left(n,(len(n)-1)) + "ю"
case "ь"
name = left(n,(len(n)-1)) + "я"
case else
name = n
end select
call this("BookQuery").ValueByFieldName ("Имя в род.п.", name )




' отчество
select case right(s,1)
case "ч"
otch = s + "а"
case else
otch = s
end select
call this("BookQuery").ValueByFieldName ("Отчество в род.п.", otch )
end if




' для женщин
if this("BookQuery").ValueByFieldName ("ID_Пол") = 2 then


' для фамилии
select case right(f,2)
case "на"
fam = left(f,(len(f)-1)) + "ой"
case "ва"
fam = left(f,(len(f)-1)) + "ой"
case "ая"
fam = left(f,(len(f)-2)) + "ой"
case else
fam = f
end select


call this("BookQuery").ValueByFieldName ("Фамилия в род.п.", fam )


' для имени
select case right(n,1)
case "а"
if right(n,2) = "га" or right(n,2) = "ка" then
name = left(n,(len(n)-1)) + "и"
else
name = left(n,(len(n)-1)) + "ы"
end if
case "я"
name = left(n,(len(n)-1)) + "и"
case "ь"
name = left(n,(len(n)-1)) + "и"
case else
name = n
end select
call this("BookQuery").ValueByFieldName ("Имя в род.п.", name )






' для отчества
select case right(s,1)
case "а"
otch = left(s, len(s)-1) + "ы"
case else
otch = s
end select
call this("BookQuery").ValueByFieldName ("Отчество в род.п.", otch )


end if
end if




end sub




Sub FillObrashenie (Sender)
'if isnull (this("BookQuery").ValueByFieldName ("Обращение")) then
if this ("BookQuery").ValueByFieldName("ID_Пол") = "1" then
call this("BookQuery").ValueByFieldName ("Обращение", "Уважаемый")
end if


if this ("BookQuery").ValueByFieldName("ID_Пол") = "2" then
call this("BookQuery").ValueByFieldName ("Обращение", "Уважаемая")
end if






'end if
end sub


''''''''''''''''''ФУНКЦИИ ДЛЯ КНОПОК
sub CreateNapom ()
if isnull (this("BookQuery").ValueByFieldName ("ID_")) then
'msgbox "Для создания напоминания необходимо сохранить объект!", 48, "Создание напоминания"
MsgDialog "Для создания напоминания необходимо сохранить объект!", "I"
else ' карточка объекта сохранена
' для открытия карточки напоминания
If not IsObject(this("datNapom")) Then
datNapom = this.create ("TX2Query",this,"datNapom")
end if


with this("datNapom")
.ClassName ="Напоминания"
.Connector = this ("X2Connector1")
.WhereString = "p1057 = "+cstr(this("BookQuery").ValueByFieldName ("ID_"))
end with


this ("datNapom").openempty
' проверяем есть ли напоминания на этот объект на этого сотрудника
this ("datNapom").append
If not IsObject(this("dat22Napom")) Then
dat22Napom = this.create ("TX2Query",this,"dat22Napom")
end if
with this("dat22Napom")
.ClassName = "Напоминания"
.Connector = this ("X2Connector1")
.SelectString = "top 1 (SELECT count(*) FROM Class172 where Class172.p1057="+CStr(this ("BookQuery").ValueByFieldName("ID_"))+" and class172.p1046= dbo.F_GetCurrUserRef() ) AS [кол-во напом], (SELECT ObjectID FROM Class172 where Class172.p1057="+CStr(this ("BookQuery").ValueByFieldName("ID_"))+" and class172.p1046= dbo.F_GetCurrUserRef() ) AS [ID_]"
end with
' this ("SaveAction").Execute


this ("dat22Napom").refresh
' this ("dat22Napom").last


if isnull ( this("dat22Napom").ValueByFieldName("кол-во напом") ) then
dim kn
kn = 0
else
kn = this("dat22Napom").ValueByFieldName("кол-во напом")
end if


' msgbox kn


if kn = 0 then
'открываем пустую карточку
call this ("datNapom").ValueByFieldName ("ID_Контактное лицо",this("BookQuery").ValueByFieldName("ID_"))
call this ("datNapom").ValueByFieldName ("Дата",dateadd("n",60,date+time))
this ("datNapom").post


ff = this ("datNapom").ValueByFieldName ("ID_")
this("datNapom").OpenModalCard(ff)


else


ff2 = this ("dat22Napom").ValueByFieldName ("ID_")
this("datNapom").OpenModalCard(ff2)
end if
this("datNapom").free
this("dat22Napom").free
end if
end sub






sub CreateTask()


if not isnull(this("BookQuery").ValueByFieldName("ID_")) then


if not isnull (this("BookQuery").ValueByFieldName("ID_Место работы")) then




IF NOT ISOBJECT (THIS("datKonstDlitZad")) THEN
datKonstDlitZad = this.create ("TX2Query",this,"datKonstDlitZad")
end if
with this("datKonstDlitZad")
.ClassName = "Константы"
.Connector = this("X2Connector1")
.SelectString = " p343 AS [Длительность]"
.WhereString = "ObjectID = 39"
.refresh
KonstDlitZad =.ValueByFieldName("Длительность")
.Free
end with


if isnull(KonstDlitZad) then
KonstDlitZad = 15
else
KonstDlitZad = KonstDlitZad
end if


' для открытия карточки Задачи
If not IsObject(this("datCrTask")) Then
datCrTask = this.create ("TX2Query",this,"datCrTask")
end if


with this("datCrTask")
.ClassName ="Задачи"
.Connector = this ("X2Connector1")
.WhereString = "p846 = "+cstr(this("BookQuery").ValueByFieldName("ID_"))
end with


this ("datCrTask").openempty
cur = GetCurrUserRef()
this("datCrTask").append
call this("datCrTask").ValueByFieldName("Наименование", " ")
call this("datCrTask").ValueByFieldName("ID_Контрагент", this("BookQuery").ValueByFieldName("ID_Место работы"))
call this("datCrTask").ValueByFieldName("ID_Состояние", 35)
call this("datCrTask").ValueByFieldName("ID_Тип", 38)
call this("datCrTask").ValueByFieldName("ID_Контактное лицо контрагента", this("BookQuery").ValueByFieldName("ID_"))
call this("datCrTask").ValueByFieldName("Дата начала (план)", dateadd("h", 1 , date()+time()))
call this("datCrTask").ValueByFieldName("Дата окончания (план)", dateadd("n", cint(KonstDlitZad), dateadd("h", 1 , date()+time())))
call this("datCrTask").ValueByFieldName("ID_Единица измерения времени", 22)
call this("datCrTask").ValueByFieldName("Длительность (план)", cstr(KonstDlitZad))
call this("datCrTask").ValueByFieldName("ID_Автор", cur)
call this("datCrTask").ValueByFieldName("ID_Исполнитель", cur)
call this("datCrTask").ValueByFieldName("Дата напоминания (исполнитель)",Dateadd("n", 45, date()+time()))


this("datCrTask").post
TaskID = this("datCrTask").ValueByFieldName("ID_")
this("datCrTask").OpenModalCard(TaskID)
this ("datCrTask").free
else
' msgbox "У контактного лица не указано место работы!Создание задачи невозможно!", 64, "Создание задачи по контактному лицу"
MsgDialog "У контактного лица не указано место работы!Создание задачи невозможно!", "I"
end if


end if


end sub


sub CreateProdazha()
' для создания продажи
dim cur
dim rs
dim rsID
dim typeID
cur = GetCurrUserRef()
rs = GetSystParam(10)
BaseCurrency = GetBaseCurrency()
select case rs
case 1
rsID = 158 'по продуктам
case 2
rsID = 159 'по планам оплат
case 3
rsID = 176 'по счетам
case 4
rsID = 160 'ручной ввод
end select


if not isnull (this("BookQuery").ValueByFieldName("ID_Место работы")) then


If not IsObject(this("datProdazha")) Then
datProdazha = this.create ("TX2Query",this,"datProdazha")
end if


with this("datProdazha")
.ClassName ="Продажи"
.Connector = this ("X2Connector1")
.WhereString = "p867 = "+cstr(this("BookQuery").ValueByFieldName("ID_Место работы"))
end with
this("datProdazha").openempty
this ("datProdazha").append
call this("datProdazha").ValueByFieldName("Дата запуска", date())
call this("datProdazha").ValueByFieldName("ID_Контрагент", this("BookQuery").ValueByFieldName("ID_Место работы"))
call this("datProdazha").ValueByFieldName("ID_Контактное лицо", this("BookQuery").ValueByFieldName("ID_"))


call this("datProdazha").ValueByFieldName("ID_Валюта", BaseCurrency)
call this("datProdazha").ValueByFieldName("Курс", 1)
call this("datProdazha").ValueByFieldName("Наименование", " ")
call this("datProdazha").ValueByFieldName("ID_Ответственный", cur)
call this("datProdazha").ValueByFieldName("ID_Состояние", 14)


'Тип продажи по умолчанию
typeID = GetSystParam(13)
call this("datProdazha").ValueByFieldName("ID_Расчет суммы", rsID)
call this("datProdazha").ValueByFieldName("ID_Тип", typeID)
if not isObject(this("datStage")) then
datStage = this.create("TX2Query", this, "datStage")
end if
with this("datStage")
.ClassName = "Продажи. Стадии"
.Connector = this("X2Connector1")
.SelectString = "top 1 ObjectID as [ID_Стадия], p816 as [ID_Состояние]"
.WhereString = "p815 = "+cstr(typeID) +" order by p813 asc"
end with


this("datStage").refresh
dim stat
dim stage
stat = this("datStage").ValueByFieldName("ID_Состояние")
stage = this("datStage").ValueByFieldName("ID_Стадия")
this("datStage").free
call this("datProdazha").ValueByFieldName("ID_Стадия", stage)
call this("datProdazha").ValueByFieldName("ID_Состояние", stat)
this ("datProdazha").post
ProdazhaCard =this ("datProdazha").ValueByFieldName("ID_")
this ("datProdazha").OpenModalCard(ProdazhaCard)
this ("datProdazha").free
else
' msgbox "У контактного лица не указано место работы!Создание продажи невозможно!", 64, "Создание продажи по контактному лицу"
MsgDialog "У контактного лица не указано место работы!Создание продажи невозможно!", "I"
end if


end sub






'''''''''''''''''''''ОБРАБОТЧИКИ НА КНОПКИ
sub ClickVip(Sender)


ZnachKonst_vip (this)


dim r
r = this("Ref").Text


if konst_vip = 1 then
if r = "Выберите действие из списка:" then
'msgbox("Выберите действие!")
MsgDialog "Выберите действие!", "I"
end if
end if




if r = "Напомнить" then
CreateNapom()
end if
if r = "Назначить задачу" then
CreateTask
end if
if r = "Начать продажу" then
CreateProdazha
end if
this("ref").Text = "Выберите действие из списка:"
end sub












sub SaveCloseCard(Sender) 'Сохранить и закрыть
CanSave "SaveClose"
end sub


sub SaveCard(Sender) 'Сохранить
CanSave "Save"
end sub
'''''''''''''''''ОКОНЧАНИЕ НАЖАТИЕ НА КНОПКИ


sub ChangeKA(sender)
call this("BookQuery").ValueByFieldName("Рабочий телефон", null)
GetKAtel
GetVosn
end sub






'''''''''''''''''''ОТКРЫТИЕ КАРТОЧКИ'''''''''''''''''
Sub Main()


ZnachKonst_vip (this)


if isnull(this("BookQuery").ValueByFieldName("Рабочий телефон"))then
GetKAtel
end if
GetVosn
BaseCurrency = GetBaseCurrency()
''''''''''''''''''Кнопка "Заполнить"
if not isObject(this("keyFLnameRP")) then
keyFLnameRP = this.create("TButton", this, "keyFLnameRP")
end if
with this("keyFLnameRP")
.Parent = this("PageControl1TS1017")
.top = 111
.left = 500
.Caption = "Заполнить"
.OnClick = "FillFLnameRP"
.visible = true
end with




'''''''''''''''''Обработчики событий
this("BookQuery").FieldByName("ID_Пол").OnValidate = "FillObrashenie" 'Пол КЛ.
this("tbOKButton").OnClick = "SaveCloseCard" 'Сохранить и закрыть
this("tbSaveButton").OnClick = "SaveCard" 'Сохранить
this("BookQuery").FieldByName("ID_Место работы").OnValidate = "ChangeKA" 'Пол КЛ.










''''''''''''''НИЖНЯЯ ПАНЕЛЬ для кнопок
keyPanelBottom = this("keyPanelBottom")


if not isObject(keyPanelBottom) then
keyPanelBottom = this.create("TCPanel", this, "keyPanelBottom")
with keyPanelBottom
.Parent = this("gbNames")
.Caption = ""
.Align = "alBottom"
.height = 32
.BorderWidth = 0
end with
end if


' кнопка Выполнить
keybuttonVip=THIS("keybuttonVip")


keyPanelBox = this("keyPanelBox")


if not isObject(keyPanelBox) then
keyPanelBox = this.create("TCPanel", this, "keyPanelBox")
with keyPanelBox
.Caption = ""
.width = 360
.Align = "alRight"
.BorderWidth = 0
.Parent = keyPanelBottom
end with
end if


IF NOT ISOBJECT(keybuttonVip) THEN
keybuttonVip = this.Create("TcxButton", this, "keybuttonVip")
With keybuttonVip
.Caption = "Выполнить"
.width = 100
.height = 25
.OnClick = "ClickVip"
.Align = "alRight"
.Parent = keyPanelBox


if konst_vip = 0 then
.visible = false
else
.visible = true
end if


End With
end if


ref = this("ref")
if not IsObject(ref) then
ref = this.create ("TcxComboBox",this,"ref")
with ref
.Parent = keyPanelBox
.width = 250
.height = 25
.top = 3
.left = 0


if konst_vip = 0 then
.OnClick = "ClickVip"
.Align = "alRight"
end if


with .Properties
.DropDownRows = 17
.DropDownListStyle = "lsFixedList" 'Нередактируемый стиль
.Items.Add = "Выберите действие из списка:"
.Items.Add = "Напомнить"
.Items.Add = "Назначить задачу"
.Items.Add = "Начать продажу"
end with
.ItemIndex = 0 'Выбираем первый эелемент
end with
end if






VisibleButton


this ("lab10161645").visible = false ' фото
this ("ref10161645").visible = false


foto


if not isnull (this("BookQuery").ValueByFieldName ("ID_Место работы")) then
if not isObject(this("datKA")) then
datKA = this.create("TX2Query", this, "datKA")
end if
with this("datKA")
.ClassName = "Контрагенты"
.Connector = this ("X2Connector1")
.SelectString = "isnull(p554,0) AS [физЛ]"
.WhereString = "ObjectID="+CStr(this ("BookQuery").ValueByFieldName("ID_Место работы"))
end with


this ("datKA").refresh
kll = this ("datKA").ValueByFieldName("физЛ")


if isnull(kll) or kll = "ЛОЖЬ" or kll = false then
kll = 0
else
kll = 1
end if
this ("datKA").free


if kll = 1 then
this("attr969726").enabled = false
else
this("attr969726").enabled = true
end if
end if




End Sub
Вы открыли VBS на режиме. А нужно на карточке "Контактные лица". Т.е. войти на ражим и открыть какое-либо контактное лицо
Хорошо,  как проверите, обязательно напишите ответ 
Нужно поправить VBS на карточке. Для этого нужно зайти в КлиК под пользователем SA, открыть карточку "контактные лица". Нажать СTRL + T затем CTRL + E.
Найти в коде следующий текст: 

sub GetVosn
dim v
if not isnull (this("BookQuery").ValueByFieldName ("ID_Место работы")) then
v=this("BookQuery").ValueByFieldName ("ID_Место работы")
id = this("BookQuery").ValueByFieldName("ID_")
if isnull(ID) then id = 0
if not isObject(this("datCountKL")) then
datCountKL = this.create("TX2Query", this, "datCountKL")
end if
'при создании карточки подставляет телефон из контрагента, если у контрагента телефон не указан, поставит пустую строку
with this("datCountKL")
.ClassName = "Контактные лица"
.Connector = this ("X2Connector1")
.SelectString = "COUNT(*) AS [Колво]"
.WhereString = "p357 = " + CStr(v) +" and ObjectID <> "+cstr(id)
.refresh
kol =.ValueByFieldName("Колво")
.free
end with
if kol = 0 then
call this("BookQuery").ValueByFieldName ("Основной контакт", 1)
else
call this("BookQuery").ValueByFieldName ("Основной контакт", 0)
end if


end if


end sub


заменить его следующим текстом

sub GetVosn
dim v
if not isnull (this("BookQuery").ValueByFieldName ("ID_Место работы")) then
v=this("BookQuery").ValueByFieldName ("ID_Место работы")
id = this("BookQuery").ValueByFieldName("ID_")
if isnull(ID) then id = 0
if not isObject(this("datCountKL")) then
datCountKL = this.create("TX2Query", this, "datCountKL")
end if
'при создании карточки подставляет телефон из контрагента, если у контрагента телефон не указан, поставит пустую строку
with this("datCountKL")
.ClassName = "Контактные лица"
.Connector = this ("X2Connector1")
.SelectString = "COUNT(*) AS [Колво]"
.WhereString = "p357 = " + CStr(v) +" and ObjectID <> "+cstr(id)
.refresh
kol =.ValueByFieldName("Колво")
.free
end with
if kol = 0 then
call this("BookQuery").ValueByFieldName ("Основной контакт", 1)
else
if isnull(id) then
call this("BookQuery").ValueByFieldName ("Основной контакт", 0)
end if
end if
end if
end sub


нажать F4
Здравствуйте. Поле сумма всех продаж считается в процедуре, которая вызывается действием "пересчитать аналитики"
к SQL нужно будет точно подключаться.
Уточните пожалуйста скайп, очень много там пользователей Alexandr Selivanov