MStaff.Class.php 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  1. <?php
  2. /**
  3. * 员工管理Model
  4. * Created by PhpStorm.
  5. * User: 小威
  6. * Date: 2019/10/31
  7. * Time: 18:00
  8. */
  9. namespace JinDouYun\Model\Department;
  10. use JinDouYun\Dao\Customer\DCustomer;
  11. use JinDouYun\Dao\Customer\DMemberBalanceDetail;
  12. use JinDouYun\Dao\Department\DStaffComment;
  13. use JinDouYun\Dao\Department\DStaffLadder;
  14. use JinDouYun\Dao\Department\DStaffLadderRecord;
  15. use JinDouYun\Dao\Department\DStaffReflect;
  16. use JinDouYun\Dao\Department\DStaffStock;
  17. use JinDouYun\Dao\Reward\DRewardRule;
  18. use JinDouYun\Dao\Shop\DShopProject;
  19. use JinDouYun\Dao\Shop\DShopSubscribe;
  20. use JinDouYun\Model\MBaseModel;
  21. use JinDouYun\Model\System\MBasicSetup;
  22. use Mall\Framework\Core\ErrorCode;
  23. use Mall\Framework\Core\StatusCode;
  24. use Mall\Framework\Core\ResultWrapper;
  25. use Jindouyun\Cache\EnterpriseCache;
  26. use JinDouYun\Cache\RoleAclCache;
  27. use JinDouYun\Dao\Department\DStaff;
  28. use JinDouYun\Dao\UserCenter\DUserCenter;
  29. use JinDouYun\Dao\Enterprise\DUserBindEnterprise;
  30. use JinDouYun\Dao\Shop\DShopBindStaff;
  31. use JinDouYun\Dao\Department\DStaffRewardDesc;
  32. use JinDouYun\Model\Shop\MShop;
  33. use JinDouYun\Model\Department\MRole;
  34. use JinDouYun\Model\Customer\MCustomer;
  35. use JinDouYun\Model\Department\MDepartment;
  36. use JinDouYun\Model\Enterprise\MEnterprise;
  37. use JinDouYun\Model\UserCenter\MUserCenterRegister;
  38. class MStaff extends MBaseModel
  39. {
  40. private $objDStaff;
  41. private $objDUserCenter;
  42. private $objDStaffRewardDesc;
  43. private $objDUserBindEnterprise;
  44. private $objDShopBindStaff;
  45. private $enterpriseId;
  46. private $userCenterId;
  47. private $objMUserCenterRegister;
  48. private $Mbais;
  49. private $DCustomer;
  50. private $DSubscribe;
  51. private $objMenber;
  52. private $objLadder;
  53. private $objStock;
  54. public function __construct($enterpriseId = '', $userCenterId = '')
  55. {
  56. $this->enterpriseId = $enterpriseId;
  57. $this->userCenterId = $userCenterId;
  58. $this->objDStaff = new DStaff('default');
  59. $this->objDUserCenter = new DUserCenter('default');
  60. $this->objDStaffRewardDesc = new DUserCenter('default');
  61. $this->objDUserBindEnterprise = new DUserBindEnterprise('default');
  62. $this->objMUserCenterRegister = new MUserCenterRegister();
  63. $this->objDShopBindStaff = new DShopBindStaff('default');
  64. $this->objDShopBindStaff->setTable('qianniao_shop_bind_staff_' . $enterpriseId);
  65. $this->objDStaffRewardDesc->setTable('qianniao_staff_reward_desc_' . $enterpriseId);
  66. $this->objDStaff->setTable('qianniao_staff_' . $enterpriseId);
  67. $this->Mbais = new MBasicSetup($enterpriseId);
  68. $this->DCustomer = new DCustomer('default');
  69. $this->DCustomer->setTable('qianniao_customer_' . $enterpriseId);
  70. $this->DSubscribe = new DShopSubscribe('default');
  71. $this->DSubscribe->setTable('qianniao_shop_subscribe_' . $enterpriseId);
  72. $this->objMenber = new DMemberBalanceDetail('default');
  73. $this->objMenber->setTable('qianniao_member_balance_detail_'.$enterpriseId);
  74. $this->objLadder = new DStaffLadder('default');
  75. $this->objStock = new DStaffStock('default');
  76. }
  77. /**
  78. * 员工添加
  79. * @param $params
  80. * @return ResultWrapper
  81. */
  82. public function addStaff($params)
  83. {
  84. //查询userCenter
  85. $dbResult = $this->objDUserCenter->get(['mobile' => $params['mobile']]);
  86. if ($dbResult === false) {
  87. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
  88. }
  89. $user = $dbResult;
  90. unset($dbResult);
  91. //判断手机号是否存在
  92. if (!empty($user)) {
  93. $selectWhere = [
  94. 'userCenterId' => $user['id']
  95. ];
  96. //判断是否有shopId 每个商铺只能添加一个userCenter
  97. if ($params['shopId']) {
  98. $selectWhere['shopId'] = $params['shopId'];
  99. }
  100. $selectWhere['deleteStatus'] = StatusCode::$standard;
  101. $result = $this->objDStaff->get($selectWhere);
  102. if ($result === false) {
  103. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  104. }
  105. if (!empty($result)) {
  106. return ResultWrapper::fail('该手机号的员工已存在', ErrorCode::$mobileishaved);
  107. }
  108. }
  109. $params['deleteStatus'] = StatusCode::$standard;
  110. $params['createTime'] = time();
  111. $params['updateTime'] = time();
  112. $beginStatus = $this->objDUserCenter->beginTransaction();
  113. //3.未注册手机号进行注册
  114. $password = '88888888';
  115. if (empty($user)) {
  116. //添加userCenter
  117. $userCenterAddData['mobile'] = $params['mobile'];
  118. $userCenterAddData['password'] = password_hash($password, PASSWORD_DEFAULT);
  119. $userCenterAddData['deleteStatus'] = StatusCode::$standard;
  120. $userCenterAddData['source'] = StatusCode::$source['manage'];
  121. $userCenterAddData['isCustomer'] = StatusCode::$customerType['user'];
  122. $userCenterAddData['createTime'] = time();
  123. $userCenterAddData['updateTime'] = time();
  124. //添加userCenter
  125. $dbResult = $this->objDUserCenter->insert($userCenterAddData);
  126. if ($dbResult === false) {
  127. $this->objDUserCenter->rollBack();
  128. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
  129. }
  130. $params['userCenterId'] = $dbResult;
  131. $returnData['userCenterId'] = $dbResult;
  132. $returnData['title'] = '该手机号未注册, 已自动创建账号, 初始密码' . $password;
  133. unset($dbResult);
  134. } else {
  135. if ($user['isCustomer'] == StatusCode::$standard) {
  136. $updateUser = [
  137. 'password' => password_hash($password, PASSWORD_DEFAULT),
  138. 'updateTime' => time(),
  139. 'isCustomer' => StatusCode::$delete,//4:后台用户(优先级高,有密码) 5:小程序用户(优先级低, 无密码)
  140. ];
  141. $dbResult = $this->objDUserCenter->update($updateUser, ['id' => $user['id']]);
  142. if ($dbResult === false) {
  143. $this->objDUserCenter->rollBack();
  144. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
  145. }
  146. $returnData['title'] = '该手机号未注册, 已自动创建账号, 初始密码' . $password;
  147. } else {
  148. $returnData['title'] = '该手机号号已注册, 绑定成功';
  149. }
  150. $params['userCenterId'] = $user['id'];
  151. $returnData['userCenterId'] = $user['id'];
  152. }
  153. //查询绑定表
  154. $where = [
  155. 'userCenterId' => $params['userCenterId'],
  156. 'enterpriseId' => $this->enterpriseId,
  157. 'roleType' => StatusCode::$roleType['staff'],
  158. ];
  159. if (isset($params['shopId']) && !empty($params['shopId'])) {
  160. $where['shopId'] = $params['shopId'];
  161. }
  162. $result = $this->objDUserBindEnterprise->get($where);
  163. if ($result === false) {
  164. $this->objDUserCenter->rollBack();
  165. return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
  166. }
  167. if (empty($result)) {
  168. $bindData['userCenterId'] = $params['userCenterId'];
  169. $bindData['enterpriseId'] = $this->enterpriseId;
  170. $bindData['roleType'] = StatusCode::$roleType['staff'];
  171. $bindData['updateTime'] = time();
  172. $bindData['createTime'] = time();
  173. if (isset($params['shopId']) && !empty($params['shopId'])) {
  174. $bindData['shopId'] = $params['shopId'];
  175. }
  176. $dbResult = $this->objDUserBindEnterprise->insert($bindData);
  177. if ($dbResult === false) {
  178. $this->objDUserCenter->rollBack();
  179. return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
  180. }
  181. unset($dbResult);
  182. }
  183. //新增员工表
  184. $dbResult = $this->objDStaff->insert($params);
  185. if ($dbResult === false) {
  186. $this->objDUserCenter->rollBack();
  187. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  188. }
  189. $beginStatus && $this->objDUserCenter->commit();
  190. $objRoleAclCache = new RoleAclCache();
  191. $objRoleAclCache->cacheStaffIdAndUserCenterId($this->enterpriseId, $params['userCenterId'], $dbResult);
  192. $objRoleAclCache->cacheUserCenterIdAndStaffId($this->enterpriseId, $dbResult, $params['userCenterId']);
  193. return ResultWrapper::success($returnData);
  194. }
  195. /**
  196. * 员工删除
  197. * @param array $where
  198. * @return ResultWrapper
  199. */
  200. public function deleteStaff($where = [])
  201. {
  202. $where['deleteStatus'] = StatusCode::$standard;
  203. $dbResult = $this->objDStaff->get($where);
  204. if ($dbResult === false) {
  205. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  206. }
  207. $staff = $dbResult;
  208. unset($dbResult);
  209. if (empty($staff)) {
  210. return ResultWrapper::fail('员工不存在', ErrorCode::$paramError);
  211. }
  212. //查询是否有员工角色
  213. $dbResult = $this->objDUserBindEnterprise->select(['userCenterId' => $staff['userCenterId'], 'enterpriseId' => $this->enterpriseId, 'roleType' => StatusCode::$roleType['staff']]);
  214. if ($dbResult === false) {
  215. return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$paramError);
  216. }
  217. $bind = $dbResult;
  218. unset($dbResult);
  219. if (empty($bind)) {
  220. return ResultWrapper::fail('员工不存在', ErrorCode::$paramError);
  221. }
  222. //删除员工绑定企业表的关系
  223. $bindWhere = [
  224. 'userCenterId' => $staff['userCenterId'],
  225. 'enterpriseId' => $this->enterpriseId,
  226. 'roleType' => StatusCode::$roleType['staff'],
  227. 'shopId' => 0,
  228. ];
  229. if (isset($where['shopId'])) $bindWhere['shopId'] = $where['shopId'];
  230. $dbResult = $this->objDUserBindEnterprise->delete($bindWhere);
  231. if ($dbResult === false) {
  232. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  233. }
  234. $update = [
  235. 'deleteStatus' => StatusCode::$delete,
  236. 'updateTime' => time(),
  237. ];
  238. $dbResult = $this->objDStaff->update($update, $where);
  239. if ($dbResult === false) {
  240. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  241. }
  242. return ResultWrapper::success($dbResult);
  243. }
  244. /**
  245. * 获取员工信息
  246. * @param array $where
  247. * @return ResultWrapper
  248. */
  249. public function getStaffData($where = [])
  250. {
  251. $dbResult = $this->objDStaff->get($where);
  252. if ($dbResult === false) {
  253. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  254. }
  255. return ResultWrapper::success($dbResult);
  256. }
  257. /**
  258. * 获取员工信息
  259. * @param array $where
  260. * @return ResultWrapper
  261. */
  262. public function getAllStaffData($where = [])
  263. {
  264. $dbResult = $this->objDStaff->select($where);
  265. if ($dbResult === false) {
  266. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  267. }
  268. return ResultWrapper::success($dbResult);
  269. }
  270. /**
  271. * 获取员工信息
  272. * @param array $where
  273. * @return ResultWrapper
  274. */
  275. public function getAllStaffDatas($where = [])
  276. {
  277. $dbResult = $this->objDStaff->select($where);
  278. if ($dbResult === false) {
  279. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  280. }
  281. return ResultWrapper::success(self::formatList($dbResult));
  282. }
  283. /**
  284. * 员工修改
  285. * @param $params
  286. * @param $idWhere
  287. * @return ResultWrapper
  288. */
  289. public function updateStaff($params, $idWhere)
  290. {
  291. unset($params['userCenterId']);
  292. $dbResult = $this->objDStaff->get($idWhere);
  293. if ($dbResult === false) {
  294. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  295. }
  296. $staff = $dbResult;
  297. unset($dbResult);
  298. if (empty($staff)) {
  299. return ResultWrapper::fail('员工不存在', ErrorCode::$paramError);
  300. }
  301. //编辑员工不支持编辑手机号 (例:修改员工手机号 编辑了18888888888) 修改手机号需要本人登录修改
  302. /* if(isset($params['mobile']) && !empty($params['mobile'])){
  303. $dbResult = $this->objDUserCenter->get(['id' => $staff['userCenterId']]);
  304. if($dbResult === false){
  305. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$paramError);
  306. }
  307. $user = $dbResult;
  308. unset($dbResult);
  309. if($user['mobile'] != $params['mobile']){
  310. $dbResult = $this->objDUserCenter->update(['mobile' => $params['mobile']], ['id' => $staff['userCenterId']]);
  311. if($dbResult === false){
  312. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$paramError);
  313. }
  314. }
  315. }*/
  316. unset($params['mobile']);
  317. $dbResult = $this->objDStaff->update($params, $idWhere);
  318. if ($dbResult === false) {
  319. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  320. }
  321. return ResultWrapper::success($dbResult);
  322. }
  323. /**
  324. * 修改密码
  325. * @param $params
  326. * @return ResultWrapper
  327. */
  328. public function updatePassword($params)
  329. {
  330. $dbResult = $this->objDUserCenter->get(['id' => $params['id']]);
  331. if ($dbResult === false) {
  332. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
  333. }
  334. $isPassword = password_verify($params['oldPassword'], $dbResult['password']);
  335. if (!$isPassword) {
  336. return ResultWrapper::fail('旧密码错误', ErrorCode::$paramError);
  337. }
  338. $dbResult = $this->objDUserCenter->update(['password' => $params['password']], ['id' => $params['id']]);
  339. if ($dbResult === false) {
  340. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
  341. } else {
  342. return ResultWrapper::success($dbResult);
  343. }
  344. }
  345. /**
  346. * 员工列表
  347. * @param $selectParams
  348. * @return ResultWrapper
  349. */
  350. public function getAllStaff($selectParams)
  351. {
  352. $limit = $selectParams['limit'];
  353. unset($selectParams['limit']);
  354. $offset = $selectParams['offset'];
  355. unset($selectParams['offset']);
  356. $this->objDStaff->setTable('qianniao_department_role_' . $this->enterpriseId);
  357. $this->objDStaff->setTable('qianniao_staff_' . $this->enterpriseId);
  358. $fields = 's.*,r.signId,b.staffName as spread_name';
  359. $sql = 'SELECT ' . $fields . ' FROM qianniao_staff_' . $this->enterpriseId . ' AS s
  360. LEFT JOIN qianniao_department_role_' . $this->enterpriseId . ' AS r ON r.id = s.roleId
  361. LEFT JOIN qianniao_staff_' . $this->enterpriseId . ' AS b ON s.spread_uid = b.id
  362. WHERE s.deleteStatus = ' . StatusCode::$standard . ' AND s.is_shareholder = 0';
  363. if (isset($selectParams['staffName'])) {
  364. $sql .= ' AND s.staffName LIKE "%' . $selectParams['staffName'] . '%"' . ' or s.mobile LIKE "%' . $selectParams['staffName'] . '%"';
  365. }
  366. if (isset($selectParams['roleId'])) {
  367. $sql .= ' AND s.roleId =' . $selectParams['roleId'];
  368. }
  369. if (isset($selectParams['departmentId'])) {
  370. $sql .= ' AND s.departmentId =' . $selectParams['departmentId'];
  371. }
  372. if (isset($selectParams['signId']) && !empty($selectParams['signId'])) {
  373. $sql .= ' AND r.signId =' . $selectParams['signId'];
  374. }
  375. if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) {
  376. $sql .= ' AND s.shopId =' . $selectParams['shopId'];
  377. }
  378. $total = count((array)$this->objDStaff->query($sql));
  379. $sql .= ' ORDER BY createTime DESC LIMiT ' . $offset . ',' . $limit;
  380. $dbResult = $this->objDStaff->query($sql);
  381. if ($dbResult === false) {
  382. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  383. }
  384. $db = new DStaffComment('default');
  385. foreach ($dbResult as &$item)
  386. {
  387. $sql = "SELECT AVG(score) as score FROM qianniao_staff_comment WHERE uid = ".$item['id'].' and en_id = '.$this->enterpriseId;
  388. $score = $db->query($sql);
  389. $score = $score[0]['score'];
  390. if ($score){
  391. $item['evaluate'] = $score;
  392. }
  393. if ($item['spread_uid']){
  394. $staff = $this->objDStaff->get(['id' => $item['spread_uid']]);
  395. $item['spread_name'] = $staff['staffName'];
  396. }
  397. }
  398. $return = [
  399. 'data' => self::formatList($dbResult),
  400. 'total' => ($total) ? intval($total) : 0,
  401. ];
  402. if ($return === false) {
  403. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  404. } else {
  405. return ResultWrapper::success($return);
  406. }
  407. }
  408. /**
  409. * 员工详情
  410. * @param $params
  411. * @return ResultWrapper
  412. */
  413. public function getStaffInfo($params)
  414. {
  415. if (empty($params)) {
  416. return ResultWrapper::success($params);
  417. }
  418. $dbResult = $this->objDStaff->get($params);
  419. $dbResult['sold'] = $this->DSubscribe->count(['uid' => $dbResult['id'], 'paid' => 1]);
  420. $db = new DStaffComment('default');
  421. $sql = "SELECT AVG(score) as score FROM qianniao_staff_comment WHERE uid = ".$dbResult['id'].' and en_id = '.$this->enterpriseId;
  422. $score = $db->query($sql);
  423. $dbResult['evaluate'] = $score[0]['score'];
  424. if ($score){
  425. $item['evaluate'] = $score;
  426. }
  427. $dbs = new DShopSubscribe('default');
  428. $dbs->setTable('qianniao_shop_subscribe_'.$this->enterpriseId);
  429. $firstDay = strtotime(date('Y-m-01', time()));
  430. $lastDay = strtotime(date('Y-m-01', time()). ' 1 month -1 day');
  431. $count = $dbs->get([['paid', '=', 1], ['createTime', '>=', $firstDay], ['createTime', '<=', $lastDay], ['status', '=', 1], ['uid' ,'=', $dbResult['id']]], 'sum(to_price) as to_price')['to_price'];
  432. $dbResult['order_count'] = $count;
  433. if ($dbResult === false) {
  434. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  435. }
  436. if ($dbResult) {
  437. return ResultWrapper::success(self::formatInfo($dbResult));
  438. }
  439. }
  440. /**
  441. * 根据userCenterId获取员工详情
  442. * @param $userCenterId
  443. * @return ResultWrapper
  444. * @throws \Exception
  445. */
  446. public function getStaffDataByUserCenterId($userCenterId)
  447. {
  448. //获取当前用户的身份信息
  449. $dbResult = $this->objDUserBindEnterprise->get(['userCenterId' => $userCenterId, 'enterpriseId' => $this->enterpriseId]);
  450. if ($dbResult === false) {
  451. return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
  452. }
  453. $userCenterBind = $dbResult;
  454. unset($dbResult);
  455. $objMEnterprise = new MEnterprise();
  456. $modelResult = $objMEnterprise->getEnterpriseDataByEnterpriseId($this->enterpriseId);
  457. if (!$modelResult->isSuccess()) {
  458. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  459. }
  460. $enterpriseData = $modelResult->getData();
  461. unset($modelResult);
  462. $returnData = [];
  463. if ($userCenterBind['roleType'] == StatusCode::$roleType['admin']) {
  464. //管理员
  465. //管理员名称和信息就在企业信息里
  466. $returnData = [
  467. 'enterpriseId' => $this->enterpriseId,
  468. 'enterpriseLogo' => $enterpriseData['logo'],
  469. 'enterpriseName' => $enterpriseData['enterpriseName'],
  470. 'userName' => $enterpriseData['contact'],
  471. 'departmentName' => '企业管理员',
  472. 'roleName' => '企业管理员'
  473. ];
  474. } elseif ($userCenterBind['roleType'] == StatusCode::$roleType['staff']) {
  475. //员工
  476. $dbResult = $this->objDStaff->get(['userCenterId' => $userCenterId]);
  477. if ($dbResult === false) {
  478. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  479. }
  480. $result = $dbResult;
  481. unset($dbResult);
  482. $returnData = [
  483. 'enterpriseId' => $this->enterpriseId,
  484. 'enterpriseLogo' => $enterpriseData['logo'],
  485. 'enterpriseName' => $enterpriseData['enterpriseName'],
  486. 'userName' => $result['staffName'],
  487. 'departmentName' => isset($result['departmentName']) ? $result['departmentName'] : '',
  488. 'roleName' => isset($result['roleName']) ? $result['roleName'] : ''
  489. ];
  490. } elseif ($userCenterBind['roleType'] == StatusCode::$roleType['customer']) {
  491. //客户
  492. $objMCustomer = new MCustomer($this->enterpriseId, $this->userCenterId);
  493. $modelResult = $objMCustomer->getCustomerDataByUserCenterIdAndEnterpriseId($userCenterId, $this->enterpriseId);
  494. if (!$modelResult->isSuccess()) {
  495. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  496. }
  497. $result = $modelResult->getData();
  498. unset($modelResult);
  499. $returnData = [
  500. 'enterpriseId' => $this->enterpriseId,
  501. 'enterpriseLogo' => $enterpriseData['logo'],
  502. 'enterpriseName' => $enterpriseData['enterpriseName'],
  503. 'userName' => $result['name'],
  504. 'departmentName' => '企业客户',
  505. 'roleName' => '企业客户'
  506. ];
  507. }
  508. return ResultWrapper::success($returnData);
  509. }
  510. /**
  511. * 格式化员工详情
  512. * @param $data
  513. * @return mixed
  514. */
  515. public function formatInfo($data)
  516. {
  517. if (empty($data)) return $data;
  518. //取出部门id 角色id
  519. $departmentId = $data['departmentId'];
  520. $roleId = $data['roleId'];
  521. //查询部门 id 名称
  522. $MDepartment = new MDepartment($this->enterpriseId);
  523. $departmentData = $MDepartment->departmentDataByDepartmentId($departmentId);
  524. $data['departmentName'] = isset($departmentData['departmentName']) ? $departmentData['departmentName'] : '';
  525. //查询角色 id 名称
  526. $MRole = new MRole($this->enterpriseId);
  527. $roleData = $MRole->roleDataByRoleId($roleId);
  528. $data['roleName'] = isset($roleData['roleName']) ? $roleData['roleName'] : '';
  529. $data['extend'] = json_decode($data['extend'], true);
  530. $data['dataField'] = json_decode($data['dataField'], true);
  531. $data['dataField']['shopNames'] = [];
  532. if (isset($data['dataField']['shopIds'])) {
  533. $objMShop = new MShop($this->enterpriseId, $this->userCenterId);
  534. $shops = $objMShop->getShopName($data['dataField']['shopIds'], 'id,name');
  535. foreach ($shops as $shop) {
  536. $data['dataField']['shopNames'][] = $shop['name'];
  537. }
  538. }
  539. $data['dataField']['staffNames'] = [];
  540. if (isset($data['dataField']['staffIds'])) {
  541. $staffs = self::getStaffDataByStaffIds($data['dataField']['staffIds']);
  542. foreach ($staffs as $staff) {
  543. $data['dataField']['staffNames'][] = $staff['staffName'];
  544. }
  545. }
  546. //总收益
  547. $data['rewardData'] = [
  548. 'rewardTotal' => [
  549. 'total' => $data['rewardTotal'],
  550. 'order' => $data['rewardOrder'],
  551. 'goods' => $data['rewardGoods'],
  552. ]
  553. ];
  554. //查询月收益
  555. $startTime = mktime(0, 0, 0, date('m'), 1, date('Y'));
  556. $endTime = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
  557. $sql = 'select `source`,sum(amount) as total from qianniao_staff_reward_desc_' . $this->enterpriseId . ' where staffId = ' . $data['id'] . ' and type = 5 and createTime between ' . $startTime . ' and ' . $endTime . ' group by `source`';
  558. $dbResult = $this->objDStaffRewardDesc->query($sql);
  559. if ($dbResult === false) {
  560. return ResultWrapper::fail($this->objDStaffRewardDesc->error(), ErrorCode::$dberror);
  561. }
  562. $reward = [
  563. 1 => 0,
  564. 2 => 0,
  565. ];
  566. foreach ($dbResult as $value) {
  567. empty($value['total']) && $value['total'] = 0;
  568. $reward[$value['source']] = isset($reward[$value['source']]) ? $reward[$value['source']] += $value['total'] : $value['total'];
  569. }
  570. unset($dbResult);
  571. $data['rewardData']['rewardMonth'] = [
  572. 'total' => bcadd($reward[1], $reward[2]),
  573. 'order' => $reward[1],
  574. 'goods' => $reward[2]
  575. ];
  576. //查询日收益
  577. $startTime = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
  578. $endTime = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
  579. $sql = 'select `source`,sum(amount) as total from qianniao_staff_reward_desc_' . $this->enterpriseId . ' where staffId = ' . $data['id'] . ' and type = 5 and createTime between ' . $startTime . ' and ' . $endTime . ' group by `source`';
  580. $dbResult = $this->objDStaffRewardDesc->query($sql);
  581. if ($dbResult === false) {
  582. return ResultWrapper::fail($this->objDStaffRewardDesc->error(), ErrorCode::$dberror);
  583. }
  584. $reward = [
  585. 1 => 0,
  586. 2 => 0,
  587. ];
  588. foreach ($dbResult as $value) {
  589. empty($value['total']) && $value['total'] = 0;
  590. $reward[$value['source']] = isset($reward[$value['source']]) ? $reward[$value['source']] += $value['total'] : $value['total'];
  591. }
  592. $data['rewardData']['rewardDay'] = [
  593. 'total' => bcadd($reward[1], $reward[2]),
  594. 'order' => $reward[1],
  595. 'goods' => $reward[2]
  596. ];
  597. $data['staffCode'] = createCode(StatusCode::$code['staff']['prefix'], $data['id'], StatusCode::$code['staff']['length']);
  598. $data['rule'] = empty($data['rule']) ? (object)[] : json_decode($data['rule'], true);
  599. return $data;
  600. }
  601. /**
  602. * 格式化员工列表数据
  603. * @param $data
  604. * @return mixed
  605. */
  606. public function formatList(array $data)
  607. {
  608. $departmentIds = [];
  609. $roleIds = [];
  610. $userCenterIds = [];
  611. $shopIds = [];
  612. //取出部门id 角色id 商品id
  613. foreach ($data as $key => $value) {
  614. if (!in_array($value['departmentId'], $departmentIds)) {
  615. $departmentIds[] = $value['departmentId'];
  616. }
  617. if (!in_array($value['roleId'], $roleIds)) {
  618. $roleIds[] = $value['roleId'];
  619. }
  620. if (!in_array($value['shopId'], $shopIds)) {
  621. $shopIds[] = $value['shopId'];
  622. }
  623. $userCenterIds[] = $value['userCenterId'];
  624. }
  625. //查询所有部门 id 名称
  626. $MDepartment = new MDepartment($this->enterpriseId);
  627. $departmentData = $MDepartment->departmentDataByDepartmentIds($departmentIds);
  628. //映射 key = id
  629. $departmentNames = [];
  630. foreach ($departmentData as $key => $v) {
  631. $departmentNames[$v['id']] = $v['departmentName'];
  632. }
  633. //查询所有店铺id名称
  634. $MShop = new MShop($this->enterpriseId);
  635. $shopData = $MShop->getShopNameByIds($shopIds);
  636. //映射 key==id、
  637. $shopNames = [];
  638. foreach ($shopData as $key => $v) {
  639. $shopNames[$v['id']] = $v['name'];
  640. }
  641. //查询所有角色 id 名称
  642. $MRole = new MRole($this->enterpriseId);
  643. $roleData = $MRole->roleDataByRoleIds($roleIds);
  644. //映射 key = id
  645. $roleNames = [];
  646. foreach ($roleData as $key => $v) {
  647. $roleNames[$v['id']] = $v['roleName'];
  648. }
  649. //手机号
  650. $userData = [];
  651. if (!empty($userCenterIds)) {
  652. $objDUserCenter = new DUserCenter();
  653. $dbResult = $objDUserCenter->select(['id' => $userCenterIds]);
  654. if ($dbResult) {
  655. foreach ($dbResult as $value) {
  656. $userData[$value['id']] = $value['mobile'];
  657. }
  658. }
  659. }
  660. foreach ($data as &$v) {
  661. $v['departmentName'] = isset($departmentNames[$v['departmentId']]) ? $departmentNames[$v['departmentId']] : '';
  662. $v['roleName'] = isset($roleNames[$v['roleId']]) ? $roleNames[$v['roleId']] : '';
  663. $v['shopName'] = isset($shopNames[$v['shopId']]) ? $shopNames[$v['shopId']] : '';
  664. $v['extend'] = json_decode($v['extend'], true);
  665. $v['dataField'] = json_decode($v['dataField'], true);
  666. $v['staffCode'] = createCode(StatusCode::$code['staff']['prefix'], $v['id'], StatusCode::$code['staff']['length']);
  667. $v['rule'] = empty($v['rule']) ? (object)[] : json_decode($v['rule'], true);
  668. $v['mobile'] = isset($userData[$v['userCenterId']]) ? $userData[$v['userCenterId']] : '';
  669. }
  670. return $data;
  671. }
  672. /**
  673. * 根据员工ids获取员工id和员工名称
  674. * @param array $ids
  675. * @return bool|ResultWrapper
  676. */
  677. public function getStaffDataByStaffIds(array $ids)
  678. {
  679. //查询所有 id 员工名称
  680. $where = [
  681. 'id' => array_values($ids),
  682. 'deleteStatus' => StatusCode::$standard,
  683. ];
  684. $fields = 'id,staffName,mobile';
  685. $departmentData = $this->objDStaff->select($where, $fields);
  686. if ($departmentData === false) {
  687. return [];
  688. }
  689. return $departmentData;
  690. }
  691. /**
  692. * 单个业务员Id查询名称和电话
  693. * @param $staffId
  694. * @return string
  695. */
  696. public function getNameById($staffId)
  697. {
  698. $return = [];
  699. if (!$staffId) {
  700. return $return;
  701. }
  702. $sql = 'select b.mobile as userMobile, a.* from qianniao_staff_' . $this->enterpriseId . ' as a left join qianniao_user_center as b on a.userCenterId = b.id where a.id =' . $staffId;
  703. $dbResult = $this->objDStaff->query($sql);
  704. if ($dbResult === false || empty($dbResult)) {
  705. return $return;
  706. }
  707. $return = $dbResult[0];
  708. return $return;
  709. }
  710. /**
  711. * 根据userCenterId获取员工名称
  712. * @param $userCenterId
  713. * @return ResultWrapper|string
  714. */
  715. public function getStaffInfoByUserCenterId($userCenterId)
  716. {
  717. $dbResult = $this->objDStaff->get(['userCenterId' => $userCenterId], 'id,staffName');
  718. if ($dbResult === false) {
  719. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  720. }
  721. return ResultWrapper::success($dbResult);
  722. }
  723. /**
  724. * 根据多个userCenterId获取员工信息
  725. * @param $userCenterId
  726. * @return ResultWrapper
  727. */
  728. public function getStaffByUserCenterIds($userCenterId)
  729. {
  730. if (empty($userCenterId)) {
  731. return ResultWrapper::success($userCenterId);
  732. }
  733. $dbResult = $this->objDStaff->select(['userCenterId' => $userCenterId, 'deleteStatus' => StatusCode::$standard], 'userCenterId,staffName,mobile');
  734. if ($dbResult === false) {
  735. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  736. }
  737. return ResultWrapper::success($dbResult);
  738. }
  739. /**
  740. * 获取当前登录员工信息
  741. * @param $userId
  742. * @return ResultWrapper
  743. * @throws \Exception
  744. */
  745. public function getStaffByToken($userId)
  746. {
  747. //获取redis以userCenterId为key的数据
  748. //如果有数据 返回读出来的数据
  749. //如果没有数据 就去数据库里查询 把查询出来的数据保存到redis
  750. $objMEnterprise = new MEnterprise();
  751. $enterpriseInfo = $objMEnterprise->getEnterpriseByUserId($userId);
  752. $staffData = $this->objDStaff->get(['userCenterId' => $userId], 'staffName,mobile,departmentId,roleId');
  753. if ($staffData === false) {
  754. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  755. }
  756. $userInfo = [
  757. 'staffName' => $staffData['staffName'],
  758. 'mobile' => $staffData['mobile'],
  759. 'departmentId' => $staffData['departmentId'],
  760. 'roleId' => $staffData['roleId'],
  761. 'enterpriseInfo' => $enterpriseInfo,
  762. ];
  763. return ResultWrapper::success($userInfo);
  764. }
  765. /**
  766. * 根据企业id获取企业下员工总数
  767. * @param $enterpriseId
  768. * @return ResultWrapper
  769. * @throws \Exception
  770. */
  771. public function getStaffTotalByEnterpriseId($enterpriseId)
  772. {
  773. if (empty($enterpriseId)) return ResultWrapper::fail('参数为空', ErrorCode::$paramError);
  774. $cacheEnterpriseCache = new EnterpriseCache();
  775. $cacheResult = $cacheEnterpriseCache->delStaffTotalByEnterpriseId($enterpriseId);
  776. unset($cacheResult);
  777. $cacheResult = $cacheEnterpriseCache->getStaffTotalByEnterpriseId($enterpriseId);
  778. if ($cacheResult) {
  779. return ResultWrapper::success($cacheResult);
  780. }
  781. $this->objDStaff->setTable('qianniao_staff_' . $enterpriseId);
  782. $dbResult = $this->objDStaff->count(['deleteStatus' => StatusCode::$standard]);
  783. if ($dbResult === false) {
  784. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  785. }
  786. if (empty($dbResult)) {
  787. $returnData = 0;
  788. } else {
  789. $returnData = $dbResult;
  790. }
  791. unset($cacheResult);
  792. $cacheResult = $cacheEnterpriseCache->setStaffTotalByEnterpriseId($enterpriseId, $returnData);
  793. return ResultWrapper::success($returnData);
  794. }
  795. /**
  796. * 获取商铺下的员工
  797. * @param $params
  798. * @return ResultWrapper
  799. */
  800. public function getStaffByShopId($params)
  801. {
  802. $whereSql = ' and s.deleteStatus = ' . StatusCode::$standard;
  803. $sql = 'select s.*,u.mobile from qianniao_staff_' . $this->enterpriseId . ' s left join qianniao_user_center u on s.userCenterId = u.id where s.shopId = ' . $params['shopId'] . $whereSql . ' order by s.createTime ASC limit ' . $params['offset'] . ',' . $params['limit'];
  804. $dbResult = $this->objDStaff->query($sql);
  805. if ($dbResult === false) {
  806. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  807. }
  808. $data = $dbResult;
  809. unset($dbResult);
  810. $countSql = 'select count(*) as count from qianniao_staff_' . $this->enterpriseId . ' s left join qianniao_user_center u on s.userCenterId = u.id where s.shopId = ' . $params['shopId'] . $whereSql;
  811. $dbResult = $this->objDStaff->query($countSql);
  812. if ($dbResult === false) {
  813. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  814. }
  815. $count = array_shift($dbResult)['count'];
  816. $return = [
  817. 'data' => self::formatList($data),
  818. 'total' => $count
  819. ];
  820. return ResultWrapper::success($return);
  821. }
  822. /**
  823. * 提成流水
  824. * @param $selectParams
  825. * @return ResultWrapper
  826. */
  827. public function getAllStaffRewardDesc($selectParams)
  828. {
  829. $limit = $selectParams['limit'];
  830. unset($selectParams['limit']);
  831. $offset = $selectParams['offset'];
  832. unset($selectParams['offset']);
  833. $params = $selectParams;
  834. $selectParams = self::formatSqlWhere($selectParams);
  835. $dbResult = $this->objDStaffRewardDesc->select($selectParams, '*', 'createTime desc', $limit, $offset);
  836. if ($dbResult === false) {
  837. return ResultWrapper::fail($this->objDStaffRewardDesc->error(), ErrorCode::$dberror);
  838. }
  839. $countResult = $this->objDStaffRewardDesc->count($selectParams);
  840. if ($countResult === false) {
  841. return ResultWrapper::fail($this->objDStaffRewardDesc->error(), ErrorCode::$dberror);
  842. }
  843. unset($params['source']);
  844. $params['type'] = 4;
  845. $zc = $this->objDStaffRewardDesc->get(self::formatSqlWhere($params), 'sum(amount) as amount');
  846. $params['type'] = 5;
  847. $sr = $this->objDStaffRewardDesc->get(self::formatSqlWhere($params), 'sum(amount) as amount');
  848. $return = [
  849. 'data' => self::formatRewardDesc($dbResult),
  850. 'total' => ($countResult) ? intval($countResult) : 0,
  851. 'zc' => $zc,
  852. 'sr' => $sr,
  853. ];
  854. return ResultWrapper::success($return);
  855. }
  856. /**
  857. * 格式化提成流水
  858. * @param $data
  859. * @return mixed
  860. */
  861. public function formatRewardDesc($data)
  862. {
  863. $staffIds = array_column($data, 'staffId');
  864. $dbResult = $this->objDStaff->select(['id' => $staffIds]);
  865. $staff = [];
  866. if ($dbResult) {
  867. foreach ($dbResult as $value) {
  868. $staff[$value['id']] = $value;
  869. }
  870. }
  871. foreach ($data as &$value) {
  872. $value['staffName'] = isset($staff[$value['id']]) ? $staff[$value['id']]['staffName'] : '';
  873. }
  874. unset($value);
  875. return $data;
  876. }
  877. /**
  878. * 员工修改
  879. * @param $update
  880. * @param $where
  881. * @return ResultWrapper
  882. */
  883. public function updateStaffData($update, $where)
  884. {
  885. $dbResult = $this->objDStaff->get($where);
  886. if ($dbResult === false) {
  887. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  888. }
  889. $staff = $dbResult;
  890. unset($dbResult);
  891. if (isset($update['rewardGo']) && !empty($update['rewardGo'])) {
  892. $update['rewardOut'] = bcadd($staff['rewardOut'], $update['rewardGo']);
  893. $update['reward'] = bcsub($staff['reward'], $update['rewardGo']);
  894. if ($update['reward'] < 0) {
  895. return ResultWrapper::fail('余额不足', ErrorCode::$paramError);
  896. }
  897. //增加记录
  898. $insertRewardDesc = [
  899. 'userCenterId' => $staff['userCenterId'],
  900. 'staffId' => $staff['id'],
  901. 'shopId' => $staff['shopId'],
  902. 'title' => '发放提成',
  903. 'amount' => $update['rewardGo'],
  904. 'changeAmount' => $update['reward'],
  905. 'type' => StatusCode::$delete,
  906. 'source' => 4,
  907. 'createTime' => time(),
  908. 'updateTime' => time(),
  909. ];
  910. $dbResult = $this->objDStaffRewardDesc->insert($insertRewardDesc);
  911. if ($dbResult === false) {
  912. return ResultWrapper::fail($this->objDStaffRewardDesc->error(), ErrorCode::$dberror);
  913. }
  914. }
  915. unset($update['rewardGo']);
  916. $update['updateTime'] = time();
  917. $dbResult = $this->objDStaff->update($update, $where);
  918. if ($dbResult === false) {
  919. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  920. }
  921. return ResultWrapper::success($dbResult);
  922. }
  923. public function clockReward($price, $balance, $uid, $staff_id, $shopId, $rewardTotal)
  924. {
  925. $insertRewardDesc = [
  926. 'userCenterId' => $uid,
  927. 'staffId' => $staff_id,
  928. 'shopId' => $shopId,
  929. 'title' => '发放打卡提成',
  930. 'amount' => $price,
  931. 'changeAmount' => $balance,
  932. 'type' => 5,
  933. 'source' => 4,
  934. 'createTime' => time(),
  935. 'updateTime' => time(),
  936. ];
  937. $dbResult = $this->objDStaffRewardDesc->insert($insertRewardDesc);
  938. $this->objDStaff->update(['reward' => $balance, 'rewardTotal' => $rewardTotal], $staff_id);
  939. if ($dbResult === false) {
  940. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  941. }
  942. return ResultWrapper::success($dbResult);
  943. }
  944. /**
  945. * 发放员工提成
  946. * @param $data
  947. * @param $shopId
  948. * @return mixed
  949. */
  950. public function service($data, $shopId)
  951. {
  952. $this->objDStaff->beginTransaction();
  953. $commission = $this->Mbais->getBasicField('commission')->getData();
  954. $Mproject = new DShopProject('default');
  955. $project = $Mproject->select([['id', 'in', $data['project']]]);
  956. $price = 0;
  957. foreach ($project as $item){
  958. $price += $item['commission'];
  959. }
  960. // $price = $data['pay_price'] * ($commission['commission'] / 100);//提成
  961. $staff = $this->objDStaff->get(['id' => $data['uid']]);
  962. $spread_staff = $this->objDStaff->get(['id' => $staff['spread_uid']]);
  963. $balance = $staff['reward'] + $price;
  964. $rewardTotal = $staff['rewardTotal'] + $price;
  965. $insertRewardDesc = [
  966. 'userCenterId' => $staff['userCenterId'],
  967. 'staffId' => $staff['id'],
  968. 'shopId' => $shopId,
  969. 'customerId' => $data['customer_id'],
  970. 'title' => '服务项目提成',
  971. 'amount' => $price,
  972. 'originId' => $data['id'],
  973. 'changeAmount' => $balance,
  974. 'type' => 5,
  975. 'source' => 4,
  976. 'createTime' => time(),
  977. 'updateTime' => time(),
  978. ];
  979. if ($spread_staff) {
  980. $db = new MBasicSetup($this->enterpriseId);
  981. $staff_push = $db->getBasicField('staff_push')->getData();
  982. $spread_balance = $spread_staff['reward'] + ($price * ($staff_push['staff_push'] /100));
  983. $spread_rewardTotal = $spread_staff['rewardTotal'] + ($price * ($staff_push['staff_push'] /100));
  984. $insert = [
  985. 'userCenterId' => $spread_staff['userCenterId'],
  986. 'staffId' => $spread_staff['id'],
  987. 'shopId' => $shopId,
  988. 'customerId' => $data['customer_id'],
  989. 'title' => '推荐员工服务项目提成',
  990. 'amount' => $price * 0.1,
  991. 'originId' => $data['id'],
  992. 'changeAmount' => $spread_balance,
  993. 'type' => 5,
  994. 'source' => 4,
  995. 'createTime' => time(),
  996. 'updateTime' => time(),
  997. ];
  998. $res = $this->objDStaffRewardDesc->insert($insert);
  999. $this->objDStaff->update(['reward' => $spread_balance, 'rewardTotal' => $spread_rewardTotal], $spread_balance['id']);
  1000. }
  1001. $dbResult = $this->objDStaffRewardDesc->insert($insertRewardDesc);
  1002. $this->objDStaff->update(['reward' => $balance, 'rewardTotal' => $rewardTotal], $staff['id']);
  1003. if ($dbResult === false) {
  1004. $this->objDStaff->rollBack();
  1005. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  1006. }
  1007. $this->objDStaff->commit();
  1008. return ResultWrapper::success($dbResult);
  1009. }
  1010. /**
  1011. * 发放客户推荐奖
  1012. * @param $data
  1013. * @param $shopId
  1014. * @return bool
  1015. */
  1016. public function recommend($data, $shopId)
  1017. {
  1018. $customer = $this->DCustomer->get(['id' => $data['customer_id']]);
  1019. if ($customer['recommenderId'] > 0 and $customer['recommenderType'] == 3) {
  1020. $this->DCustomer->beginTransaction();
  1021. $recommender = $this->DCustomer->get(['id' => $customer['recommenderId']]); //推荐人
  1022. $count = $this->DSubscribe->count(['customer_id' => $data['customer_id']]);
  1023. $price = $data['pay_price'] - $data['cost_price'];// 利润
  1024. if ($recommender['is_shareholder'] == 1) {
  1025. $shareholder_extension = $this->Mbais->getBasicField('shareholder_extension')->getData();//股东提成
  1026. //推荐人是股东
  1027. if ($count == 1) {
  1028. //如果是第一单提成30%
  1029. $commission = $price * 0.3; //提成
  1030. $before = $recommender['memberBalance'];
  1031. $after = $recommender['memberBalance'] + $commission;
  1032. }elseif ($count > 1){
  1033. //如果是第一单提成30%
  1034. $commission = $price * ($shareholder_extension['shareholder_extension']/100); //提成
  1035. $before = $recommender['memberBalance'];
  1036. $after = $recommender['memberBalance'] + $commission;
  1037. }
  1038. } else {
  1039. //推荐人不是股东
  1040. $customer_extension = $this->Mbais->getBasicField('customer_extension')->getData();//客户提成
  1041. $commission = $price * ($customer_extension['customer_extension']/100); //提成
  1042. $before = $recommender['memberBalance'];
  1043. $after = $recommender['memberBalance'] + $commission;
  1044. }
  1045. $memberInsert = [
  1046. 'customerId' => $recommender['id'],
  1047. 'userCenterId' => $recommender['userCenterId'],
  1048. 'type' => 5,
  1049. 'purpose' => '转介绍奖励',
  1050. 'money' => $commission,
  1051. 'afterMoney' => $after,
  1052. 'beforeMoney' => $before,
  1053. 'remark' => '用户'.$customer['name'].'消费,转介绍奖励',
  1054. 'createTime' => time(),
  1055. 'updateTime' => time(),
  1056. ];
  1057. $res = $this->objMenber->insert($memberInsert);
  1058. $res1 = $this->DCustomer->update(['memberBalance' => $after], $recommender['id']);
  1059. if ($res and $res1){
  1060. $this->DCustomer->commit();
  1061. return ResultWrapper::success('成功');
  1062. }
  1063. $this->DCustomer->rollBack();
  1064. return ResultWrapper::fail('发放失败', ErrorCode::$dberror);
  1065. }
  1066. return true;
  1067. }
  1068. /**
  1069. * 发放奖励股权
  1070. * @param $id
  1071. * @return void
  1072. */
  1073. public function stock($id)
  1074. {
  1075. $db = new DStaffLadderRecord('default');
  1076. $start = strtotime( date('Y-m-01', time()));
  1077. $end = strtotime(date('Y-m-t 23:59:59', time()));
  1078. $wherein[] = ['createTime', '>=', $start];
  1079. $wherein[] = ['createTime', '<=', $end];
  1080. $wherein[] = ['uid', '=', $id];
  1081. $wherein[] = ['status', '=', 1];
  1082. $count = $this->DSubscribe->get($wherein, 'sum(to_price) as to_price');
  1083. $where = [
  1084. 'enterpriseId' => $this->enterpriseId,
  1085. ];
  1086. $ladder = $this->objLadder->select($where, '*', 'number ASC');
  1087. if ($ladder){
  1088. foreach ($ladder as &$item){
  1089. $wheres = [
  1090. ['createTime', '>=', $start],
  1091. ['createTime', '<=', $end],
  1092. ['staff_id', '=', $id],
  1093. ['ladder_id', '=', $item['id']],
  1094. ];
  1095. $record = $db->get($wheres);
  1096. if (empty($record)){
  1097. if ($count['to_price'] > $item['number']){
  1098. $staff = $this->objDStaff->get(['id'=> $id]);
  1099. $stock = $staff['cumulative_stock_right'];
  1100. $use_stock = $staff['use_stock'];
  1101. $before = $staff['use_stock'];
  1102. $stock += $item['stock'];//增加累计股权
  1103. $use_stock += $item['stock']; //增加可使用股权
  1104. $insert = [
  1105. 'en_id' => $this->enterpriseId,
  1106. 'staff_id' => $id,
  1107. 'pm' => 1,
  1108. 'number' => $item['stock'],
  1109. 'before' => $before,
  1110. 'after' => $use_stock,
  1111. 'mark' => $item['name'].'达标发放股权奖励',
  1112. ];
  1113. $this->objStock->insert($insert);
  1114. $db->insert([
  1115. 'en_id' =>$this->enterpriseId,
  1116. 'staff_id' => $id,
  1117. 'ladder_id' => $item['id'],
  1118. 'createTime' => time()
  1119. ]);
  1120. $this->objDStaff->update(['cumulative_stock_right' => $stock, 'use_stock' => $use_stock]);
  1121. }
  1122. }
  1123. }
  1124. }
  1125. }
  1126. /**
  1127. * 根据订单增加员工业绩提成
  1128. * @param int $shopId
  1129. * @param array $customer
  1130. * @param array $order
  1131. * @param array $orderGoods
  1132. * @return ResultWrapper
  1133. */
  1134. public function addStaffRewardByOrder($shopId = 0, $customer = [], $order = [], $orderGoods = [])
  1135. {
  1136. if (empty($customer['salesManId'])) {
  1137. return ResultWrapper::success(false);
  1138. }
  1139. //查询员工
  1140. $dbResult = $this->objDStaff->get(['id' => $customer['salesManId'], 'deleteStatus' => StatusCode::$standard]);
  1141. if ($dbResult === false) {
  1142. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  1143. }
  1144. $staff = $dbResult;
  1145. unset($dbResult);
  1146. if (empty($staff)) {
  1147. return ResultWrapper::success(false);
  1148. }
  1149. //查询规则
  1150. $objDRewardRule = new DRewardRule();
  1151. $objDRewardRule->setTable('qianniao_reward_rule_' . $this->enterpriseId);
  1152. $dbResult = $objDRewardRule->get(['id' => $staff['rewardRuleId'], 'enableStatus' => StatusCode::$standard, 'deleteStatus' => StatusCode::$standard], '*', 'createTime DESC');
  1153. if ($dbResult === false) {
  1154. return ResultWrapper::fail($objDRewardRule->error(), ErrorCode::$dberror);
  1155. }
  1156. $rule = $dbResult;
  1157. unset($dbResult);
  1158. if (empty($rule)) {
  1159. return ResultWrapper::success(false);
  1160. }
  1161. $ruleGoods = json_decode($rule['goods'], true);
  1162. //匹配商品
  1163. $goodsReward = 0;
  1164. $orderAmount = 0;
  1165. foreach ($orderGoods as $value) {
  1166. if (isset($ruleGoods[$value['skuId']])) {
  1167. //计算商品
  1168. if ($ruleGoods[$value['skuId']]['money'] > 0) {
  1169. $goodsReward = bcadd($goodsReward, bcmul($ruleGoods[$value['skuId']]['money'], $value['buyNum']), 2);
  1170. }
  1171. if ($rule['computed'] == StatusCode::$standard) {
  1172. $orderAmount = bcadd($orderAmount, $value['totalMoney'], 2);
  1173. }
  1174. } else {
  1175. $orderAmount = bcadd($orderAmount, $value['totalMoney'], 2);
  1176. }
  1177. }
  1178. $insertRewardDesc = [];
  1179. if ($goodsReward > 0) {
  1180. //增加记录
  1181. $insertRewardDesc[] = [
  1182. 'userCenterId' => $staff['userCenterId'],
  1183. 'customerId' => $customer['id'],
  1184. 'staffId' => $staff['id'],
  1185. 'shopId' => $shopId,
  1186. 'originId' => $order['id'],
  1187. 'originNo' => $order['no'],
  1188. 'ruleId' => $rule['id'],
  1189. 'title' => '客户购买指定商品增加提成',
  1190. 'amount' => $goodsReward,
  1191. 'changeAmount' => bcadd($staff['reward'], $goodsReward, 2),
  1192. 'type' => StatusCode::$standard,
  1193. 'source' => 2,
  1194. 'createTime' => time() - 1,
  1195. 'updateTime' => time() - 1,
  1196. ];
  1197. }
  1198. //计算订单金额
  1199. $orderReward = 0;
  1200. if ($orderAmount > 0 && $rule['percentage'] > 0) {
  1201. $orderReward = bcmul(bcdiv($orderAmount, 100), $rule['percentage'], 2);
  1202. //增加记录
  1203. $insertRewardDesc[] = [
  1204. 'userCenterId' => $staff['userCenterId'],
  1205. 'customerId' => $customer['id'],
  1206. 'staffId' => $staff['id'],
  1207. 'shopId' => $shopId,
  1208. 'originId' => $order['id'],
  1209. 'originNo' => $order['no'],
  1210. 'ruleId' => $rule['id'],
  1211. 'title' => '客户下单增加提成',
  1212. 'amount' => $orderReward,
  1213. 'changeAmount' => bcadd($staff['reward'], bcadd($orderReward, $goodsReward, 2), 2),
  1214. 'type' => StatusCode::$standard,
  1215. 'source' => 1,
  1216. 'createTime' => time(),
  1217. 'updateTime' => time(),
  1218. ];
  1219. }
  1220. //累加金额
  1221. $addReward = bcadd($orderReward, $goodsReward, 2);
  1222. //增加员工金额
  1223. if ($addReward > 0) {
  1224. $updateStaff = [
  1225. 'completed' => bcadd($staff['completed'], $order['payAmount'], 2),
  1226. 'reward' => bcadd($staff['reward'], $addReward, 2),
  1227. 'rewardOrder' => bcadd($staff['rewardOrder'], $orderReward, 2),
  1228. 'rewardGoods' => bcadd($staff['rewardGoods'], $goodsReward, 2),
  1229. 'rewardTotal' => bcadd($staff['rewardTotal'], $addReward, 2),
  1230. 'updateTime' => time(),
  1231. ];
  1232. $dbResult = $this->objDStaff->update($updateStaff, ['id' => $staff['id']]);
  1233. if ($dbResult === false) {
  1234. return ResultWrapper::fail($this->objDStaff->error(), ErrorCode::$dberror);
  1235. }
  1236. }
  1237. //保存记录
  1238. if (!empty($insertRewardDesc)) {
  1239. $dbResult = $this->objDStaffRewardDesc->insert($insertRewardDesc, true);
  1240. if ($dbResult === false) {
  1241. return ResultWrapper::fail($this->objDStaffRewardDesc->error(), ErrorCode::$dberror);
  1242. }
  1243. }
  1244. return ResultWrapper::success('执行成功');
  1245. }
  1246. public function addReflectDetail($params)
  1247. {
  1248. $staff = $this->objDStaff->get(['userCenterId' => $this->userCenterId, 'id' => $params['staffId']]);
  1249. if ($staff['reward'] < $params['money']) return ResultWrapper::fail('余额不足', ErrorCode::$notAllowAccess);
  1250. $before = $staff['reward'];
  1251. $after = $staff['reward'] - $params['money'];
  1252. $insertRewardDesc[] = [
  1253. 'userCenterId' => $staff['userCenterId'],
  1254. 'customerId' => '',
  1255. 'staffId' => $staff['id'],
  1256. 'shopId' => $staff['shopId'],
  1257. 'originId' => 0,
  1258. 'originNo' => '',
  1259. 'ruleId' => '',
  1260. 'title' => '员工提成提现',
  1261. 'amount' => $params['money'],
  1262. 'changeAmount' => $after,
  1263. 'type' => 4,
  1264. 'source' => 5,
  1265. 'createTime' => time(),
  1266. 'updateTime' => time(),
  1267. ];
  1268. $dbResult = $this->objDStaffRewardDesc->insert($insertRewardDesc, true);
  1269. $res = $this->objDStaff->update(['reward' => $after]);
  1270. $db = new DStaffReflect('default');
  1271. $res1 = $db->insert($params);
  1272. if ($dbResult === false && $res === false && $res1 === false) {
  1273. return ResultWrapper::fail($this->objDStaffRewardDesc->error(), ErrorCode::$dberror);
  1274. }
  1275. return ResultWrapper::success('申请提现成功');
  1276. }
  1277. public function exchange($number, $money, $staff)
  1278. {
  1279. $stock_before = $staff['use_stock'];
  1280. $stock_after = $staff['use_stock'] - $number;
  1281. $used_stock = $staff['used_stock'] + $number;
  1282. $reward_before = $staff['reward'];
  1283. $reward_after = $staff['reward'] + $money;
  1284. $insertRewardDesc[] = [
  1285. 'userCenterId' => $staff['userCenterId'],
  1286. 'customerId' => '',
  1287. 'staffId' => $staff['id'],
  1288. 'shopId' => $staff['shopId'],
  1289. 'originId' => 0,
  1290. 'originNo' => '',
  1291. 'ruleId' => '',
  1292. 'title' => '股权兑换提成',
  1293. 'amount' => $money,
  1294. 'changeAmount' => $reward_after,
  1295. 'type' => 4,
  1296. 'source' => 4,
  1297. 'createTime' => time(),
  1298. 'updateTime' => time(),
  1299. ];
  1300. $stockI = [
  1301. 'en_id' => $this->enterpriseId,
  1302. 'staff_id' => $staff['id'],
  1303. 'pm' => 2,
  1304. 'number' => $number,
  1305. 'before' => $stock_before,
  1306. 'after' => $stock_after,
  1307. 'mark' => '股权提现',
  1308. ];
  1309. $dbResult = $this->objDStaffRewardDesc->insert($insertRewardDesc, true);
  1310. $res = $this->objStock->insert($stockI);
  1311. $res1 = $this->objDStaff->update(['reward' => $reward_after, 'use_stock' => $stock_after, 'used_stock' => $used_stock], $staff['id']);
  1312. if ($res and $dbResult and $res1){
  1313. return true;
  1314. }
  1315. return false;
  1316. }
  1317. }