channel.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. <template>
  2. <!-- 对应页面:渠道(app) -->
  3. <view class="fix-top-window">
  4. <view class="uni-header">
  5. <uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
  6. <view class="uni-group">
  7. <view class="uni-sub-title hide-on-phone">
  8. <uni-link href="https://ask.dcloud.net.cn/article/35974"
  9. text="支持Android App多渠道统计。设置App渠道包的方法,请参考 https://ask.dcloud.net.cn/article/35974。"></uni-link>
  10. </view>
  11. </view>
  12. </view>
  13. <view class="uni-container">
  14. <view class="uni-stat--x flex p-1015">
  15. <view class="uni-stat--app-select">
  16. <uni-data-select collection="opendb-app-list" field="appid as value, name as text" orderby="text asc" :defItem="1" label="应用选择" v-model="query.appid" :clear="false" />
  17. <uni-data-select collection="opendb-app-versions" :storage="false" :where="versionQuery" class="ml-m" field="_id as value, version as text, uni_platform as label, create_date as date" format="{label} - {text}" orderby="date desc" label="版本选择" v-model="query.version_id" />
  18. </view>
  19. <uni-stat-tabs label="平台选择" type="boldLine" mode="platform-channel" :all="false" v-model="query.platform_id" @change="changePlatform" />
  20. </view>
  21. <view class="uni-stat--x flex">
  22. <uni-stat-tabs label="日期选择" :current="currentDateTab" mode="date" @change="changeTimeRange" />
  23. <uni-datetime-picker type="datetimerange" :end="new Date().getTime()" v-model="query.start_time"
  24. returnType="timestamp" :clearIcon="false" class="uni-stat-datetime-picker"
  25. :class="{'uni-stat__actived': currentDateTab < 0 && !!query.start_time.length}"
  26. @change="useDatetimePicker" />
  27. </view>
  28. <view class="uni-stat--x" style="padding: 15px 0;">
  29. <uni-stat-panel :items="panelData" class="uni-stat-panel" />
  30. <uni-stat-tabs type="box" v-model="chartTab" :tabs="chartTabs" class="mb-l" @change="changeChartTab" />
  31. <view class="uni-charts-box">
  32. <qiun-data-charts type="area" :chartData="chartData" echartsH5 echartsApp
  33. tooltipFormat="tooltipCustom" :errorMessage="errorMessage"/>
  34. </view>
  35. </view>
  36. <view class="uni-stat--x p-m">
  37. <view class="mb-m">
  38. <uni-link color="" href="https://ask.dcloud.net.cn/article/35974" text="如何自定义渠道包?"></uni-link>
  39. </view>
  40. <uni-table :loading="loading" border stripe :emptyText="errorMessage || $t('common.empty')">
  41. <uni-tr>
  42. <block v-for="(mapper, index) in fieldsMap.slice(0, fieldsMap.length-1)" :key="index">
  43. <uni-th v-if="mapper.title" :key="index" align="center">
  44. {{mapper.title}}
  45. </uni-th>
  46. </block>
  47. </uni-tr>
  48. <uni-tr v-for="(item ,i) in tableData" :key="i">
  49. <block v-for="(mapper, index) in fieldsMap.slice(0, fieldsMap.length-1)" :key="index">
  50. <uni-td v-if="mapper.title && index === 1" :key="mapper.field" class="uni-stat-edit--x">
  51. {{item[mapper.field] ? item[mapper.field] : '-'}}
  52. <uni-icons type="compose" color="#2979ff" size="25" class="uni-stat-edit--btn"
  53. @click="inputDialogToggle(item.channel_code, item.channel_name)" />
  54. </uni-td>
  55. <uni-td v-else="mapper.title" :key="mapper.field" align="center">
  56. {{item[mapper.field] !== undefined ? item[mapper.field] : '-'}}
  57. </uni-td>
  58. </block>
  59. </uni-tr>
  60. </uni-table>
  61. <view class="uni-pagination-box">
  62. <uni-pagination show-icon show-page-size :page-size="paginationOptions.pageSize"
  63. :current="paginationOptions.pageCurrent" :total="paginationOptions.total"
  64. @change="changePageCurrent" @pageSizeChange="changePageSize" />
  65. </view>
  66. </view>
  67. </view>
  68. <uni-popup ref="inputDialog" type="dialog" :maskClick="true">
  69. <uni-popup-dialog ref="inputClose" mode="input" title="请编辑名称" v-model="updateValue" placeholder="请输入内容"
  70. @confirm="editName"></uni-popup-dialog>
  71. </uni-popup>
  72. <!-- #ifndef H5 -->
  73. <fix-window />
  74. <!-- #endif -->
  75. </view>
  76. </template>
  77. <script>
  78. import {
  79. mapfields,
  80. stringifyQuery,
  81. stringifyField,
  82. stringifyGroupField,
  83. maxDeltaDay,
  84. getTimeOfSomeDayAgo,
  85. division,
  86. format,
  87. formatDate,
  88. getFieldTotal,
  89. debounce
  90. } from '@/js_sdk/uni-stat/util.js'
  91. import fieldsMap from './fieldsMap.js'
  92. export default {
  93. data() {
  94. return {
  95. // 字段映射表
  96. fieldsMap,
  97. // 查询参数
  98. query: {
  99. // 统计范围 day:按天统计,hour:按小时统计
  100. dimension: "day",
  101. // 应用id
  102. appid: '',
  103. // 平台
  104. uni_platform: 'android',
  105. // 平台id
  106. platform_id: '',
  107. // 版本号
  108. version_id: '',
  109. // 开始时间
  110. start_time: [],
  111. },
  112. // 分页数据
  113. paginationOptions: {
  114. pageSize: 20,
  115. pageCurrent: 1, // 当前页
  116. total: 0, // 数据总量
  117. },
  118. // 加载状态
  119. loading: false,
  120. // 日期选择索引
  121. currentDateTab: 1,
  122. days: 0,
  123. // 表格数据
  124. tableData: [],
  125. panelData: fieldsMap.filter(f => f.hasOwnProperty('value')),
  126. chartData: {},
  127. chartTab: 'new_device_count',
  128. queryId: '',
  129. updateValue: '',
  130. errorMessage: ""
  131. }
  132. },
  133. computed: {
  134. chartTabs() {
  135. const tabs = []
  136. fieldsMap.forEach(item => {
  137. const {
  138. field: _id,
  139. title: name
  140. } = item
  141. const isTab = item.hasOwnProperty('value')
  142. if (_id && name && isTab) {
  143. tabs.push({
  144. _id,
  145. name
  146. })
  147. }
  148. })
  149. return tabs
  150. },
  151. queryStr() {
  152. return stringifyQuery(this.query, true)
  153. },
  154. dimension() {
  155. if (maxDeltaDay(this.query.start_time, 1)) {
  156. return 'hour'
  157. } else {
  158. return 'day'
  159. }
  160. },
  161. versionQuery() {
  162. const {
  163. appid,
  164. uni_platform
  165. } = this.query
  166. const query = stringifyQuery({
  167. appid,
  168. uni_platform,
  169. type: 'native_app'
  170. })
  171. return query
  172. }
  173. },
  174. created() {
  175. this.debounceGet = debounce(() => {
  176. this.getAllData(this.queryStr);
  177. }, 300);
  178. },
  179. watch: {
  180. query: {
  181. deep: true,
  182. handler(val) {
  183. this.paginationOptions.pageCurrent = 1 // 重置分页
  184. this.debounceGet()
  185. }
  186. }
  187. },
  188. methods: {
  189. useDatetimePicker() {
  190. this.currentDateTab = -1
  191. },
  192. changePlatform(id, index, name, item) {
  193. this.query.version_id = 0
  194. this.query.uni_platform = item.code
  195. },
  196. changeTimeRange(id, index) {
  197. this.currentDateTab = index
  198. const day = 24 * 60 * 60 * 1000
  199. let start, end
  200. start = getTimeOfSomeDayAgo(id)
  201. if (!id) {
  202. end = getTimeOfSomeDayAgo(0) + day - 1
  203. } else {
  204. end = getTimeOfSomeDayAgo(0) - 1
  205. }
  206. this.query.start_time = [start, end]
  207. },
  208. changePageCurrent(e) {
  209. this.paginationOptions.pageCurrent = e.current
  210. this.getTableData()
  211. },
  212. changePageSize(pageSize) {
  213. this.paginationOptions.pageSize = pageSize
  214. this.paginationOptions.pageCurrent = 1 // 重置分页
  215. this.getTableData()
  216. },
  217. changeChartTab(id, index, name) {
  218. this.getChartData(id, name)
  219. },
  220. getAllData(query) {
  221. if (!this.query.appid){
  222. this.errorMessage = "请先选择应用";
  223. return;
  224. }
  225. this.errorMessage = "";
  226. this.getPanelData();
  227. this.getChartData();
  228. this.getTableData();
  229. },
  230. getChartData(field = this.chartTab) {
  231. // this.chartData = {}
  232. let querystr = stringifyQuery(this.query, false, ['uni_platform'])
  233. const {
  234. pageCurrent
  235. } = this.paginationOptions
  236. const db = uniCloud.database()
  237. db.collection('uni-stat-result')
  238. .where(querystr)
  239. .field(`${stringifyField(fieldsMap, field)}, start_time, channel_id`)
  240. .groupBy('channel_id,start_time')
  241. .groupField(stringifyGroupField(fieldsMap, field))
  242. .orderBy('start_time', 'asc')
  243. .get({
  244. getCount: true
  245. })
  246. .then(res => {
  247. const {
  248. count,
  249. data
  250. } = res.result
  251. const options = {
  252. categories: [],
  253. series: [{
  254. name: '暂无数据',
  255. data: []
  256. }]
  257. }
  258. const xAxis = options.categories
  259. if (this.dimension === 'hour') {
  260. for (let i = 0; i < 24; ++i) {
  261. const hour = i < 10 ? '0' + i : i
  262. const x = `${hour}:00 ~ ${hour}:59`
  263. xAxis.push(x)
  264. }
  265. }
  266. const hasChannels = []
  267. data.forEach(item => {
  268. if (hasChannels.indexOf(item.channel_id) < 0) {
  269. hasChannels.push(item.channel_id)
  270. }
  271. })
  272. // 请求所有渠道数据,与 hasChannels 匹配得出 channel_name
  273. let allChannels = []
  274. this.getChannels().then(res => {
  275. allChannels = res.result.data
  276. }).finally(() => {
  277. hasChannels.forEach((channel, index) => {
  278. // TODO 需要做个排序,暂时排序还是有问题的
  279. // allChannels = allChannels.sort((a,b)=>{ return a.channel_code.localeCompare(b.channel_code)})
  280. const c = allChannels.find(item => item._id === channel)
  281. const line = options.series[index] = {
  282. name: c && c.channel_name || '未知',
  283. data: []
  284. }
  285. if (this.dimension === 'hour') {
  286. for (let i = 0; i < 24; ++i) {
  287. line.data[i] = 0
  288. }
  289. }
  290. let mapper = fieldsMap.filter(f => f.field === field)
  291. mapper = JSON.parse(JSON.stringify(mapper))
  292. delete mapper[0].value
  293. mapper[0].formatter = ''
  294. for (const item of data) {
  295. // 将 item 根据 mapper 计算、格式化
  296. mapfields(mapper, item, item)
  297. let date = item.start_time
  298. const x = formatDate(date, this.dimension)
  299. let y = item[field]
  300. const dateIndex = xAxis.indexOf(x)
  301. if (channel === item.channel_id) {
  302. if (dateIndex < 0) {
  303. xAxis.push(x)
  304. line.data.push(y)
  305. } else {
  306. line.data[dateIndex] = y
  307. }
  308. }
  309. }
  310. })
  311. options.series = options.series.sort((a, b) => {
  312. return a.name.localeCompare(b.name)
  313. })
  314. this.chartData = options
  315. })
  316. }).catch((err) => {
  317. console.error(err)
  318. // err.message 错误信息
  319. // err.code 错误码
  320. }).finally(() => {})
  321. },
  322. getChannels() {
  323. const db = uniCloud.database()
  324. return db.collection('uni-stat-app-channels').where(stringifyQuery({
  325. appid: this.query.appid,
  326. platform_id: this.query.platform_id
  327. })).get()
  328. },
  329. getTableData() {
  330. const query = stringifyQuery(this.query, false, ['uni_platform'])
  331. const {
  332. pageCurrent
  333. } = this.paginationOptions
  334. this.loading = true
  335. const db = uniCloud.database()
  336. db.collection('uni-stat-result')
  337. .where(query)
  338. .field(`${stringifyField(fieldsMap)},appid, channel_id`)
  339. .groupBy('appid, channel_id')
  340. .groupField(stringifyGroupField(fieldsMap))
  341. .orderBy('new_device_count', 'desc')
  342. .skip((pageCurrent - 1) * this.paginationOptions.pageSize)
  343. .limit(this.paginationOptions.pageSize)
  344. .get({
  345. getCount: true
  346. })
  347. .then(res => {
  348. const {
  349. count,
  350. data
  351. } = res.result
  352. this.getChannels().then(res => {
  353. const channels = res.result.data
  354. for (const item of data) {
  355. channels.forEach(channel => {
  356. if (item.channel_id === channel._id) {
  357. item.channel_code = channel.channel_code
  358. item.channel_name = channel.channel_name
  359. }
  360. })
  361. }
  362. }).finally(() => {
  363. for (const item of data) {
  364. mapfields(fieldsMap, item, item, 'total_')
  365. }
  366. this.tableData = []
  367. this.paginationOptions.total = count
  368. this.tableData = data
  369. this.loading = false
  370. })
  371. }).catch((err) => {
  372. console.error(err)
  373. // err.message 错误信息
  374. // err.code 错误码
  375. this.loading = false
  376. })
  377. },
  378. createStr(maps, fn, prefix = 'total_') {
  379. const strArr = []
  380. maps.forEach(mapper => {
  381. if (field.hasOwnProperty('value')) {
  382. const fieldName = mapper.field
  383. strArr.push(`${fn}(${fieldName}) as ${prefix + fieldName}`)
  384. }
  385. })
  386. return strArr.join()
  387. },
  388. getPanelData() {
  389. let query = JSON.parse(JSON.stringify(this.query))
  390. query.dimension = 'day'
  391. // let query = stringifyQuery(cloneQuery)
  392. let querystr = stringifyQuery(query, false, ['uni_platform'])
  393. const db = uniCloud.database()
  394. const subTable = db.collection('uni-stat-result')
  395. .where(querystr)
  396. .field(stringifyField(fieldsMap))
  397. .groupBy('appid')
  398. .groupField(stringifyGroupField(fieldsMap))
  399. .orderBy('start_time', 'desc')
  400. .get()
  401. .then(res => {
  402. const item = res.result.data[0]
  403. item && (item.total_devices = 0)
  404. getFieldTotal.call(this, query)
  405. this.panelData = []
  406. this.panelData = mapfields(fieldsMap, item)
  407. })
  408. },
  409. inputDialogToggle(queryId, updateValue) {
  410. this.queryId = queryId
  411. this.updateValue = updateValue
  412. this.$refs.inputDialog.open()
  413. },
  414. editName(value) {
  415. // 使用 clientDB 提交数据
  416. const db = uniCloud.database()
  417. db.collection('uni-stat-app-channels')
  418. .where({
  419. channel_code: this.queryId
  420. })
  421. .update({
  422. channel_name: value
  423. })
  424. .then((res) => {
  425. uni.showToast({
  426. title: '修改成功'
  427. })
  428. this.getTableData()
  429. }).catch((err) => {
  430. uni.showModal({
  431. content: err.message || '请求服务失败',
  432. showCancel: false
  433. })
  434. }).finally(() => {
  435. uni.hideLoading()
  436. })
  437. }
  438. }
  439. }
  440. </script>
  441. <style>
  442. .uni-stat-panel {
  443. box-shadow: unset;
  444. border-bottom: 1px solid #eee;
  445. padding: 0;
  446. margin: 0 15px;
  447. }
  448. .uni-stat-edit--x {
  449. display: flex;
  450. justify-content: space-between;
  451. }
  452. .uni-stat-edit--btn {
  453. cursor: pointer;
  454. }
  455. </style>