adPlanList.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import { useAjax } from '@/Hook/useAjax'
  2. import { Col, Row, message, Space, Button, Table, Statistic } from 'antd'
  3. import React, { useEffect, useCallback, useState, useRef } from 'react'
  4. import { getPutUserApi, delUserTagApi } from '@/services/launchAdq/adq'
  5. import { LineChartOutlined, PauseCircleOutlined, PlayCircleOutlined, TransactionOutlined } from '@ant-design/icons'
  6. import { planAdConfig } from './config'
  7. import '../../launchSystemNew/adq/ad/index.less'
  8. import tablePlanConfig from './tablePlanListConfig'
  9. import { AdListProps, getAdV3ListApi } from '@/services/adMonitor/adMonitor'
  10. import FilterQuery from './FilterQuery'
  11. import AdExpandedRowRender from './adExpandedRowRender'
  12. import { useSize, useUpdateEffect } from 'ahooks'
  13. import PlanTag from '../../launchSystemNew/adq/ad/planTag'
  14. import moment from 'moment'
  15. import ColumnTrend from '@/pages/adMonitor/adMonitorList/columnTrend'
  16. import TableData from '../../launchSystemNew/components/TableData'
  17. import RuleAccountLog from '@/components/EarlyWarning/ruleAccountLog'
  18. import Details from './Details'
  19. import { modifyStatusBatchApi, syncBatchApi } from '@/services/launchAdq/adqv3'
  20. import UpdateAd from '../adqv3/ad/updateAd'
  21. import SaveSearch from './SaveSearch'
  22. const AdPlanList: React.FC<{ userId: string }> = (props) => {
  23. /***********************/
  24. const refF = useRef(null)
  25. const { userId } = props
  26. const [selectedRows, setSelectedRows] = useState<any[]>([])
  27. const [detailShow, setDetailShow] = useState<boolean>(false)
  28. const [detailData, setDetailData] = useState<any>({})
  29. const [update, setUpdate] = useState<{ visible: boolean }>({ visible: false })
  30. const [queryForm, setQueryForm] = useState<AdListProps>({ pageNum: 1, pageSize: 20, columns: [], isDeleted: false, dataTimeMin: moment().subtract(7, 'days').format('YYYY-MM-DD'), dataTimeMax: moment().format('YYYY-MM-DD') })
  31. const [filterForm, setFilterForm] = useState<AdListProps>()
  32. const getAdList = useAjax((params) => getAdV3ListApi(params), { formatResult: true })
  33. const getPutUser = useAjax((params) => getPutUserApi(params))
  34. const delUserTag = useAjax((params) => delUserTagApi(params))
  35. const [logVisible, setLogVisible] = useState<boolean>(false)
  36. const [adgroupId, setAdgroupId] = useState<string>('')
  37. const [adgroupName, setAdgroupName] = useState<string>('')
  38. const [accountIdRule, setAccountIdRule] = useState<string>('')
  39. const [tagVisible, setTagVisible] = useState<boolean>(false)
  40. const [tagData, setTagData] = useState<any>({})
  41. const configName = '广告列表3.0'
  42. const ref = useRef(null)
  43. const size = useSize(ref)
  44. const [scrollLeft, setScrollLeft] = useState<number>(0)
  45. const [totalData, setTotalData] = useState<any>({})
  46. const [tableField, setTableField] = useState<{ title: string, dataIndex: string }[]>([])
  47. const [initialValues, setInitialValues] = useState<any>()
  48. const [trendVisible, setTrendVisible] = useState<boolean>(false)
  49. const [trendData, setTrendData] = useState<any>({})
  50. const syncBatch = useAjax((params) => syncBatchApi(params))
  51. const modifyStatusBatch = useAjax((params) => modifyStatusBatchApi(params))
  52. /************************/
  53. useEffect(() => {
  54. getList()
  55. }, [filterForm, queryForm])
  56. const getList = () => {
  57. let message = localStorage.getItem(`myAdMonitorConfig1.0.1_${configName}`)
  58. if (message) {
  59. message = JSON.parse(message)
  60. }
  61. let columns: string[] = []
  62. if (message && Array.isArray(message)) {
  63. message.forEach((item: { serverIndex: any; dataIndex: string; }) => {
  64. if (!['cz', 'cost_speed'].includes(item.dataIndex)) {
  65. columns.push(item?.serverIndex || 'adgroup_data.' + item.dataIndex)
  66. }
  67. })
  68. } else {
  69. planAdConfig.forEach((item: any) => {
  70. item?.data?.forEach((d: { default: any, serverIndex: string, dataIndex: string }) => {
  71. if (d.default && !['cz', 'cost_speed'].includes(d.dataIndex)) {
  72. columns.push(d?.serverIndex || 'adgroup_data.' + d.dataIndex)
  73. }
  74. })
  75. })
  76. }
  77. getAdList.run({ ...queryForm, ...filterForm, columns })
  78. }
  79. useUpdateEffect(() => {
  80. let data: any = {}
  81. if (getAdList.data?.data?.sumRecord) {
  82. data = getAdList.data?.data?.sumRecord
  83. }
  84. setTotalData(data)
  85. }, [getAdList.data])
  86. useEffect(() => {
  87. let localData = localStorage.getItem('myAdMonitorConfig1.0.1_广告列表3.0')
  88. let data: any[] = []
  89. if (localData) {
  90. data = JSON.parse(localData)
  91. } else {
  92. let newSelectData: any[] = [];
  93. (planAdConfig as any).forEach((item: { data: { default: any }[] }) => {
  94. item?.data?.forEach((d: { default: any }) => {
  95. if (d.default) {
  96. newSelectData[d.default - 1] = d
  97. }
  98. })
  99. })
  100. data = newSelectData
  101. }
  102. data.unshift({ title: '选择框', dataIndex: 'xzk' })
  103. data.unshift({ title: '总计', dataIndex: 'zj' })
  104. setTableField(data)
  105. }, [localStorage.getItem('myAdMonitorConfig1.0.1_广告列表3.0')])
  106. useEffect(() => {
  107. getPutUser.run({ userId })
  108. }, [userId])
  109. // 同步
  110. const sync = useCallback(() => {
  111. if (selectedRows?.length > 0) {
  112. let accountAdgroupMaps = [...new Set(selectedRows?.map(item => item.account_id + ',' + item.adgroup_id))]
  113. syncBatch.run({ accountAdgroupMaps }).then(res => {
  114. res && getAdList.refresh()
  115. res ? message.success('同步成功!') : message.error('同步失败!')
  116. })
  117. } else {
  118. message.error('请勾选')
  119. }
  120. }, [getAdList, selectedRows])
  121. // 单个启停
  122. const onChange = () => {
  123. getAdList.refresh()
  124. setSelectedRows([])
  125. }
  126. const details = (data: any) => {
  127. setDetailData(data)
  128. setDetailShow(true)
  129. }
  130. useEffect(() => {
  131. const headerBodyScroll = (e: any) => {
  132. let el = document.querySelector(`.expandClassname .expendTable .ant-table-body`);
  133. if (el) {
  134. setScrollLeft(e.target.scrollLeft)
  135. }
  136. }
  137. document.querySelector(`.expandClassname .expendTable .ant-table-body`)?.addEventListener('scroll', headerBodyScroll);
  138. () => {
  139. document.querySelector(`.expandClassname .expendTable .ant-table-body`)?.removeEventListener('scroll', headerBodyScroll);
  140. }
  141. }, [])
  142. const log = (value: any) => {
  143. setAccountIdRule(value.account_id)
  144. setAdgroupId(value.adgroup_id)
  145. setAdgroupName(value.adgroup_name)
  146. setLogVisible(true)
  147. }
  148. const handleTag = (value: any) => {
  149. setTagData(value)
  150. setTagVisible(true)
  151. }
  152. const delTag = (value: any) => {
  153. delUserTag.run({ accountId: value.account_id, adgroupId: value.adgroup_id }).then(res => {
  154. if (res) {
  155. message.success('删除成功')
  156. getAdList.refresh()
  157. }
  158. })
  159. }
  160. const handleColumnTrend = (value: string) => {
  161. let message = localStorage.getItem(`myAdMonitorConfig1.0.1_${configName}`)
  162. if (message) {
  163. message = JSON.parse(message)
  164. }
  165. let columns: string[] = []
  166. if (message && Array.isArray(message)) {
  167. message.forEach((item: { serverIndex: any; dataIndex: string; }) => {
  168. if (!['cz', 'cost_speed'].includes(item.dataIndex)) {
  169. columns.push(item?.serverIndex || 'adgroup_data.' + item.dataIndex)
  170. }
  171. })
  172. } else {
  173. planAdConfig.forEach((item: any) => {
  174. item?.data?.forEach((d: { default: any, serverIndex: string, dataIndex: string }) => {
  175. if (d.default && !['cz', 'cost_speed'].includes(d.dataIndex)) {
  176. columns.push(d?.serverIndex || 'adgroup_data.' + d.dataIndex)
  177. }
  178. })
  179. })
  180. }
  181. setTrendData({ ...queryForm, ...filterForm, columns, field: value.replace('_total', '') })
  182. setTrendVisible(true)
  183. }
  184. // 批量启停
  185. const adStatus = (type: boolean) => {
  186. let newSelectedRows = []
  187. if (type) {
  188. newSelectedRows = selectedRows.filter((item: { configuredStatus: string, adgroupId: number }) => item.configuredStatus === 'AD_STATUS_SUSPEND')
  189. } else {
  190. newSelectedRows = selectedRows.filter((item: { configuredStatus: string, adgroupId: number }) => item.configuredStatus === 'AD_STATUS_NORMAL')
  191. }
  192. if (newSelectedRows.length === 0) {
  193. message.warn(`所有广告都是${type ? '启动' : '暂停'}状态,无需${type ? '启动' : '暂停'}操作`)
  194. return
  195. }
  196. let accountAdgroupMaps = [...new Set(newSelectedRows?.map(item => item.accountId + ',' + item.adgroupId))]
  197. modifyStatusBatch.run({ accountAdgroupMaps, suspend: !type }).then(res => {
  198. message.success(`${type ? '启动' : '暂停'}成功`)
  199. getAdList.refresh()
  200. setSelectedRows([])
  201. })
  202. }
  203. const countDecimals = (num: number) => {
  204. // 匹配数字的小数部分
  205. const match = String(num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
  206. // 返回小数位数
  207. return match ? Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0)) : 0;
  208. }
  209. return <div>
  210. {/* 列表指标趋势 */}
  211. {trendVisible && <ColumnTrend visible={trendVisible} data={trendData} onClose={() => { setTrendVisible(false) }} />}
  212. {/* 打标签 */}
  213. {tagVisible && <PlanTag
  214. visible={tagVisible}
  215. data={tagData}
  216. onClose={() => setTagVisible(false)}
  217. onChange={() => {
  218. getAdList.refresh()
  219. setTagVisible(false)
  220. }}
  221. />}
  222. <Row gutter={[6, 6]} align='middle' style={{ marginBottom: 10 }}>
  223. <FilterQuery
  224. queryForm={queryForm}
  225. setQueryForm={setQueryForm}
  226. onChange={(value) => {
  227. setFilterForm({ ...value })
  228. }}
  229. initialValues={filterForm}
  230. ref={refF}
  231. />
  232. </Row>
  233. <div ref={ref} className='expandClassname'>
  234. <TableData
  235. refreshData={getList}
  236. isCard={false}
  237. className='expendTable'
  238. columns={() => tablePlanConfig(onChange, details, log, handleTag, delTag)}
  239. ajax={getAdList}
  240. syncAjax={sync}
  241. fixed={{ left: 2, right: 4 }}
  242. dataSource={getAdList?.data?.data?.records}
  243. loading={getAdList?.loading || syncBatch?.loading}
  244. scroll={{ y: 560 }}
  245. total={getAdList?.data?.data?.total}
  246. page={getAdList?.data?.data?.current}
  247. pageSize={getAdList?.data?.data?.size}
  248. myKey={'adgroup_id'}
  249. gutter={[0, 10]}
  250. config={planAdConfig}
  251. configName={configName}
  252. rowClassName={(record) => {
  253. if (record?.tag_value === 100) {
  254. return 'row_error'
  255. } else if (record?.tag_value === 90) {
  256. return 'row_warning'
  257. } else {
  258. return ''
  259. }
  260. }}
  261. leftChild={<Space direction='vertical'>
  262. <Row gutter={[10, 10]} align='middle'>
  263. <Col><Button type='primary' style={{ background: '#67c23a', borderColor: '#67c23a' }} loading={modifyStatusBatch.loading} icon={<PlayCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => adStatus(true)}>启动</Button></Col>
  264. <Col><Button type='primary' style={{ background: '#e6a23c', borderColor: '#e6a23c' }} loading={modifyStatusBatch.loading} icon={<PauseCircleOutlined />} disabled={selectedRows.length === 0} onClick={() => adStatus(false)}>暂停</Button></Col>
  265. <Col><Button type='primary' icon={<TransactionOutlined />} disabled={selectedRows.length === 0} onClick={() => setUpdate({ visible: true })}>修改出价</Button></Col>
  266. <Col><SaveSearch
  267. type='ADPLAN_SEARCH'
  268. strategyValue={JSON.stringify({
  269. queryForm,
  270. filterForm
  271. })}
  272. onChange={(value) => {
  273. let { queryForm, filterForm } = JSON.parse(value)
  274. setQueryForm(data => ({ ...queryForm, pageNum: data.pageNum, pageSize: data.pageSize }))
  275. setFilterForm(filterForm);
  276. (refF.current as any)?.onOpen(filterForm)
  277. }}
  278. /></Col>
  279. </Row>
  280. </Space>}
  281. rowSelection={{
  282. selectedRowKeys: selectedRows.map(item => item.adgroup_id.toString()),
  283. getCheckboxProps: (record: any) => ({
  284. disabled: record.status === 'STATUS_DELETED'
  285. }),
  286. onSelect: (record: { adgroup_id: number, mpName: string }, selected: boolean) => {
  287. if (selected) {
  288. selectedRows.push({ ...record })
  289. setSelectedRows([...selectedRows])
  290. } else {
  291. let newSelectAccData = selectedRows.filter((item: { adgroup_id: number }) => item.adgroup_id !== record.adgroup_id)
  292. setSelectedRows([...newSelectAccData])
  293. }
  294. },
  295. onSelectAll: (selected: boolean, selectedRowss: { adgroup_id: number }[], changeRows: { adgroup_id: number }[]) => {
  296. if (selected) {
  297. let newSelectAccData = [...selectedRows]
  298. changeRows.forEach((item: { adgroup_id: number }) => {
  299. let index = newSelectAccData.findIndex((ite: { adgroup_id: number }) => ite.adgroup_id === item.adgroup_id)
  300. if (index === -1) {
  301. newSelectAccData.push({ ...item })
  302. }
  303. })
  304. setSelectedRows([...newSelectAccData])
  305. } else {
  306. let newSelectAccData = selectedRows.filter((item: { adgroup_id: number }) => {
  307. let index = changeRows.findIndex((ite: { adgroup_id: number }) => ite.adgroup_id === item.adgroup_id)
  308. if (index !== -1) {
  309. return false
  310. } else {
  311. return true
  312. }
  313. })
  314. setSelectedRows([...newSelectAccData])
  315. }
  316. }
  317. }}
  318. onChange={(props: any) => {
  319. let { sortData, pagination } = props
  320. let { current, pageSize } = pagination
  321. let newQueryForm = JSON.parse(JSON.stringify(queryForm))
  322. newQueryForm.pageNum = current
  323. newQueryForm.pageSize = pageSize
  324. if (sortData && JSON.stringify('sortData') !== '{}') {
  325. let { field, order } = sortData // descend 降序 大到小 ascend 升序 小到大
  326. if (order) {
  327. newQueryForm.sortColumn = field
  328. newQueryForm.sortAsc = order === 'ascend'
  329. } else {
  330. Object.keys(newQueryForm).forEach(key => {
  331. if (key === 'sortColumn' || key === 'sortAsc') {
  332. delete newQueryForm[key]
  333. }
  334. })
  335. }
  336. } else {
  337. Object.keys(newQueryForm).forEach(key => {
  338. if (key === 'sortField' || key === 'sort') {
  339. delete newQueryForm[key]
  340. }
  341. })
  342. }
  343. setQueryForm({ ...newQueryForm })
  344. }}
  345. expandedRowRender={(data) => <AdExpandedRowRender data={data} scrollLeft={scrollLeft} width={size?.width} />}
  346. summary={() => (
  347. <Table.Summary fixed>
  348. <Table.Summary.Row className='s_summary'>
  349. {tableField.map((item, index) => {
  350. let data = totalData[item.dataIndex]
  351. if (item.dataIndex === 'zj') {
  352. return <Table.Summary.Cell index={index} key={item.dataIndex} align="center"><strong>总计</strong></Table.Summary.Cell>
  353. } else if (['ctr_total', 'mp_follow_rate_total',
  354. 'add_quick_app_rate_total', 'scan_follow_rate_total',
  355. 'first_day_order_roi_total', 'order_rate_total',
  356. 'order_roi_total', 'conversions_rate_total',
  357. 'income_roi124h_pla_total', 'income_roi124h_total', 'income_roi1_total', 'income_roi3_total', 'income_roi7_total', 'income_roi14_total', 'ad_monetization_roi_total',
  358. 'mini_game_income_roi1_total', 'minigame3d_income_roi_total', 'minigame7d_income_roi_total', 'mini_game_ad_monetization_roi_total', 'reg_click_rate_pla_total', 'reg_rate_total'
  359. ].includes(item.dataIndex)) {
  360. let value = (data === 0 || data) ? data : '--'
  361. return <Table.Summary.Cell index={index} key={item.dataIndex} align="center">
  362. <Space size={4}>
  363. <strong>
  364. {value !== '--' ? <Statistic value={value ? value * 100 : 0} precision={2} valueStyle={{ color: '#3f8600' }} suffix="%" /> : '--'}
  365. </strong>
  366. {value !== '--' && <a onClick={() => handleColumnTrend(item.dataIndex)}><LineChartOutlined /></a>}
  367. </Space>
  368. </Table.Summary.Cell>
  369. } else {
  370. let value = (data === 0 || data) ? countDecimals(data) > 2 ? Math.floor(data * 100) / 100 : data : '--'
  371. return <Table.Summary.Cell index={index} key={item.dataIndex} align="center">
  372. <Space size={4}>
  373. <strong><Statistic value={value} /></strong>
  374. {value !== '--' && <a onClick={() => handleColumnTrend(item.dataIndex)}><LineChartOutlined /></a>}
  375. </Space>
  376. </Table.Summary.Cell>
  377. }
  378. })}
  379. </Table.Summary.Row>
  380. </Table.Summary>
  381. )}
  382. />
  383. </div>
  384. {detailShow && <Details visible={detailShow} onClose={() => { setDetailShow(false) }} data={detailData} />}
  385. {logVisible && <RuleAccountLog accountId={accountIdRule} adgroupName={adgroupName} adgroupId={adgroupId} visible={logVisible} onClose={() => setLogVisible(false)} />}
  386. {/* 修改广告 */}
  387. {update.visible && <UpdateAd
  388. {...update}
  389. selectedRows={selectedRows.map(item => ({ ...item, accountId: item.account_id, adgroupId: item.adgroup_id }))}
  390. onChange={() => {
  391. setUpdate({ visible: false })
  392. getAdList.refresh()
  393. setSelectedRows([])
  394. }}
  395. onClose={() => { setUpdate({ visible: false }) }}
  396. />}
  397. </div>
  398. }
  399. export default AdPlanList